BlueGit

ict rusty-teams

feat(appearance): light, dark, high contrast and follow-OS theme, window zoom like Teams

- Theme dropdown in Settings > Appearance (Follow operating system theme, Light, Dark, High contrast), stored locally like Teams (localStorage / host app_settings); default stays Dark
- Light palettes for Rusty Teams and Teams (Fluent teamsLightTheme tokens), one high contrast palette from Teams' contrast tokens; code/quote overlays moved into the palettes
- Follow OS reads the gpui window appearance and Windows SPI_GETHIGHCONTRAST, re-resolves on appearance changes
- Zoom via a platform wrapper (scale factor x zoom, viewport and input / zoom) for resizable normal windows; Ctrl+= / Ctrl++ / Ctrl+- / Ctrl+0, steps 50-400 %, zoom row in the own-status menu, Teams toast texts, saved in appearance.settings
- Composer and toast send icons, readable() card text colours follow the theme
- Tests: contrast check for every palette, layout_guard at a 125 % zoom step and settings dialog in light
- Deviation: zoom row lives in the own-status menu (no Settings and more menu), toast lasts 6 s instead of 3 s

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
6bb28d8a7a2593b1cf7dcdf4b2a96c9c2041d8d4
Parent
102d0207
21 files changed +2207 −275
Cargo.lock +1 −0
@@ -312,6 +312,7 @@ dependencies = [
312 312 "chatsvc",
313 313 "chrono",
314 314 "directories",
315 "futures-channel",
315 316 "futures-util",
316 317 "gpui-kit",
317 318 "image",
@@ -312,6 +312,7 @@ dependencies = [
312 "chatsvc",
312 "chatsvc",
313 "chrono",
313 "chrono",
314 "directories",
314 "directories",
315 "futures-channel",
315 "futures-util",
316 "futures-util",
316 "gpui-kit",
317 "gpui-kit",
317 "image",
318 "image",
crates/app-base/Cargo.toml +3 −2
@@ -15,6 +15,7 @@ calling.workspace = true
15 15 chatsvc.workspace = true
16 16 chrono.workspace = true
17 17 directories.workspace = true
18 futures-channel = "0.3"
18 19 futures-util = { workspace = true, features = ["io"] }
19 20 gpui-kit.workspace = true
20 21 log = "0.4"
@@ -26,13 +27,12 @@ store.workspace = true
26 27 teams-core.workspace = true
27 28 tokio.workspace = true
28 29 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
30 raw-window-handle = "0.6"
29 31
30 32 [target.'cfg(target_os = "linux")'.dependencies]
31 raw-window-handle = "0.6"
32 33 x11rb = { version = "0.13", features = ["shape"] }
33 34
34 35 [target.'cfg(windows)'.dependencies]
35 raw-window-handle = "0.6"
36 36 rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
37 37 tray-icon = { version = "0.21", default-features = false }
38 38 windows = { version = "0.62", features = [
@@ -48,6 +48,7 @@ windows = { version = "0.62", features = [
48 48 "Win32_System_Pipes",
49 49 "Win32_System_SystemInformation",
50 50 "Win32_System_Threading",
51 "Win32_UI_Accessibility",
51 52 "Win32_UI_HiDpi",
52 53 "Win32_UI_Input_KeyboardAndMouse",
53 54 "Win32_UI_Shell",
@@ -15,6 +15,7 @@ calling.workspace = true
15chatsvc.workspace = true
15chatsvc.workspace = true
16chrono.workspace = true
16chrono.workspace = true
17directories.workspace = true
17directories.workspace = true
18futures-channel = "0.3"
18futures-util = { workspace = true, features = ["io"] }
19futures-util = { workspace = true, features = ["io"] }
19gpui-kit.workspace = true
20gpui-kit.workspace = true
20log = "0.4"
21log = "0.4"
@@ -26,13 +27,12 @@ store.workspace = true
26teams-core.workspace = true
27teams-core.workspace = true
27tokio.workspace = true
28tokio.workspace = true
28image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
29image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
30raw-window-handle = "0.6"
29
31
30[target.'cfg(target_os = "linux")'.dependencies]
32[target.'cfg(target_os = "linux")'.dependencies]
31raw-window-handle = "0.6"
32x11rb = { version = "0.13", features = ["shape"] }
33x11rb = { version = "0.13", features = ["shape"] }
33
34
34[target.'cfg(windows)'.dependencies]
35[target.'cfg(windows)'.dependencies]
35raw-window-handle = "0.6"
36rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
36rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
37tray-icon = { version = "0.21", default-features = false }
37tray-icon = { version = "0.21", default-features = false }
38windows = { version = "0.62", features = [
38windows = { version = "0.62", features = [
@@ -48,6 +48,7 @@ windows = { version = "0.62", features = [
48 "Win32_System_Pipes",
48 "Win32_System_Pipes",
49 "Win32_System_SystemInformation",
49 "Win32_System_SystemInformation",
50 "Win32_System_Threading",
50 "Win32_System_Threading",
51 "Win32_UI_Accessibility",
51 "Win32_UI_HiDpi",
52 "Win32_UI_HiDpi",
52 "Win32_UI_Input_KeyboardAndMouse",
53 "Win32_UI_Input_KeyboardAndMouse",
53 "Win32_UI_Shell",
54 "Win32_UI_Shell",
crates/app-base/src/appearance.rs +188 −5
@@ -1,10 +1,16 @@
1 1 use store::Store;
2 2
3 use crate::theme::{self, ColorScheme};
3 use crate::theme::{self, ColorScheme, Shade};
4 4
5 5 const META_KEY: &str = "appearance.settings";
6 6 const COLOR_SCHEME_KEY: &str = "color_scheme";
7 7 const APP_ICON_KEY: &str = "app_icon";
8 const THEME_KEY: &str = "theme";
9 const ZOOM_KEY: &str = "zoom";
10 pub const ZOOM_STEPS: [f32; 14] = [
11 0.5, 0.67, 0.75, 0.8, 0.9, 1., 1.1, 1.25, 1.5, 1.75, 2., 2.5, 3., 4.,
12 ];
13 pub const DEFAULT_ZOOM: f32 = 1.;
8 14 const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");
9 15 const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
10 16 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
@@ -45,10 +51,71 @@ impl AppIcon {
45 51 }
46 52 }
47 53
48 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55 pub enum ThemeChoice {
56 FollowOperatingSystem,
57 Light,
58 #[default]
59 Dark,
60 HighContrast,
61 }
62
63 impl ThemeChoice {
64 pub const ALL: [ThemeChoice; 4] = [
65 ThemeChoice::FollowOperatingSystem,
66 ThemeChoice::Light,
67 ThemeChoice::Dark,
68 ThemeChoice::HighContrast,
69 ];
70
71 pub fn key(self) -> &'static str {
72 match self {
73 ThemeChoice::FollowOperatingSystem => "followOsTheme",
74 ThemeChoice::Light => "light",
75 ThemeChoice::Dark => "dark",
76 ThemeChoice::HighContrast => "contrast",
77 }
78 }
79
80 pub fn from_key(key: &str) -> Option<ThemeChoice> {
81 ThemeChoice::ALL
82 .into_iter()
83 .find(|choice| choice.key() == key)
84 }
85
86 pub fn label(self) -> &'static str {
87 match self {
88 ThemeChoice::FollowOperatingSystem => "Follow operating system theme",
89 ThemeChoice::Light => "Light",
90 ThemeChoice::Dark => "Dark",
91 ThemeChoice::HighContrast => "High contrast",
92 }
93 }
94
95 pub fn shade(self, system: SystemTheme) -> Shade {
96 match self {
97 ThemeChoice::Light => Shade::Light,
98 ThemeChoice::Dark => Shade::Dark,
99 ThemeChoice::HighContrast => Shade::HighContrast,
100 ThemeChoice::FollowOperatingSystem if system.high_contrast => Shade::HighContrast,
101 ThemeChoice::FollowOperatingSystem if system.dark => Shade::Dark,
102 ThemeChoice::FollowOperatingSystem => Shade::Light,
103 }
104 }
105 }
106
107 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
108 pub struct SystemTheme {
109 pub dark: bool,
110 pub high_contrast: bool,
111 }
112
113 #[derive(Debug, Clone, Copy, PartialEq)]
49 114 pub struct AppearanceSettings {
50 115 pub color_scheme: &'static ColorScheme,
51 116 pub app_icon: AppIcon,
117 pub theme: ThemeChoice,
118 pub zoom: f32,
52 119 }
53 120
54 121 impl Default for AppearanceSettings {
@@ -56,10 +123,64 @@ impl Default for AppearanceSettings {
56 123 AppearanceSettings {
57 124 color_scheme: theme::default_scheme(),
58 125 app_icon: AppIcon::default(),
126 theme: ThemeChoice::default(),
127 zoom: DEFAULT_ZOOM,
59 128 }
60 129 }
61 130 }
62 131
132 pub fn nearest_zoom_step(zoom: f32) -> f32 {
133 ZOOM_STEPS
134 .into_iter()
135 .min_by(|first, second| (first - zoom).abs().total_cmp(&(second - zoom).abs()))
136 .unwrap_or(DEFAULT_ZOOM)
137 }
138
139 pub fn zoom_in(zoom: f32) -> f32 {
140 ZOOM_STEPS
141 .into_iter()
142 .find(|step| *step > zoom + f32::EPSILON)
143 .unwrap_or(ZOOM_STEPS[ZOOM_STEPS.len() - 1])
144 }
145
146 pub fn zoom_out(zoom: f32) -> f32 {
147 ZOOM_STEPS
148 .into_iter()
149 .rev()
150 .find(|step| *step < zoom - f32::EPSILON)
151 .unwrap_or(ZOOM_STEPS[0])
152 }
153
154 pub fn zoom_percent(zoom: f32) -> u32 {
155 (zoom * 100. - 0.001).ceil().max(0.) as u32
156 }
157
158 #[cfg(windows)]
159 pub fn system_high_contrast() -> bool {
160 use windows::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTW};
161 use windows::Win32::UI::WindowsAndMessaging::{
162 SPI_GETHIGHCONTRAST, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
163 };
164 let mut info = HIGHCONTRASTW {
165 cbSize: std::mem::size_of::<HIGHCONTRASTW>() as u32,
166 ..Default::default()
167 };
168 let read = unsafe {
169 SystemParametersInfoW(
170 SPI_GETHIGHCONTRAST,
171 info.cbSize,
172 Some(std::ptr::from_mut(&mut info).cast()),
173 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
174 )
175 };
176 read.is_ok() && info.dwFlags.0 & HCF_HIGHCONTRASTON.0 != 0
177 }
178
179 #[cfg(not(windows))]
180 pub fn system_high_contrast() -> bool {
181 false
182 }
183
63 184 pub fn load(store: &Store) -> AppearanceSettings {
64 185 store
65 186 .meta(META_KEY)
@@ -75,9 +196,11 @@ pub fn save(store: &Store, settings: &AppearanceSettings) {
75 196
76 197 fn serialize(settings: &AppearanceSettings) -> String {
77 198 format!(
78 "{COLOR_SCHEME_KEY}={}\n{APP_ICON_KEY}={}",
199 "{COLOR_SCHEME_KEY}={}\n{APP_ICON_KEY}={}\n{THEME_KEY}={}\n{ZOOM_KEY}={}",
79 200 settings.color_scheme.id,
80 settings.app_icon.key()
201 settings.app_icon.key(),
202 settings.theme.key(),
203 settings.zoom
81 204 )
82 205 }
83 206
@@ -95,6 +218,16 @@ fn parse(text: &str) -> AppearanceSettings {
95 218 settings.app_icon = icon;
96 219 }
97 220 }
221 Some((THEME_KEY, value)) => {
222 if let Some(choice) = ThemeChoice::from_key(value) {
223 settings.theme = choice;
224 }
225 }
226 Some((ZOOM_KEY, value)) => {
227 if let Ok(zoom) = value.parse::<f32>() {
228 settings.zoom = nearest_zoom_step(zoom);
229 }
230 }
98 231 _ => {}
99 232 }
100 233 }
@@ -110,6 +243,8 @@ mod tests {
110 243 let settings = AppearanceSettings::default();
111 244 assert_eq!(settings.color_scheme.id, "rusty-teams");
112 245 assert_eq!(settings.app_icon, AppIcon::RustyTeams);
246 assert_eq!(settings.theme, ThemeChoice::Dark);
247 assert_eq!(settings.zoom, 1.);
113 248 }
114 249
115 250 #[test]
@@ -117,6 +252,8 @@ mod tests {
117 252 let settings = AppearanceSettings {
118 253 color_scheme: theme::SCHEMES[1],
119 254 app_icon: AppIcon::MicrosoftTeams,
255 theme: ThemeChoice::FollowOperatingSystem,
256 zoom: 1.25,
120 257 };
121 258 assert_eq!(parse(&serialize(&settings)), settings);
122 259 }
@@ -125,7 +262,7 @@ mod tests {
125 262 fn unknown_values_fall_back_to_defaults() {
126 263 assert_eq!(parse(""), AppearanceSettings::default());
127 264 assert_eq!(
128 parse("color_scheme=solarized\napp_icon=clippy\njunk"),
265 parse("color_scheme=solarized\napp_icon=clippy\ntheme=sepia\nzoom=big\njunk"),
129 266 AppearanceSettings::default()
130 267 );
131 268 }
@@ -137,11 +274,57 @@ mod tests {
137 274 let changed = AppearanceSettings {
138 275 color_scheme: theme::scheme_by_id("teams").unwrap(),
139 276 app_icon: AppIcon::MicrosoftTeams,
277 theme: ThemeChoice::Light,
278 zoom: 0.9,
140 279 };
141 280 save(&store, &changed);
142 281 assert_eq!(load(&store), changed);
143 282 }
144 283
284 #[test]
285 fn older_settings_without_theme_and_zoom_keep_the_dark_default() {
286 let settings = parse("color_scheme=teams\napp_icon=rusty-teams");
287 assert_eq!(settings.theme, ThemeChoice::Dark);
288 assert_eq!(settings.zoom, DEFAULT_ZOOM);
289 assert_eq!(parse("zoom=1.3").zoom, 1.25);
290 }
291
292 #[test]
293 fn follow_os_takes_dark_light_and_forced_contrast_from_the_system() {
294 let follow = ThemeChoice::FollowOperatingSystem;
295 let dark = SystemTheme {
296 dark: true,
297 high_contrast: false,
298 };
299 assert_eq!(follow.shade(dark), Shade::Dark);
300 assert_eq!(follow.shade(SystemTheme::default()), Shade::Light);
301 let forced = SystemTheme {
302 dark: false,
303 high_contrast: true,
304 };
305 assert_eq!(follow.shade(forced), Shade::HighContrast);
306 assert_eq!(ThemeChoice::Light.shade(dark), Shade::Light);
307 assert_eq!(ThemeChoice::HighContrast.shade(dark), Shade::HighContrast);
308 }
309
310 #[test]
311 fn theme_keys_are_the_teams_option_keys() {
312 let keys: Vec<_> = ThemeChoice::ALL.iter().map(|choice| choice.key()).collect();
313 assert_eq!(keys, ["followOsTheme", "light", "dark", "contrast"]);
314 }
315
316 #[test]
317 fn zoom_walks_the_steps_and_stops_at_both_ends() {
318 assert_eq!(zoom_in(1.), 1.1);
319 assert_eq!(zoom_out(1.), 0.9);
320 assert_eq!(zoom_in(4.), 4.);
321 assert_eq!(zoom_out(0.5), 0.5);
322 assert_eq!(zoom_out(zoom_in(1.25)), 1.25);
323 assert_eq!(zoom_percent(0.67), 67);
324 assert_eq!(zoom_percent(1.1), 110);
325 assert_eq!(zoom_percent(1.), 100);
326 }
327
145 328 #[test]
146 329 fn both_icons_are_png() {
147 330 for icon in AppIcon::ALL {
@@ -1,10 +1,16 @@
1use store::Store;
1use store::Store;
2
2
3use crate::theme::{self, ColorScheme};
3use crate::theme::{self, ColorScheme, Shade};
4
4
5const META_KEY: &str = "appearance.settings";
5const META_KEY: &str = "appearance.settings";
6const COLOR_SCHEME_KEY: &str = "color_scheme";
6const COLOR_SCHEME_KEY: &str = "color_scheme";
7const APP_ICON_KEY: &str = "app_icon";
7const APP_ICON_KEY: &str = "app_icon";
8const THEME_KEY: &str = "theme";
9const ZOOM_KEY: &str = "zoom";
10pub const ZOOM_STEPS: [f32; 14] = [
11 0.5, 0.67, 0.75, 0.8, 0.9, 1., 1.1, 1.25, 1.5, 1.75, 2., 2.5, 3., 4.,
12];
13pub const DEFAULT_ZOOM: f32 = 1.;
8const 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");
9const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
15const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
10 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
16 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
@@ -45,10 +51,71 @@ impl AppIcon {
45 }
51 }
46}
52}
47
53
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub enum ThemeChoice {
56 FollowOperatingSystem,
57 Light,
58 #[default]
59 Dark,
60 HighContrast,
61}
62
63impl ThemeChoice {
64 pub const ALL: [ThemeChoice; 4] = [
65 ThemeChoice::FollowOperatingSystem,
66 ThemeChoice::Light,
67 ThemeChoice::Dark,
68 ThemeChoice::HighContrast,
69 ];
70
71 pub fn key(self) -> &'static str {
72 match self {
73 ThemeChoice::FollowOperatingSystem => "followOsTheme",
74 ThemeChoice::Light => "light",
75 ThemeChoice::Dark => "dark",
76 ThemeChoice::HighContrast => "contrast",
77 }
78 }
79
80 pub fn from_key(key: &str) -> Option<ThemeChoice> {
81 ThemeChoice::ALL
82 .into_iter()
83 .find(|choice| choice.key() == key)
84 }
85
86 pub fn label(self) -> &'static str {
87 match self {
88 ThemeChoice::FollowOperatingSystem => "Follow operating system theme",
89 ThemeChoice::Light => "Light",
90 ThemeChoice::Dark => "Dark",
91 ThemeChoice::HighContrast => "High contrast",
92 }
93 }
94
95 pub fn shade(self, system: SystemTheme) -> Shade {
96 match self {
97 ThemeChoice::Light => Shade::Light,
98 ThemeChoice::Dark => Shade::Dark,
99 ThemeChoice::HighContrast => Shade::HighContrast,
100 ThemeChoice::FollowOperatingSystem if system.high_contrast => Shade::HighContrast,
101 ThemeChoice::FollowOperatingSystem if system.dark => Shade::Dark,
102 ThemeChoice::FollowOperatingSystem => Shade::Light,
103 }
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
108pub struct SystemTheme {
109 pub dark: bool,
110 pub high_contrast: bool,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq)]
49pub struct AppearanceSettings {
114pub struct AppearanceSettings {
50 pub color_scheme: &'static ColorScheme,
115 pub color_scheme: &'static ColorScheme,
51 pub app_icon: AppIcon,
116 pub app_icon: AppIcon,
117 pub theme: ThemeChoice,
118 pub zoom: f32,
52}
119}
53
120
54impl Default for AppearanceSettings {
121impl Default for AppearanceSettings {
@@ -56,10 +123,64 @@ impl Default for AppearanceSettings {
56 AppearanceSettings {
123 AppearanceSettings {
57 color_scheme: theme::default_scheme(),
124 color_scheme: theme::default_scheme(),
58 app_icon: AppIcon::default(),
125 app_icon: AppIcon::default(),
126 theme: ThemeChoice::default(),
127 zoom: DEFAULT_ZOOM,
59 }
128 }
60 }
129 }
61}
130}
62
131
132pub fn nearest_zoom_step(zoom: f32) -> f32 {
133 ZOOM_STEPS
134 .into_iter()
135 .min_by(|first, second| (first - zoom).abs().total_cmp(&(second - zoom).abs()))
136 .unwrap_or(DEFAULT_ZOOM)
137}
138
139pub fn zoom_in(zoom: f32) -> f32 {
140 ZOOM_STEPS
141 .into_iter()
142 .find(|step| *step > zoom + f32::EPSILON)
143 .unwrap_or(ZOOM_STEPS[ZOOM_STEPS.len() - 1])
144}
145
146pub fn zoom_out(zoom: f32) -> f32 {
147 ZOOM_STEPS
148 .into_iter()
149 .rev()
150 .find(|step| *step < zoom - f32::EPSILON)
151 .unwrap_or(ZOOM_STEPS[0])
152}
153
154pub fn zoom_percent(zoom: f32) -> u32 {
155 (zoom * 100. - 0.001).ceil().max(0.) as u32
156}
157
158#[cfg(windows)]
159pub fn system_high_contrast() -> bool {
160 use windows::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTW};
161 use windows::Win32::UI::WindowsAndMessaging::{
162 SPI_GETHIGHCONTRAST, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
163 };
164 let mut info = HIGHCONTRASTW {
165 cbSize: std::mem::size_of::<HIGHCONTRASTW>() as u32,
166 ..Default::default()
167 };
168 let read = unsafe {
169 SystemParametersInfoW(
170 SPI_GETHIGHCONTRAST,
171 info.cbSize,
172 Some(std::ptr::from_mut(&mut info).cast()),
173 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
174 )
175 };
176 read.is_ok() && info.dwFlags.0 & HCF_HIGHCONTRASTON.0 != 0
177}
178
179#[cfg(not(windows))]
180pub fn system_high_contrast() -> bool {
181 false
182}
183
63pub fn load(store: &Store) -> AppearanceSettings {
184pub fn load(store: &Store) -> AppearanceSettings {
64 store
185 store
65 .meta(META_KEY)
186 .meta(META_KEY)
@@ -75,9 +196,11 @@ pub fn save(store: &Store, settings: &AppearanceSettings) {
75
196
76fn serialize(settings: &AppearanceSettings) -> String {
197fn serialize(settings: &AppearanceSettings) -> String {
77 format!(
198 format!(
78 "{COLOR_SCHEME_KEY}={}\n{APP_ICON_KEY}={}",
199 "{COLOR_SCHEME_KEY}={}\n{APP_ICON_KEY}={}\n{THEME_KEY}={}\n{ZOOM_KEY}={}",
79 settings.color_scheme.id,
200 settings.color_scheme.id,
80 settings.app_icon.key()
201 settings.app_icon.key(),
202 settings.theme.key(),
203 settings.zoom
81 )
204 )
82}
205}
83
206
@@ -95,6 +218,16 @@ fn parse(text: &str) -> AppearanceSettings {
95 settings.app_icon = icon;
218 settings.app_icon = icon;
96 }
219 }
97 }
220 }
221 Some((THEME_KEY, value)) => {
222 if let Some(choice) = ThemeChoice::from_key(value) {
223 settings.theme = choice;
224 }
225 }
226 Some((ZOOM_KEY, value)) => {
227 if let Ok(zoom) = value.parse::<f32>() {
228 settings.zoom = nearest_zoom_step(zoom);
229 }
230 }
98 _ => {}
231 _ => {}
99 }
232 }
100 }
233 }
@@ -110,6 +243,8 @@ mod tests {
110 let settings = AppearanceSettings::default();
243 let settings = AppearanceSettings::default();
111 assert_eq!(settings.color_scheme.id, "rusty-teams");
244 assert_eq!(settings.color_scheme.id, "rusty-teams");
112 assert_eq!(settings.app_icon, AppIcon::RustyTeams);
245 assert_eq!(settings.app_icon, AppIcon::RustyTeams);
246 assert_eq!(settings.theme, ThemeChoice::Dark);
247 assert_eq!(settings.zoom, 1.);
113 }
248 }
114
249
115 #[test]
250 #[test]
@@ -117,6 +252,8 @@ mod tests {
117 let settings = AppearanceSettings {
252 let settings = AppearanceSettings {
118 color_scheme: theme::SCHEMES[1],
253 color_scheme: theme::SCHEMES[1],
119 app_icon: AppIcon::MicrosoftTeams,
254 app_icon: AppIcon::MicrosoftTeams,
255 theme: ThemeChoice::FollowOperatingSystem,
256 zoom: 1.25,
120 };
257 };
121 assert_eq!(parse(&serialize(&settings)), settings);
258 assert_eq!(parse(&serialize(&settings)), settings);
122 }
259 }
@@ -125,7 +262,7 @@ mod tests {
125 fn unknown_values_fall_back_to_defaults() {
262 fn unknown_values_fall_back_to_defaults() {
126 assert_eq!(parse(""), AppearanceSettings::default());
263 assert_eq!(parse(""), AppearanceSettings::default());
127 assert_eq!(
264 assert_eq!(
128 parse("color_scheme=solarized\napp_icon=clippy\njunk"),
265 parse("color_scheme=solarized\napp_icon=clippy\ntheme=sepia\nzoom=big\njunk"),
129 AppearanceSettings::default()
266 AppearanceSettings::default()
130 );
267 );
131 }
268 }
@@ -137,11 +274,57 @@ mod tests {
137 let changed = AppearanceSettings {
274 let changed = AppearanceSettings {
138 color_scheme: theme::scheme_by_id("teams").unwrap(),
275 color_scheme: theme::scheme_by_id("teams").unwrap(),
139 app_icon: AppIcon::MicrosoftTeams,
276 app_icon: AppIcon::MicrosoftTeams,
277 theme: ThemeChoice::Light,
278 zoom: 0.9,
140 };
279 };
141 save(&store, &changed);
280 save(&store, &changed);
142 assert_eq!(load(&store), changed);
281 assert_eq!(load(&store), changed);
143 }
282 }
144
283
284 #[test]
285 fn older_settings_without_theme_and_zoom_keep_the_dark_default() {
286 let settings = parse("color_scheme=teams\napp_icon=rusty-teams");
287 assert_eq!(settings.theme, ThemeChoice::Dark);
288 assert_eq!(settings.zoom, DEFAULT_ZOOM);
289 assert_eq!(parse("zoom=1.3").zoom, 1.25);
290 }
291
292 #[test]
293 fn follow_os_takes_dark_light_and_forced_contrast_from_the_system() {
294 let follow = ThemeChoice::FollowOperatingSystem;
295 let dark = SystemTheme {
296 dark: true,
297 high_contrast: false,
298 };
299 assert_eq!(follow.shade(dark), Shade::Dark);
300 assert_eq!(follow.shade(SystemTheme::default()), Shade::Light);
301 let forced = SystemTheme {
302 dark: false,
303 high_contrast: true,
304 };
305 assert_eq!(follow.shade(forced), Shade::HighContrast);
306 assert_eq!(ThemeChoice::Light.shade(dark), Shade::Light);
307 assert_eq!(ThemeChoice::HighContrast.shade(dark), Shade::HighContrast);
308 }
309
310 #[test]
311 fn theme_keys_are_the_teams_option_keys() {
312 let keys: Vec<_> = ThemeChoice::ALL.iter().map(|choice| choice.key()).collect();
313 assert_eq!(keys, ["followOsTheme", "light", "dark", "contrast"]);
314 }
315
316 #[test]
317 fn zoom_walks_the_steps_and_stops_at_both_ends() {
318 assert_eq!(zoom_in(1.), 1.1);
319 assert_eq!(zoom_out(1.), 0.9);
320 assert_eq!(zoom_in(4.), 4.);
321 assert_eq!(zoom_out(0.5), 0.5);
322 assert_eq!(zoom_out(zoom_in(1.25)), 1.25);
323 assert_eq!(zoom_percent(0.67), 67);
324 assert_eq!(zoom_percent(1.1), 110);
325 assert_eq!(zoom_percent(1.), 100);
326 }
327
145 #[test]
328 #[test]
146 fn both_icons_are_png() {
329 fn both_icons_are_png() {
147 for icon in AppIcon::ALL {
330 for icon in AppIcon::ALL {
crates/app-base/src/lib.rs +1 −0
@@ -36,5 +36,6 @@ pub mod translation;
36 36 pub mod updater;
37 37 pub mod user_activity;
38 38 pub mod version;
39 pub mod zoom;
39 40
40 41 pub const APP_NAME: &str = "Rusty Teams";
@@ -36,5 +36,6 @@ pub mod translation;
36pub mod updater;
36pub mod updater;
37pub mod user_activity;
37pub mod user_activity;
38pub mod version;
38pub mod version;
39pub mod zoom;
39
40
40pub const APP_NAME: &str = "Rusty Teams";
41pub const APP_NAME: &str = "Rusty Teams";
crates/app-base/src/theme.rs +127 −119
@@ -7,8 +7,9 @@ use gpui_kit::*;
7 7 mod schemes;
8 8
9 9 pub use schemes::{
10 ColorScheme, SCHEMES, active_scheme as scheme, default_scheme, scheme_by_id, set_active_scheme,
11 set_thread_scheme,
10 ColorScheme, HIGH_CONTRAST, Palette, SCHEMES, Shade, active_palette as palette,
11 active_scheme as scheme, active_shade as shade, default_scheme, palettes, scheme_by_id,
12 set_active_scheme, set_active_shade, set_thread_scheme, set_thread_shade,
12 13 };
13 14
14 15 const FONT_FAMILY: &str = "Google Sans Flex";
@@ -22,13 +23,6 @@ const FONT_FILES: [&[u8]; 4] = [
22 23 ];
23 24
24 25 const WHITE: u32 = 0xffffff;
25 const CODE_SURFACE: u32 = 0x0000003d;
26 const CODE_HEADER_BORDER: u32 = 0xffffff0f;
27 const INLINE_CODE_FILL: u32 = 0xffffff14;
28 const INLINE_CODE_FILL_OWN: u32 = 0x0000003d;
29 const QUOTE_FILL: u32 = 0x00000052;
30 const INLINE_CODE_BORDER: u32 = 0xffffff1a;
31 const TABLE_HEADER: u32 = 0xffffff0d;
32 26 const CLOSE_BUTTON_ICON: u32 = 0xffffff;
33 27
34 28 pub fn color(hex: u32) -> Hsla {
@@ -53,7 +47,12 @@ pub fn apply(cx: &mut App) {
53 47 .iter()
54 48 .find(|family| installed.iter().any(|name| name == *family))
55 49 .map(|family| SharedString::from(*family));
56 Theme::change(ThemeMode::Dark, None, cx);
50 let mode = if palette().shade.is_dark() {
51 ThemeMode::Dark
52 } else {
53 ThemeMode::Light
54 };
55 Theme::change(mode, None, cx);
57 56 Theme::update(cx, |theme| {
58 57 theme.font_family = FONT_FAMILY.into();
59 58 theme.font_size = px(BASE_FONT_SIZE);
@@ -62,65 +61,65 @@ pub fn apply(cx: &mut App) {
62 61 }
63 62 theme.radius_lg = px(10.);
64 63 let colors = &mut theme.colors;
65 colors.background = color(scheme().background);
66 colors.foreground = color(scheme().foreground);
67 colors.border = color(scheme().border);
68 colors.muted = color(scheme().border);
69 colors.muted_foreground = color(scheme().text_muted);
70 colors.sidebar = color(scheme().surface);
71 colors.sidebar_foreground = color(scheme().foreground);
72 colors.sidebar_border = color(scheme().border);
73 colors.sidebar_accent = color(scheme().popup_hover);
74 colors.sidebar_accent_foreground = color(scheme().foreground);
75 colors.sidebar_primary = color(scheme().accent);
76 colors.popover = color(scheme().popup);
77 colors.popover_foreground = color(scheme().foreground);
78 colors.accent = color(scheme().surface_raised);
79 colors.accent_foreground = color(scheme().foreground);
80 colors.secondary = color(scheme().surface_raised);
81 colors.secondary_hover = color(scheme().border_strong);
82 colors.secondary_active = color(scheme().border_strong);
83 colors.secondary_foreground = color(scheme().foreground);
84 colors.primary = color(scheme().accent);
85 colors.primary_hover = color(scheme().accent_text);
86 colors.primary_active = color(scheme().accent_strong);
87 colors.primary_foreground = color(scheme().on_accent);
88 colors.link = color(scheme().accent_text);
89 colors.link_hover = color(scheme().accent_soft);
90 colors.link_active = color(scheme().accent_strong);
91 colors.ring = color(scheme().accent);
92 colors.caret = color(scheme().accent);
93 colors.input = color(scheme().border_strong);
94 colors.selection = color_with_alpha(scheme().selection);
95 colors.title_bar = color(scheme().background);
96 colors.title_bar_border = color(scheme().border);
97 colors.status_bar = color(scheme().background);
98 colors.status_bar_border = color(scheme().border);
99 colors.success = color(scheme().green);
100 colors.warning = color(scheme().amber);
101 colors.danger = color(scheme().close_button_hover);
102 colors.danger_active = color(scheme().close_button_pressed);
64 colors.background = color(palette().background);
65 colors.foreground = color(palette().foreground);
66 colors.border = color(palette().border);
67 colors.muted = color(palette().border);
68 colors.muted_foreground = color(palette().text_muted);
69 colors.sidebar = color(palette().surface);
70 colors.sidebar_foreground = color(palette().foreground);
71 colors.sidebar_border = color(palette().border);
72 colors.sidebar_accent = color(palette().popup_hover);
73 colors.sidebar_accent_foreground = color(palette().foreground);
74 colors.sidebar_primary = color(palette().accent);
75 colors.popover = color(palette().popup);
76 colors.popover_foreground = color(palette().foreground);
77 colors.accent = color(palette().surface_raised);
78 colors.accent_foreground = color(palette().foreground);
79 colors.secondary = color(palette().surface_raised);
80 colors.secondary_hover = color(palette().border_strong);
81 colors.secondary_active = color(palette().border_strong);
82 colors.secondary_foreground = color(palette().foreground);
83 colors.primary = color(palette().accent);
84 colors.primary_hover = color(palette().accent_text);
85 colors.primary_active = color(palette().accent_strong);
86 colors.primary_foreground = color(palette().on_accent);
87 colors.link = color(palette().accent_text);
88 colors.link_hover = color(palette().accent_soft);
89 colors.link_active = color(palette().accent_strong);
90 colors.ring = color(palette().accent);
91 colors.caret = color(palette().accent);
92 colors.input = color(palette().border_strong);
93 colors.selection = color_with_alpha(palette().selection);
94 colors.title_bar = color(palette().background);
95 colors.title_bar_border = color(palette().border);
96 colors.status_bar = color(palette().background);
97 colors.status_bar_border = color(palette().border);
98 colors.success = color(palette().green);
99 colors.warning = color(palette().amber);
100 colors.danger = color(palette().close_button_hover);
101 colors.danger_active = color(palette().close_button_pressed);
103 102 colors.danger_foreground = color(CLOSE_BUTTON_ICON);
104 colors.drop_target = color_with_alpha(scheme().drop_background);
105 colors.window_border = color(scheme().border);
106 colors.scrollbar_thumb = color(scheme().border_strong);
107 colors.scrollbar_thumb_hover = color(scheme().text_faint);
108 colors.list = color(scheme().background);
109 colors.list_hover = color(scheme().row_hover);
110 colors.list_active = color(scheme().surface_raised);
103 colors.drop_target = color_with_alpha(palette().drop_background);
104 colors.window_border = color(palette().border);
105 colors.scrollbar_thumb = color(palette().border_strong);
106 colors.scrollbar_thumb_hover = color(palette().text_faint);
107 colors.list = color(palette().background);
108 colors.list_hover = color(palette().row_hover);
109 colors.list_active = color(palette().surface_raised);
111 110 });
112 111 cx.set_global(elevation_tokens());
113 112 }
114 113
115 114 fn elevation_tokens() -> ElevationTokens {
116 115 let flyout = Elevation {
117 fill: color(scheme().popup),
118 hover: color(scheme().popup_hover),
116 fill: color(palette().popup),
117 hover: color(palette().popup_hover),
119 118 shadow: elevation::shadow16(),
120 119 };
121 120 let nested_flyout = Elevation {
122 fill: color(scheme().popup_nested),
123 hover: color(scheme().popup_nested_hover),
121 fill: color(palette().popup_nested),
122 hover: color(palette().popup_nested_hover),
124 123 shadow: elevation::shadow16(),
125 124 };
126 125 ElevationTokens {
@@ -149,7 +148,7 @@ pub fn toast_shadow() -> Vec<BoxShadow> {
149 148 }
150 149
151 150 pub fn popup_nested() -> Hsla {
152 color(scheme().popup_nested)
151 color(palette().popup_nested)
153 152 }
154 153
155 154 pub trait ElevatedSurface: Styled + Sized {
@@ -177,99 +176,99 @@ pub fn font_family() -> SharedString {
177 176 }
178 177
179 178 pub fn background() -> Hsla {
180 color(scheme().background)
179 color(palette().background)
181 180 }
182 181
183 182 pub fn background_hex() -> u32 {
184 scheme().background
183 palette().background
185 184 }
186 185
187 186 pub fn toast_mention_fill() -> Hsla {
188 color(scheme().toast_mention)
187 color(palette().toast_mention)
189 188 }
190 189
191 190 pub fn surface() -> Hsla {
192 color(scheme().surface)
191 color(palette().surface)
193 192 }
194 193
195 194 pub fn surface_raised() -> Hsla {
196 color(scheme().surface_raised)
195 color(palette().surface_raised)
197 196 }
198 197
199 198 pub fn row_hover() -> Hsla {
200 color(scheme().row_hover)
199 color(palette().row_hover)
201 200 }
202 201
203 202 pub fn popup() -> Hsla {
204 color(scheme().popup)
203 color(palette().popup)
205 204 }
206 205
207 206 pub fn popup_hover() -> Hsla {
208 color(scheme().popup_hover)
207 color(palette().popup_hover)
209 208 }
210 209
211 210 pub fn reply_surface() -> Hsla {
212 color(scheme().reply_surface)
211 color(palette().reply_surface)
213 212 }
214 213
215 214 pub fn border() -> Hsla {
216 color(scheme().border)
215 color(palette().border)
217 216 }
218 217
219 218 pub fn selection() -> Hsla {
220 color_with_alpha(scheme().selection)
219 color_with_alpha(palette().selection)
221 220 }
222 221
223 222 pub fn border_strong() -> Hsla {
224 color(scheme().border_strong)
223 color(palette().border_strong)
225 224 }
226 225
227 226 pub fn text() -> Hsla {
228 color(scheme().foreground)
227 color(palette().foreground)
229 228 }
230 229
231 230 pub fn text_strong() -> Hsla {
232 color(scheme().text_strong)
231 color(palette().text_strong)
233 232 }
234 233
235 234 pub fn text_soft() -> Hsla {
236 color(scheme().text_soft)
235 color(palette().text_soft)
237 236 }
238 237
239 238 pub fn text_muted() -> Hsla {
240 color(scheme().text_muted)
239 color(palette().text_muted)
241 240 }
242 241
243 242 pub fn text_faint() -> Hsla {
244 color(scheme().text_faint)
243 color(palette().text_faint)
245 244 }
246 245
247 246 pub fn accent() -> Hsla {
248 color(scheme().accent)
247 color(palette().accent)
249 248 }
250 249
251 250 pub fn accent_text() -> Hsla {
252 color(scheme().accent_text)
251 color(palette().accent_text)
253 252 }
254 253
255 254 pub fn accent_soft() -> Hsla {
256 color(scheme().accent_soft)
255 color(palette().accent_soft)
257 256 }
258 257
259 258 pub fn on_accent() -> Hsla {
260 color(scheme().on_accent)
259 color(palette().on_accent)
261 260 }
262 261
263 262 pub fn bubble_own() -> Hsla {
264 color(scheme().bubble_own)
263 color(palette().bubble_own)
265 264 }
266 265
267 266 pub fn bubble_other() -> Hsla {
268 color(scheme().bubble_other)
267 color(palette().bubble_other)
269 268 }
270 269
271 270 pub fn reaction_on_own() -> Hsla {
272 color(scheme().reaction_on_own)
271 color(palette().reaction_on_own)
273 272 }
274 273
275 274 pub fn white() -> Hsla {
@@ -278,113 +277,114 @@ pub fn white() -> Hsla {
278 277
279 278 pub fn mention_background(own: bool) -> Hsla {
280 279 color(if own {
281 scheme().mention_background_own
280 palette().mention_background_own
282 281 } else {
283 scheme().mention_background
282 palette().mention_background
284 283 })
285 284 }
286 285
287 286 pub fn own_meta() -> Hsla {
288 color(scheme().own_meta)
287 color(palette().own_meta)
289 288 }
290 289
291 290 pub fn own_read() -> Hsla {
292 color(scheme().own_read)
291 color(palette().own_read)
293 292 }
294 293
295 294 pub fn mention_text() -> Hsla {
296 color(scheme().accent_soft)
295 color(palette().accent_soft)
297 296 }
298 297
299 298 pub fn drop_background() -> Hsla {
300 color_with_alpha(scheme().drop_background)
299 color_with_alpha(palette().drop_background)
301 300 }
302 301
303 302 pub fn code_surface() -> Hsla {
304 color_with_alpha(CODE_SURFACE)
303 color_with_alpha(palette().code_surface)
305 304 }
306 305
307 306 pub fn code_header_border() -> Hsla {
308 color_with_alpha(CODE_HEADER_BORDER)
307 color_with_alpha(palette().code_header_border)
309 308 }
310 309
311 310 pub fn inline_code_fill(own: bool) -> Hsla {
312 311 color_with_alpha(if own {
313 INLINE_CODE_FILL_OWN
312 palette().inline_code_fill_own
314 313 } else {
315 INLINE_CODE_FILL
314 palette().inline_code_fill
316 315 })
317 316 }
318 317
319 318 pub fn quote_fill() -> Hsla {
320 color_with_alpha(QUOTE_FILL)
319 color_with_alpha(palette().quote_fill)
321 320 }
322 321
323 322 pub fn inline_code_border() -> Hsla {
324 color_with_alpha(INLINE_CODE_BORDER)
323 color_with_alpha(palette().inline_code_border)
325 324 }
326 325
327 326 pub fn table_header() -> Hsla {
328 color_with_alpha(TABLE_HEADER)
327 color_with_alpha(palette().table_header)
329 328 }
330 329
331 330 pub fn rule(own: bool) -> Hsla {
332 331 if own {
333 color(scheme().rule_own)
332 color(palette().rule_own)
334 333 } else {
335 334 border_strong()
336 335 }
337 336 }
338 337
339 338 pub fn badge_muted() -> Hsla {
340 color(scheme().badge_muted)
339 color(palette().badge_muted)
341 340 }
342 341
343 342 pub fn green() -> Hsla {
344 color(scheme().green)
343 color(palette().green)
345 344 }
346 345
347 346 pub fn red() -> Hsla {
348 color(scheme().red)
347 color(palette().red)
349 348 }
350 349
351 350 pub fn red_soft() -> Hsla {
352 color(scheme().red_soft)
351 color(palette().red_soft)
353 352 }
354 353
355 354 pub fn red_tint() -> Hsla {
356 color(scheme().red_tint)
355 color(palette().red_tint)
357 356 }
358 357
359 358 pub fn amber() -> Hsla {
360 color(scheme().amber)
359 color(palette().amber)
361 360 }
362 361
363 362 pub fn out_of_office() -> Hsla {
364 color(scheme().out_of_office)
363 color(palette().out_of_office)
365 364 }
366 365
367 366 pub fn meeting_avatar() -> Hsla {
368 color(scheme().meeting_avatar)
367 color(palette().meeting_avatar)
369 368 }
370 369
371 370 pub fn bot_avatar() -> Hsla {
372 color(scheme().bot_avatar)
371 color(palette().bot_avatar)
373 372 }
374 373
375 374 pub fn avatar_color(index: usize) -> Hsla {
376 let palette = scheme().avatar_palette;
375 let palette = palette().avatar_palette;
377 376 color(palette[index % palette.len()])
378 377 }
379 378
380 379 pub fn avatar_palette_len() -> usize {
381 scheme().avatar_palette.len()
380 palette().avatar_palette.len()
382 381 }
383 382
384 383 #[cfg(test)]
385 384 mod tests {
386 385 use super::{
387 SCHEMES, avatar_color, avatar_palette_len, color, elevation_tokens, set_thread_scheme,
386 SCHEMES, Shade, avatar_color, avatar_palette_len, color, elevation_tokens,
387 set_thread_scheme, set_thread_shade,
388 388 };
389 389
390 390 #[test]
@@ -396,17 +396,25 @@ mod tests {
396 396 #[test]
397 397 fn flyout_over_a_dialog_takes_a_lighter_fill_than_the_dialog() {
398 398 for scheme in SCHEMES {
399 set_thread_scheme(Some(scheme.id));
400 let tokens = elevation_tokens();
401 assert_eq!(tokens.dialog.fill, color(scheme.popup));
402 assert_eq!(tokens.flyout_at(0).fill, color(scheme.popup));
403 let nested = tokens.flyout_at(1);
404 assert_eq!(nested.fill, color(scheme.popup_nested));
405 assert!(nested.fill.l > tokens.dialog.fill.l);
406 assert!(nested.hover.l > nested.fill.l);
407 assert_ne!(nested.fill, color(scheme.popup_hover));
399 for shade in Shade::ALL {
400 set_thread_scheme(Some(scheme.id));
401 set_thread_shade(Some(shade));
402 let palette = scheme.palette(shade);
403 let tokens = elevation_tokens();
404 assert_eq!(tokens.dialog.fill, color(palette.popup));
405 assert_eq!(tokens.flyout_at(0).fill, color(palette.popup));
406 let nested = tokens.flyout_at(1);
407 assert_eq!(nested.fill, color(palette.popup_nested));
408 assert_ne!(nested.hover, nested.fill);
409 if shade == Shade::Dark {
410 assert!(nested.fill.l > tokens.dialog.fill.l);
411 assert!(nested.hover.l > nested.fill.l);
412 assert_ne!(nested.fill, color(palette.popup_hover));
413 }
414 }
408 415 }
409 416 set_thread_scheme(None);
417 set_thread_shade(None);
410 418 }
411 419
412 420 #[test]
@@ -7,8 +7,9 @@ use gpui_kit::*;
7mod schemes;
7mod schemes;
8
8
9pub use schemes::{
9pub use schemes::{
10 ColorScheme, SCHEMES, active_scheme as scheme, default_scheme, scheme_by_id, set_active_scheme,
10 ColorScheme, HIGH_CONTRAST, Palette, SCHEMES, Shade, active_palette as palette,
11 set_thread_scheme,
11 active_scheme as scheme, active_shade as shade, default_scheme, palettes, scheme_by_id,
12 set_active_scheme, set_active_shade, set_thread_scheme, set_thread_shade,
12};
13};
13
14
14const FONT_FAMILY: &str = "Google Sans Flex";
15const FONT_FAMILY: &str = "Google Sans Flex";
@@ -22,13 +23,6 @@ const FONT_FILES: [&[u8]; 4] = [
22];
23];
23
24
24const WHITE: u32 = 0xffffff;
25const WHITE: u32 = 0xffffff;
25const CODE_SURFACE: u32 = 0x0000003d;
26const CODE_HEADER_BORDER: u32 = 0xffffff0f;
27const INLINE_CODE_FILL: u32 = 0xffffff14;
28const INLINE_CODE_FILL_OWN: u32 = 0x0000003d;
29const QUOTE_FILL: u32 = 0x00000052;
30const INLINE_CODE_BORDER: u32 = 0xffffff1a;
31const TABLE_HEADER: u32 = 0xffffff0d;
32const CLOSE_BUTTON_ICON: u32 = 0xffffff;
26const CLOSE_BUTTON_ICON: u32 = 0xffffff;
33
27
34pub fn color(hex: u32) -> Hsla {
28pub fn color(hex: u32) -> Hsla {
@@ -53,7 +47,12 @@ pub fn apply(cx: &mut App) {
53 .iter()
47 .iter()
54 .find(|family| installed.iter().any(|name| name == *family))
48 .find(|family| installed.iter().any(|name| name == *family))
55 .map(|family| SharedString::from(*family));
49 .map(|family| SharedString::from(*family));
56 Theme::change(ThemeMode::Dark, None, cx);
50 let mode = if palette().shade.is_dark() {
51 ThemeMode::Dark
52 } else {
53 ThemeMode::Light
54 };
55 Theme::change(mode, None, cx);
57 Theme::update(cx, |theme| {
56 Theme::update(cx, |theme| {
58 theme.font_family = FONT_FAMILY.into();
57 theme.font_family = FONT_FAMILY.into();
59 theme.font_size = px(BASE_FONT_SIZE);
58 theme.font_size = px(BASE_FONT_SIZE);
@@ -62,65 +61,65 @@ pub fn apply(cx: &mut App) {
62 }
61 }
63 theme.radius_lg = px(10.);
62 theme.radius_lg = px(10.);
64 let colors = &mut theme.colors;
63 let colors = &mut theme.colors;
65 colors.background = color(scheme().background);
64 colors.background = color(palette().background);
66 colors.foreground = color(scheme().foreground);
65 colors.foreground = color(palette().foreground);
67 colors.border = color(scheme().border);
66 colors.border = color(palette().border);
68 colors.muted = color(scheme().border);
67 colors.muted = color(palette().border);
69 colors.muted_foreground = color(scheme().text_muted);
68 colors.muted_foreground = color(palette().text_muted);
70 colors.sidebar = color(scheme().surface);
69 colors.sidebar = color(palette().surface);
71 colors.sidebar_foreground = color(scheme().foreground);
70 colors.sidebar_foreground = color(palette().foreground);
72 colors.sidebar_border = color(scheme().border);
71 colors.sidebar_border = color(palette().border);
73 colors.sidebar_accent = color(scheme().popup_hover);
72 colors.sidebar_accent = color(palette().popup_hover);
74 colors.sidebar_accent_foreground = color(scheme().foreground);
73 colors.sidebar_accent_foreground = color(palette().foreground);
75 colors.sidebar_primary = color(scheme().accent);
74 colors.sidebar_primary = color(palette().accent);
76 colors.popover = color(scheme().popup);
75 colors.popover = color(palette().popup);
77 colors.popover_foreground = color(scheme().foreground);
76 colors.popover_foreground = color(palette().foreground);
78 colors.accent = color(scheme().surface_raised);
77 colors.accent = color(palette().surface_raised);
79 colors.accent_foreground = color(scheme().foreground);
78 colors.accent_foreground = color(palette().foreground);
80 colors.secondary = color(scheme().surface_raised);
79 colors.secondary = color(palette().surface_raised);
81 colors.secondary_hover = color(scheme().border_strong);
80 colors.secondary_hover = color(palette().border_strong);
82 colors.secondary_active = color(scheme().border_strong);
81 colors.secondary_active = color(palette().border_strong);
83 colors.secondary_foreground = color(scheme().foreground);
82 colors.secondary_foreground = color(palette().foreground);
84 colors.primary = color(scheme().accent);
83 colors.primary = color(palette().accent);
85 colors.primary_hover = color(scheme().accent_text);
84 colors.primary_hover = color(palette().accent_text);
86 colors.primary_active = color(scheme().accent_strong);
85 colors.primary_active = color(palette().accent_strong);
87 colors.primary_foreground = color(scheme().on_accent);
86 colors.primary_foreground = color(palette().on_accent);
88 colors.link = color(scheme().accent_text);
87 colors.link = color(palette().accent_text);
89 colors.link_hover = color(scheme().accent_soft);
88 colors.link_hover = color(palette().accent_soft);
90 colors.link_active = color(scheme().accent_strong);
89 colors.link_active = color(palette().accent_strong);
91 colors.ring = color(scheme().accent);
90 colors.ring = color(palette().accent);
92 colors.caret = color(scheme().accent);
91 colors.caret = color(palette().accent);
93 colors.input = color(scheme().border_strong);
92 colors.input = color(palette().border_strong);
94 colors.selection = color_with_alpha(scheme().selection);
93 colors.selection = color_with_alpha(palette().selection);
95 colors.title_bar = color(scheme().background);
94 colors.title_bar = color(palette().background);
96 colors.title_bar_border = color(scheme().border);
95 colors.title_bar_border = color(palette().border);
97 colors.status_bar = color(scheme().background);
96 colors.status_bar = color(palette().background);
98 colors.status_bar_border = color(scheme().border);
97 colors.status_bar_border = color(palette().border);
99 colors.success = color(scheme().green);
98 colors.success = color(palette().green);
100 colors.warning = color(scheme().amber);
99 colors.warning = color(palette().amber);
101 colors.danger = color(scheme().close_button_hover);
100 colors.danger = color(palette().close_button_hover);
102 colors.danger_active = color(scheme().close_button_pressed);
101 colors.danger_active = color(palette().close_button_pressed);
103 colors.danger_foreground = color(CLOSE_BUTTON_ICON);
102 colors.danger_foreground = color(CLOSE_BUTTON_ICON);
104 colors.drop_target = color_with_alpha(scheme().drop_background);
103 colors.drop_target = color_with_alpha(palette().drop_background);
105 colors.window_border = color(scheme().border);
104 colors.window_border = color(palette().border);
106 colors.scrollbar_thumb = color(scheme().border_strong);
105 colors.scrollbar_thumb = color(palette().border_strong);
107 colors.scrollbar_thumb_hover = color(scheme().text_faint);
106 colors.scrollbar_thumb_hover = color(palette().text_faint);
108 colors.list = color(scheme().background);
107 colors.list = color(palette().background);
109 colors.list_hover = color(scheme().row_hover);
108 colors.list_hover = color(palette().row_hover);
110 colors.list_active = color(scheme().surface_raised);
109 colors.list_active = color(palette().surface_raised);
111 });
110 });
112 cx.set_global(elevation_tokens());
111 cx.set_global(elevation_tokens());
113}
112}
114
113
115fn elevation_tokens() -> ElevationTokens {
114fn elevation_tokens() -> ElevationTokens {
116 let flyout = Elevation {
115 let flyout = Elevation {
117 fill: color(scheme().popup),
116 fill: color(palette().popup),
118 hover: color(scheme().popup_hover),
117 hover: color(palette().popup_hover),
119 shadow: elevation::shadow16(),
118 shadow: elevation::shadow16(),
120 };
119 };
121 let nested_flyout = Elevation {
120 let nested_flyout = Elevation {
122 fill: color(scheme().popup_nested),
121 fill: color(palette().popup_nested),
123 hover: color(scheme().popup_nested_hover),
122 hover: color(palette().popup_nested_hover),
124 shadow: elevation::shadow16(),
123 shadow: elevation::shadow16(),
125 };
124 };
126 ElevationTokens {
125 ElevationTokens {
@@ -149,7 +148,7 @@ pub fn toast_shadow() -> Vec<BoxShadow> {
149}
148}
150
149
151pub fn popup_nested() -> Hsla {
150pub fn popup_nested() -> Hsla {
152 color(scheme().popup_nested)
151 color(palette().popup_nested)
153}
152}
154
153
155pub trait ElevatedSurface: Styled + Sized {
154pub trait ElevatedSurface: Styled + Sized {
@@ -177,99 +176,99 @@ pub fn font_family() -> SharedString {
177}
176}
178
177
179pub fn background() -> Hsla {
178pub fn background() -> Hsla {
180 color(scheme().background)
179 color(palette().background)
181}
180}
182
181
183pub fn background_hex() -> u32 {
182pub fn background_hex() -> u32 {
184 scheme().background
183 palette().background
185}
184}
186
185
187pub fn toast_mention_fill() -> Hsla {
186pub fn toast_mention_fill() -> Hsla {
188 color(scheme().toast_mention)
187 color(palette().toast_mention)
189}
188}
190
189
191pub fn surface() -> Hsla {
190pub fn surface() -> Hsla {
192 color(scheme().surface)
191 color(palette().surface)
193}
192}
194
193
195pub fn surface_raised() -> Hsla {
194pub fn surface_raised() -> Hsla {
196 color(scheme().surface_raised)
195 color(palette().surface_raised)
197}
196}
198
197
199pub fn row_hover() -> Hsla {
198pub fn row_hover() -> Hsla {
200 color(scheme().row_hover)
199 color(palette().row_hover)
201}
200}
202
201
203pub fn popup() -> Hsla {
202pub fn popup() -> Hsla {
204 color(scheme().popup)
203 color(palette().popup)
205}
204}
206
205
207pub fn popup_hover() -> Hsla {
206pub fn popup_hover() -> Hsla {
208 color(scheme().popup_hover)
207 color(palette().popup_hover)
209}
208}
210
209
211pub fn reply_surface() -> Hsla {
210pub fn reply_surface() -> Hsla {
212 color(scheme().reply_surface)
211 color(palette().reply_surface)
213}
212}
214
213
215pub fn border() -> Hsla {
214pub fn border() -> Hsla {
216 color(scheme().border)
215 color(palette().border)
217}
216}
218
217
219pub fn selection() -> Hsla {
218pub fn selection() -> Hsla {
220 color_with_alpha(scheme().selection)
219 color_with_alpha(palette().selection)
221}
220}
222
221
223pub fn border_strong() -> Hsla {
222pub fn border_strong() -> Hsla {
224 color(scheme().border_strong)
223 color(palette().border_strong)
225}
224}
226
225
227pub fn text() -> Hsla {
226pub fn text() -> Hsla {
228 color(scheme().foreground)
227 color(palette().foreground)
229}
228}
230
229
231pub fn text_strong() -> Hsla {
230pub fn text_strong() -> Hsla {
232 color(scheme().text_strong)
231 color(palette().text_strong)
233}
232}
234
233
235pub fn text_soft() -> Hsla {
234pub fn text_soft() -> Hsla {
236 color(scheme().text_soft)
235 color(palette().text_soft)
237}
236}
238
237
239pub fn text_muted() -> Hsla {
238pub fn text_muted() -> Hsla {
240 color(scheme().text_muted)
239 color(palette().text_muted)
241}
240}
242
241
243pub fn text_faint() -> Hsla {
242pub fn text_faint() -> Hsla {
244 color(scheme().text_faint)
243 color(palette().text_faint)
245}
244}
246
245
247pub fn accent() -> Hsla {
246pub fn accent() -> Hsla {
248 color(scheme().accent)
247 color(palette().accent)
249}
248}
250
249
251pub fn accent_text() -> Hsla {
250pub fn accent_text() -> Hsla {
252 color(scheme().accent_text)
251 color(palette().accent_text)
253}
252}
254
253
255pub fn accent_soft() -> Hsla {
254pub fn accent_soft() -> Hsla {
256 color(scheme().accent_soft)
255 color(palette().accent_soft)
257}
256}
258
257
259pub fn on_accent() -> Hsla {
258pub fn on_accent() -> Hsla {
260 color(scheme().on_accent)
259 color(palette().on_accent)
261}
260}
262
261
263pub fn bubble_own() -> Hsla {
262pub fn bubble_own() -> Hsla {
264 color(scheme().bubble_own)
263 color(palette().bubble_own)
265}
264}
266
265
267pub fn bubble_other() -> Hsla {
266pub fn bubble_other() -> Hsla {
268 color(scheme().bubble_other)
267 color(palette().bubble_other)
269}
268}
270
269
271pub fn reaction_on_own() -> Hsla {
270pub fn reaction_on_own() -> Hsla {
272 color(scheme().reaction_on_own)
271 color(palette().reaction_on_own)
273}
272}
274
273
275pub fn white() -> Hsla {
274pub fn white() -> Hsla {
@@ -278,113 +277,114 @@ pub fn white() -> Hsla {
278
277
279pub fn mention_background(own: bool) -> Hsla {
278pub fn mention_background(own: bool) -> Hsla {
280 color(if own {
279 color(if own {
281 scheme().mention_background_own
280 palette().mention_background_own
282 } else {
281 } else {
283 scheme().mention_background
282 palette().mention_background
284 })
283 })
285}
284}
286
285
287pub fn own_meta() -> Hsla {
286pub fn own_meta() -> Hsla {
288 color(scheme().own_meta)
287 color(palette().own_meta)
289}
288}
290
289
291pub fn own_read() -> Hsla {
290pub fn own_read() -> Hsla {
292 color(scheme().own_read)
291 color(palette().own_read)
293}
292}
294
293
295pub fn mention_text() -> Hsla {
294pub fn mention_text() -> Hsla {
296 color(scheme().accent_soft)
295 color(palette().accent_soft)
297}
296}
298
297
299pub fn drop_background() -> Hsla {
298pub fn drop_background() -> Hsla {
300 color_with_alpha(scheme().drop_background)
299 color_with_alpha(palette().drop_background)
301}
300}
302
301
303pub fn code_surface() -> Hsla {
302pub fn code_surface() -> Hsla {
304 color_with_alpha(CODE_SURFACE)
303 color_with_alpha(palette().code_surface)
305}
304}
306
305
307pub fn code_header_border() -> Hsla {
306pub fn code_header_border() -> Hsla {
308 color_with_alpha(CODE_HEADER_BORDER)
307 color_with_alpha(palette().code_header_border)
309}
308}
310
309
311pub fn inline_code_fill(own: bool) -> Hsla {
310pub fn inline_code_fill(own: bool) -> Hsla {
312 color_with_alpha(if own {
311 color_with_alpha(if own {
313 INLINE_CODE_FILL_OWN
312 palette().inline_code_fill_own
314 } else {
313 } else {
315 INLINE_CODE_FILL
314 palette().inline_code_fill
316 })
315 })
317}
316}
318
317
319pub fn quote_fill() -> Hsla {
318pub fn quote_fill() -> Hsla {
320 color_with_alpha(QUOTE_FILL)
319 color_with_alpha(palette().quote_fill)
321}
320}
322
321
323pub fn inline_code_border() -> Hsla {
322pub fn inline_code_border() -> Hsla {
324 color_with_alpha(INLINE_CODE_BORDER)
323 color_with_alpha(palette().inline_code_border)
325}
324}
326
325
327pub fn table_header() -> Hsla {
326pub fn table_header() -> Hsla {
328 color_with_alpha(TABLE_HEADER)
327 color_with_alpha(palette().table_header)
329}
328}
330
329
331pub fn rule(own: bool) -> Hsla {
330pub fn rule(own: bool) -> Hsla {
332 if own {
331 if own {
333 color(scheme().rule_own)
332 color(palette().rule_own)
334 } else {
333 } else {
335 border_strong()
334 border_strong()
336 }
335 }
337}
336}
338
337
339pub fn badge_muted() -> Hsla {
338pub fn badge_muted() -> Hsla {
340 color(scheme().badge_muted)
339 color(palette().badge_muted)
341}
340}
342
341
343pub fn green() -> Hsla {
342pub fn green() -> Hsla {
344 color(scheme().green)
343 color(palette().green)
345}
344}
346
345
347pub fn red() -> Hsla {
346pub fn red() -> Hsla {
348 color(scheme().red)
347 color(palette().red)
349}
348}
350
349
351pub fn red_soft() -> Hsla {
350pub fn red_soft() -> Hsla {
352 color(scheme().red_soft)
351 color(palette().red_soft)
353}
352}
354
353
355pub fn red_tint() -> Hsla {
354pub fn red_tint() -> Hsla {
356 color(scheme().red_tint)
355 color(palette().red_tint)
357}
356}
358
357
359pub fn amber() -> Hsla {
358pub fn amber() -> Hsla {
360 color(scheme().amber)
359 color(palette().amber)
361}
360}
362
361
363pub fn out_of_office() -> Hsla {
362pub fn out_of_office() -> Hsla {
364 color(scheme().out_of_office)
363 color(palette().out_of_office)
365}
364}
366
365
367pub fn meeting_avatar() -> Hsla {
366pub fn meeting_avatar() -> Hsla {
368 color(scheme().meeting_avatar)
367 color(palette().meeting_avatar)
369}
368}
370
369
371pub fn bot_avatar() -> Hsla {
370pub fn bot_avatar() -> Hsla {
372 color(scheme().bot_avatar)
371 color(palette().bot_avatar)
373}
372}
374
373
375pub fn avatar_color(index: usize) -> Hsla {
374pub fn avatar_color(index: usize) -> Hsla {
376 let palette = scheme().avatar_palette;
375 let palette = palette().avatar_palette;
377 color(palette[index % palette.len()])
376 color(palette[index % palette.len()])
378}
377}
379
378
380pub fn avatar_palette_len() -> usize {
379pub fn avatar_palette_len() -> usize {
381 scheme().avatar_palette.len()
380 palette().avatar_palette.len()
382}
381}
383
382
384#[cfg(test)]
383#[cfg(test)]
385mod tests {
384mod tests {
386 use super::{
385 use super::{
387 SCHEMES, avatar_color, avatar_palette_len, color, elevation_tokens, set_thread_scheme,
386 SCHEMES, Shade, avatar_color, avatar_palette_len, color, elevation_tokens,
387 set_thread_scheme, set_thread_shade,
388 };
388 };
389
389
390 #[test]
390 #[test]
@@ -396,17 +396,25 @@ mod tests {
396 #[test]
396 #[test]
397 fn flyout_over_a_dialog_takes_a_lighter_fill_than_the_dialog() {
397 fn flyout_over_a_dialog_takes_a_lighter_fill_than_the_dialog() {
398 for scheme in SCHEMES {
398 for scheme in SCHEMES {
399 set_thread_scheme(Some(scheme.id));
399 for shade in Shade::ALL {
400 let tokens = elevation_tokens();
400 set_thread_scheme(Some(scheme.id));
401 assert_eq!(tokens.dialog.fill, color(scheme.popup));
401 set_thread_shade(Some(shade));
402 assert_eq!(tokens.flyout_at(0).fill, color(scheme.popup));
402 let palette = scheme.palette(shade);
403 let nested = tokens.flyout_at(1);
403 let tokens = elevation_tokens();
404 assert_eq!(nested.fill, color(scheme.popup_nested));
404 assert_eq!(tokens.dialog.fill, color(palette.popup));
405 assert!(nested.fill.l > tokens.dialog.fill.l);
405 assert_eq!(tokens.flyout_at(0).fill, color(palette.popup));
406 assert!(nested.hover.l > nested.fill.l);
406 let nested = tokens.flyout_at(1);
407 assert_ne!(nested.fill, color(scheme.popup_hover));
407 assert_eq!(nested.fill, color(palette.popup_nested));
408 assert_ne!(nested.hover, nested.fill);
409 if shade == Shade::Dark {
410 assert!(nested.fill.l > tokens.dialog.fill.l);
411 assert!(nested.hover.l > nested.fill.l);
412 assert_ne!(nested.fill, color(palette.popup_hover));
413 }
414 }
408 }
415 }
409 set_thread_scheme(None);
416 set_thread_scheme(None);
417 set_thread_shade(None);
410 }
418 }
411
419
412 #[test]
420 #[test]
crates/app-base/src/theme/schemes.rs +492 −103
@@ -1,10 +1,41 @@
1 1 use std::cell::Cell;
2 use std::sync::atomic::{AtomicUsize, Ordering};
2 use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
3
4 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
5 pub enum Shade {
6 #[default]
7 Dark,
8 Light,
9 HighContrast,
10 }
11
12 impl Shade {
13 pub const ALL: [Shade; 3] = [Shade::Dark, Shade::Light, Shade::HighContrast];
14
15 pub fn is_dark(self) -> bool {
16 !matches!(self, Shade::Light)
17 }
18
19 fn index(self) -> u8 {
20 match self {
21 Shade::Dark => 0,
22 Shade::Light => 1,
23 Shade::HighContrast => 2,
24 }
25 }
26
27 fn from_index(index: u8) -> Shade {
28 match index {
29 1 => Shade::Light,
30 2 => Shade::HighContrast,
31 _ => Shade::Dark,
32 }
33 }
34 }
3 35
4 36 #[derive(Debug, PartialEq, Eq)]
5 pub struct ColorScheme {
6 pub id: &'static str,
7 pub name: &'static str,
37 pub struct Palette {
38 pub shade: Shade,
8 39 pub background: u32,
9 40 pub surface: u32,
10 41 pub surface_raised: u32,
@@ -49,112 +80,344 @@ pub struct ColorScheme {
49 80 pub meeting_avatar: u32,
50 81 pub bot_avatar: u32,
51 82 pub avatar_palette: [u32; 6],
83 pub code_surface: u32,
84 pub code_header_border: u32,
85 pub inline_code_fill: u32,
86 pub inline_code_fill_own: u32,
87 pub quote_fill: u32,
88 pub inline_code_border: u32,
89 pub table_header: u32,
52 90 }
53 91
54 pub const RUSTY_TEAMS: ColorScheme = ColorScheme {
55 id: "rusty-teams",
56 name: "Rusty Teams",
57 background: 0x0f0f10,
58 surface: 0x161617,
59 surface_raised: 0x232325,
60 row_hover: 0x1c1c1e,
61 popup: 0x2c2c2f,
62 popup_hover: 0x38383c,
63 popup_nested: 0x3a3a3e,
64 popup_nested_hover: 0x47474c,
65 reply_surface: 0x19191b,
66 border: 0x262628,
67 border_strong: 0x3f3f42,
68 foreground: 0xf4f4f5,
69 text_strong: 0xe4e4e7,
70 text_soft: 0xd4d4d8,
71 text_muted: 0xa1a1a6,
72 text_faint: 0x8e8e93,
73 accent: 0xce6a3b,
74 accent_text: 0xe08a5c,
75 accent_soft: 0xf5c4a5,
76 accent_strong: 0xa84f27,
77 on_accent: 0x0f0f10,
78 bubble_own: 0x4f2a1b,
79 bubble_other: 0x232325,
80 reaction_on_own: 0x6b3a26,
81 mention_background: 0x3a2a23,
82 mention_background_own: 0x3b1d11,
83 own_meta: 0xc9a28c,
84 own_read: 0xf5c4a5,
85 drop_background: 0xce6a3b14,
86 selection: 0xce6a3b66,
87 rule_own: 0x6a3a25,
88 badge_muted: 0x3f3f42,
89 toast_mention: 0x2e1d15,
90 green: 0x22c55e,
91 red: 0xef4444,
92 red_soft: 0xf87171,
93 red_tint: 0xfca5a5,
94 amber: 0xfbbf24,
92 #[derive(Debug, PartialEq, Eq)]
93 pub struct ColorScheme {
94 pub id: &'static str,
95 pub name: &'static str,
96 pub dark: Palette,
97 pub light: Palette,
98 }
99
100 impl ColorScheme {
101 pub fn palette(&self, shade: Shade) -> &Palette {
102 match shade {
103 Shade::Dark => &self.dark,
104 Shade::Light => &self.light,
105 Shade::HighContrast => &HIGH_CONTRAST,
106 }
107 }
108 }
109
110 const AVATAR_PALETTE: [u32; 6] = [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63];
111
112 const DARK_BASE: Palette = Palette {
113 shade: Shade::Dark,
114 background: 0,
115 surface: 0,
116 surface_raised: 0,
117 row_hover: 0,
118 popup: 0,
119 popup_hover: 0,
120 popup_nested: 0,
121 popup_nested_hover: 0,
122 reply_surface: 0,
123 border: 0,
124 border_strong: 0,
125 foreground: 0,
126 text_strong: 0,
127 text_soft: 0,
128 text_muted: 0,
129 text_faint: 0,
130 accent: 0,
131 accent_text: 0,
132 accent_soft: 0,
133 accent_strong: 0,
134 on_accent: 0,
135 bubble_own: 0,
136 bubble_other: 0,
137 reaction_on_own: 0,
138 mention_background: 0,
139 mention_background_own: 0,
140 own_meta: 0,
141 own_read: 0,
142 drop_background: 0,
143 selection: 0,
144 rule_own: 0,
145 badge_muted: 0,
146 toast_mention: 0,
147 green: 0,
148 red: 0,
149 red_soft: 0,
150 red_tint: 0,
151 amber: 0,
95 152 out_of_office: 0xc239b3,
96 close_button_hover: 0xc42b1c,
97 close_button_pressed: 0xb5271a,
153 close_button_hover: 0,
154 close_button_pressed: 0,
98 155 meeting_avatar: 0x4f52b2,
99 156 bot_avatar: 0x3a96dd,
100 avatar_palette: [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63],
157 avatar_palette: AVATAR_PALETTE,
158 code_surface: 0x0000003d,
159 code_header_border: 0xffffff0f,
160 inline_code_fill: 0xffffff14,
161 inline_code_fill_own: 0x0000003d,
162 quote_fill: 0x00000052,
163 inline_code_border: 0xffffff1a,
164 table_header: 0xffffff0d,
165 };
166
167 const LIGHT_BASE: Palette = Palette {
168 shade: Shade::Light,
169 code_surface: 0x0000000a,
170 code_header_border: 0x0000000f,
171 inline_code_fill: 0x0000000d,
172 inline_code_fill_own: 0x0000000f,
173 quote_fill: 0x0000000a,
174 inline_code_border: 0x00000014,
175 table_header: 0x00000008,
176 ..DARK_BASE
177 };
178
179 pub const RUSTY_TEAMS: ColorScheme = ColorScheme {
180 id: "rusty-teams",
181 name: "Rusty Teams",
182 dark: Palette {
183 background: 0x0f0f10,
184 surface: 0x161617,
185 surface_raised: 0x232325,
186 row_hover: 0x1c1c1e,
187 popup: 0x2c2c2f,
188 popup_hover: 0x38383c,
189 popup_nested: 0x3a3a3e,
190 popup_nested_hover: 0x47474c,
191 reply_surface: 0x19191b,
192 border: 0x262628,
193 border_strong: 0x3f3f42,
194 foreground: 0xf4f4f5,
195 text_strong: 0xe4e4e7,
196 text_soft: 0xd4d4d8,
197 text_muted: 0xa1a1a6,
198 text_faint: 0x8e8e93,
199 accent: 0xce6a3b,
200 accent_text: 0xe08a5c,
201 accent_soft: 0xf5c4a5,
202 accent_strong: 0xa84f27,
203 on_accent: 0x0f0f10,
204 bubble_own: 0x4f2a1b,
205 bubble_other: 0x232325,
206 reaction_on_own: 0x6b3a26,
207 mention_background: 0x3a2a23,
208 mention_background_own: 0x3b1d11,
209 own_meta: 0xc9a28c,
210 own_read: 0xf5c4a5,
211 drop_background: 0xce6a3b14,
212 selection: 0xce6a3b66,
213 rule_own: 0x6a3a25,
214 badge_muted: 0x3f3f42,
215 toast_mention: 0x2e1d15,
216 green: 0x22c55e,
217 red: 0xef4444,
218 red_soft: 0xf87171,
219 red_tint: 0xfca5a5,
220 amber: 0xfbbf24,
221 close_button_hover: 0xc42b1c,
222 close_button_pressed: 0xb5271a,
223 ..DARK_BASE
224 },
225 light: Palette {
226 background: 0xe9e9eb,
227 surface: 0xf4f4f5,
228 surface_raised: 0xffffff,
229 row_hover: 0xfafafa,
230 popup: 0xffffff,
231 popup_hover: 0xf1f1f2,
232 popup_nested: 0xffffff,
233 popup_nested_hover: 0xebebed,
234 reply_surface: 0xf9f9fa,
235 border: 0xe2e2e5,
236 border_strong: 0xd0d0d4,
237 foreground: 0x18181b,
238 text_strong: 0x27272a,
239 text_soft: 0x3f3f46,
240 text_muted: 0x5f5f66,
241 text_faint: 0x6e6e76,
242 accent: 0xb4501f,
243 accent_text: 0xa84a1d,
244 accent_soft: 0x8f3d17,
245 accent_strong: 0x93421d,
246 on_accent: 0xffffff,
247 bubble_own: 0xfae6da,
248 bubble_other: 0xffffff,
249 reaction_on_own: 0xf2cfb9,
250 mention_background: 0xfbebe1,
251 mention_background_own: 0xf2cfb9,
252 own_meta: 0x7a5444,
253 own_read: 0xa84a1d,
254 drop_background: 0xb4501f14,
255 selection: 0xb4501f40,
256 rule_own: 0xecc3a8,
257 badge_muted: 0xd0d0d4,
258 toast_mention: 0xfbebe1,
259 green: 0x16a34a,
260 red: 0xc81e1e,
261 red_soft: 0xb91c1c,
262 red_tint: 0x991b1b,
263 amber: 0xc27c0e,
264 close_button_hover: 0xc42b1c,
265 close_button_pressed: 0xb5271a,
266 ..LIGHT_BASE
267 },
101 268 };
102 269
103 270 pub const TEAMS: ColorScheme = ColorScheme {
104 271 id: "teams",
105 272 name: "Teams",
106 background: 0x0a0a0a,
107 surface: 0x1f1f1f,
108 surface_raised: 0x2e2e2e,
109 row_hover: 0x292929,
110 popup: 0x333333,
111 popup_hover: 0x3d3d3d,
112 popup_nested: 0x424242,
113 popup_nested_hover: 0x4d4d4d,
114 reply_surface: 0x242424,
115 border: 0x333333,
116 border_strong: 0x3d3d3d,
273 dark: Palette {
274 background: 0x0a0a0a,
275 surface: 0x1f1f1f,
276 surface_raised: 0x2e2e2e,
277 row_hover: 0x292929,
278 popup: 0x333333,
279 popup_hover: 0x3d3d3d,
280 popup_nested: 0x424242,
281 popup_nested_hover: 0x4d4d4d,
282 reply_surface: 0x242424,
283 border: 0x333333,
284 border_strong: 0x3d3d3d,
285 foreground: 0xffffff,
286 text_strong: 0xe0e0e0,
287 text_soft: 0xd6d6d6,
288 text_muted: 0xadadad,
289 text_faint: 0x999999,
290 accent: 0x5b5fc7,
291 accent_text: 0x7f85f5,
292 accent_soft: 0xaab1fa,
293 accent_strong: 0x444791,
294 on_accent: 0xffffff,
295 bubble_own: 0x2f2f4a,
296 bubble_other: 0x292929,
297 reaction_on_own: 0x383966,
298 mention_background: 0x2f2f4a,
299 mention_background_own: 0x3d3e78,
300 own_meta: 0xadadad,
301 own_read: 0xaab1fa,
302 drop_background: 0x5b5fc714,
303 selection: 0x5b5fc766,
304 rule_own: 0x444791,
305 badge_muted: 0x3d3d3d,
306 toast_mention: 0x2f2f4a,
307 green: 0x92c353,
308 red: 0xc4314b,
309 red_soft: 0xe37d80,
310 red_tint: 0xf1bbbc,
311 amber: 0xffaa44,
312 close_button_hover: 0xc4314b,
313 close_button_pressed: 0xa72037,
314 ..DARK_BASE
315 },
316 light: Palette {
317 background: 0xebebeb,
318 surface: 0xf5f5f5,
319 surface_raised: 0xffffff,
320 row_hover: 0xfafafa,
321 popup: 0xffffff,
322 popup_hover: 0xf5f5f5,
323 popup_nested: 0xffffff,
324 popup_nested_hover: 0xf0f0f0,
325 reply_surface: 0xfafafa,
326 border: 0xe0e0e0,
327 border_strong: 0xd1d1d1,
328 foreground: 0x242424,
329 text_strong: 0x333333,
330 text_soft: 0x424242,
331 text_muted: 0x616161,
332 text_faint: 0x707070,
333 accent: 0x5b5fc7,
334 accent_text: 0x5b5fc7,
335 accent_soft: 0x4f52b2,
336 accent_strong: 0x444791,
337 on_accent: 0xffffff,
338 bubble_own: 0xe8ebfa,
339 bubble_other: 0xffffff,
340 reaction_on_own: 0xdce0fa,
341 mention_background: 0xe8ebfa,
342 mention_background_own: 0xc5cbfa,
343 own_meta: 0x616161,
344 own_read: 0x4f52b2,
345 drop_background: 0x5b5fc714,
346 selection: 0x5b5fc740,
347 rule_own: 0xc5cbfa,
348 badge_muted: 0xd1d1d1,
349 toast_mention: 0xe8ebfa,
350 green: 0x13a10e,
351 red: 0xc4314b,
352 red_soft: 0xb10e1c,
353 red_tint: 0x8e192e,
354 amber: 0xc27c0e,
355 close_button_hover: 0xc4314b,
356 close_button_pressed: 0xa72037,
357 ..LIGHT_BASE
358 },
359 };
360
361 pub const HIGH_CONTRAST: Palette = Palette {
362 shade: Shade::HighContrast,
363 background: 0x000000,
364 surface: 0x000000,
365 surface_raised: 0x000000,
366 row_hover: 0x003b40,
367 popup: 0x000000,
368 popup_hover: 0x003b40,
369 popup_nested: 0x000000,
370 popup_nested_hover: 0x003b40,
371 reply_surface: 0x000000,
372 border: 0xffffff,
373 border_strong: 0xffffff,
117 374 foreground: 0xffffff,
118 text_strong: 0xe0e0e0,
119 text_soft: 0xd6d6d6,
120 text_muted: 0xadadad,
121 text_faint: 0x999999,
122 accent: 0x5b5fc7,
123 accent_text: 0x7f85f5,
124 accent_soft: 0xaab1fa,
125 accent_strong: 0x444791,
126 on_accent: 0xffffff,
127 bubble_own: 0x2f2f4a,
128 bubble_other: 0x292929,
129 reaction_on_own: 0x383966,
130 mention_background: 0x2f2f4a,
131 mention_background_own: 0x3d3e78,
132 own_meta: 0xadadad,
133 own_read: 0xaab1fa,
134 drop_background: 0x5b5fc714,
135 selection: 0x5b5fc766,
136 rule_own: 0x444791,
137 badge_muted: 0x3d3d3d,
138 toast_mention: 0x2f2f4a,
139 green: 0x92c353,
140 red: 0xc4314b,
141 red_soft: 0xe37d80,
142 red_tint: 0xf1bbbc,
143 amber: 0xffaa44,
144 out_of_office: 0xc239b3,
375 text_strong: 0xffffff,
376 text_soft: 0xffffff,
377 text_muted: 0xffffff,
378 text_faint: 0x3ff23f,
379 accent: 0x1aebff,
380 accent_text: 0xffff00,
381 accent_soft: 0x1aebff,
382 accent_strong: 0x1aebff,
383 on_accent: 0x000000,
384 bubble_own: 0x002e33,
385 bubble_other: 0x000000,
386 reaction_on_own: 0x003b40,
387 mention_background: 0x000000,
388 mention_background_own: 0x000000,
389 own_meta: 0xffffff,
390 own_read: 0x1aebff,
391 drop_background: 0x1aebff26,
392 selection: 0x1aebff80,
393 rule_own: 0xffffff,
394 badge_muted: 0xffffff,
395 toast_mention: 0x000000,
396 green: 0x3ff23f,
397 red: 0xff4d4d,
398 red_soft: 0xff4d4d,
399 red_tint: 0xff4d4d,
400 amber: 0xffff00,
145 401 close_button_hover: 0xc4314b,
146 402 close_button_pressed: 0xa72037,
147 meeting_avatar: 0x4f52b2,
148 bot_avatar: 0x3a96dd,
149 avatar_palette: [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63],
403 code_surface: 0x000000ff,
404 code_header_border: 0xffffffff,
405 inline_code_fill: 0x000000ff,
406 inline_code_fill_own: 0x000000ff,
407 quote_fill: 0x000000ff,
408 inline_code_border: 0xffffffff,
409 table_header: 0x000000ff,
410 ..DARK_BASE
150 411 };
151 412
152 413 pub const SCHEMES: [&ColorScheme; 2] = [&RUSTY_TEAMS, &TEAMS];
153 414
154 415 static ACTIVE_SCHEME: AtomicUsize = AtomicUsize::new(0);
416 static ACTIVE_SHADE: AtomicU8 = AtomicU8::new(0);
155 417
156 418 thread_local! {
157 419 static THREAD_SCHEME: Cell<Option<usize>> = const { Cell::new(None) };
420 static THREAD_SHADE: Cell<Option<Shade>> = const { Cell::new(None) };
158 421 }
159 422
160 423 pub fn default_scheme() -> &'static ColorScheme {
@@ -179,20 +442,64 @@ pub fn active_scheme() -> &'static ColorScheme {
179 442 SCHEMES[index.min(SCHEMES.len() - 1)]
180 443 }
181 444
445 pub fn active_shade() -> Shade {
446 THREAD_SHADE
447 .with(Cell::get)
448 .unwrap_or_else(|| Shade::from_index(ACTIVE_SHADE.load(Ordering::Relaxed)))
449 }
450
451 pub fn active_palette() -> &'static Palette {
452 active_scheme().palette(active_shade())
453 }
454
182 455 pub fn set_active_scheme(id: &str) {
183 456 ACTIVE_SCHEME.store(position(id), Ordering::Relaxed);
184 457 }
185 458
459 pub fn set_active_shade(shade: Shade) {
460 ACTIVE_SHADE.store(shade.index(), Ordering::Relaxed);
461 }
462
186 463 pub fn set_thread_scheme(id: Option<&str>) {
187 464 THREAD_SCHEME.with(|cell| cell.set(id.map(position)));
188 465 }
189 466
467 pub fn set_thread_shade(shade: Option<Shade>) {
468 THREAD_SHADE.with(|cell| cell.set(shade));
469 }
470
471 pub fn palettes() -> impl Iterator<Item = (&'static ColorScheme, &'static Palette)> {
472 SCHEMES.into_iter().flat_map(|scheme| {
473 Shade::ALL
474 .into_iter()
475 .map(move |shade| (scheme, scheme.palette(shade)))
476 })
477 }
478
190 479 #[cfg(test)]
191 480 mod tests {
192 481 use std::collections::HashSet;
193 482
194 483 use super::*;
195 484
485 fn channel(hex: u32, shift: u32) -> f64 {
486 let value = f64::from((hex >> shift) & 0xff) / 255.;
487 if value <= 0.04045 {
488 value / 12.92
489 } else {
490 ((value + 0.055) / 1.055).powf(2.4)
491 }
492 }
493
494 fn luminance(hex: u32) -> f64 {
495 0.2126 * channel(hex, 16) + 0.7152 * channel(hex, 8) + 0.0722 * channel(hex, 0)
496 }
497
498 fn contrast(first: u32, second: u32) -> f64 {
499 let (first, second) = (luminance(first), luminance(second));
500 (first.max(second) + 0.05) / (first.min(second) + 0.05)
501 }
502
196 503 #[test]
197 504 fn scheme_ids_and_names_are_unique() {
198 505 let ids: HashSet<_> = SCHEMES.iter().map(|scheme| scheme.id).collect();
@@ -209,35 +516,112 @@ mod tests {
209 516 }
210 517
211 518 #[test]
212 fn teams_scheme_uses_the_teams_dark_brand_ramp() {
213 assert_eq!(TEAMS.accent_text, 0x7f85f5);
214 assert_eq!(TEAMS.bubble_own, 0x2f2f4a);
215 assert_eq!(TEAMS.surface, 0x1f1f1f);
519 fn teams_scheme_uses_the_teams_brand_ramp_in_both_shades() {
520 assert_eq!(TEAMS.dark.accent_text, 0x7f85f5);
521 assert_eq!(TEAMS.dark.bubble_own, 0x2f2f4a);
522 assert_eq!(TEAMS.dark.surface, 0x1f1f1f);
523 assert_eq!(TEAMS.light.accent, 0x5b5fc7);
524 assert_eq!(TEAMS.light.bubble_own, 0xe8ebfa);
525 assert_eq!(TEAMS.light.foreground, 0x242424);
526 assert_eq!(TEAMS.light.background, 0xebebeb);
216 527 }
217 528
218 529 #[test]
219 fn every_scheme_layers_its_surfaces_from_dark_to_light() {
530 fn every_palette_names_its_own_shade() {
220 531 for scheme in SCHEMES {
532 for shade in Shade::ALL {
533 assert_eq!(scheme.palette(shade).shade, shade, "{}", scheme.id);
534 }
535 }
536 }
537
538 #[test]
539 fn dark_palettes_layer_their_surfaces_from_dark_to_light() {
540 for scheme in SCHEMES {
541 let palette = &scheme.dark;
221 542 let layers = [
222 scheme.background,
223 scheme.surface,
224 scheme.reply_surface,
225 scheme.row_hover,
226 scheme.surface_raised,
227 scheme.popup,
228 scheme.popup_hover,
543 palette.background,
544 palette.surface,
545 palette.reply_surface,
546 palette.row_hover,
547 palette.surface_raised,
548 palette.popup,
549 palette.popup_hover,
229 550 ];
230 551 assert!(
231 552 layers.windows(2).all(|pair| pair[0] < pair[1]),
232 553 "{} surfaces are not ordered dark to light",
233 554 scheme.id
234 555 );
235 assert!(scheme.popup_nested > scheme.popup, "{}", scheme.id);
556 assert!(palette.popup_nested > palette.popup, "{}", scheme.id);
236 557 assert!(
237 scheme.popup_nested_hover > scheme.popup_nested,
558 palette.popup_nested_hover > palette.popup_nested,
559 "{}",
560 scheme.id
561 );
562 }
563 }
564
565 #[test]
566 fn light_palettes_lift_islands_and_flyouts_off_the_window_ground() {
567 for scheme in SCHEMES {
568 let palette = &scheme.light;
569 assert!(palette.background < palette.surface, "{}", scheme.id);
570 assert!(palette.surface < palette.reply_surface, "{}", scheme.id);
571 assert!(palette.surface < palette.popup, "{}", scheme.id);
572 assert_ne!(palette.popup_hover, palette.popup, "{}", scheme.id);
573 assert_ne!(
574 palette.popup_nested_hover, palette.popup_nested,
238 575 "{}",
239 576 scheme.id
240 577 );
578 assert_ne!(palette.row_hover, palette.surface, "{}", scheme.id);
579 }
580 }
581
582 #[test]
583 fn text_stays_readable_on_every_surface_of_every_palette() {
584 for (scheme, palette) in palettes() {
585 let grounds = [
586 palette.background,
587 palette.surface,
588 palette.reply_surface,
589 palette.row_hover,
590 palette.surface_raised,
591 palette.popup,
592 palette.bubble_other,
593 palette.bubble_own,
594 ];
595 let checks = [
596 ("foreground", palette.foreground, 4.5),
597 ("text_soft", palette.text_soft, 4.5),
598 ("text_muted", palette.text_muted, 3.),
599 ("text_faint", palette.text_faint, 2.5),
600 ("accent_text", palette.accent_text, 3.),
601 ];
602 for (name, text, minimum) in checks {
603 for ground in grounds {
604 let ratio = contrast(text, ground);
605 assert!(
606 ratio >= minimum,
607 "{} {:?}: {name} #{text:06x} on #{ground:06x} is {ratio:.2}",
608 scheme.id,
609 palette.shade
610 );
611 }
612 }
613 assert!(
614 contrast(palette.on_accent, palette.accent) >= 4.5,
615 "{} {:?}: on_accent",
616 scheme.id,
617 palette.shade
618 );
619 assert!(
620 contrast(palette.own_meta, palette.bubble_own) >= 3.,
621 "{} {:?}: own_meta",
622 scheme.id,
623 palette.shade
624 );
241 625 }
242 626 }
243 627
@@ -245,8 +629,13 @@ mod tests {
245 629 fn a_thread_override_wins_over_the_process_scheme() {
246 630 set_thread_scheme(Some("teams"));
247 631 assert_eq!(active_scheme().id, "teams");
632 set_thread_shade(Some(Shade::Light));
633 assert_eq!(active_palette(), &TEAMS.light);
634 set_thread_shade(Some(Shade::HighContrast));
635 assert_eq!(active_palette(), &HIGH_CONTRAST);
248 636 set_thread_scheme(Some("unknown"));
249 637 assert_eq!(active_scheme().id, "rusty-teams");
250 638 set_thread_scheme(None);
639 set_thread_shade(None);
251 640 }
252 641 }
@@ -1,10 +1,41 @@
1use std::cell::Cell;
1use std::cell::Cell;
2use std::sync::atomic::{AtomicUsize, Ordering};
2use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
5pub enum Shade {
6 #[default]
7 Dark,
8 Light,
9 HighContrast,
10}
11
12impl Shade {
13 pub const ALL: [Shade; 3] = [Shade::Dark, Shade::Light, Shade::HighContrast];
14
15 pub fn is_dark(self) -> bool {
16 !matches!(self, Shade::Light)
17 }
18
19 fn index(self) -> u8 {
20 match self {
21 Shade::Dark => 0,
22 Shade::Light => 1,
23 Shade::HighContrast => 2,
24 }
25 }
26
27 fn from_index(index: u8) -> Shade {
28 match index {
29 1 => Shade::Light,
30 2 => Shade::HighContrast,
31 _ => Shade::Dark,
32 }
33 }
34}
3
35
4#[derive(Debug, PartialEq, Eq)]
36#[derive(Debug, PartialEq, Eq)]
5pub struct ColorScheme {
37pub struct Palette {
6 pub id: &'static str,
38 pub shade: Shade,
7 pub name: &'static str,
8 pub background: u32,
39 pub background: u32,
9 pub surface: u32,
40 pub surface: u32,
10 pub surface_raised: u32,
41 pub surface_raised: u32,
@@ -49,112 +80,344 @@ pub struct ColorScheme {
49 pub meeting_avatar: u32,
80 pub meeting_avatar: u32,
50 pub bot_avatar: u32,
81 pub bot_avatar: u32,
51 pub avatar_palette: [u32; 6],
82 pub avatar_palette: [u32; 6],
83 pub code_surface: u32,
84 pub code_header_border: u32,
85 pub inline_code_fill: u32,
86 pub inline_code_fill_own: u32,
87 pub quote_fill: u32,
88 pub inline_code_border: u32,
89 pub table_header: u32,
52}
90}
53
91
54pub const RUSTY_TEAMS: ColorScheme = ColorScheme {
92#[derive(Debug, PartialEq, Eq)]
55 id: "rusty-teams",
93pub struct ColorScheme {
56 name: "Rusty Teams",
94 pub id: &'static str,
57 background: 0x0f0f10,
95 pub name: &'static str,
58 surface: 0x161617,
96 pub dark: Palette,
59 surface_raised: 0x232325,
97 pub light: Palette,
60 row_hover: 0x1c1c1e,
98}
61 popup: 0x2c2c2f,
99
62 popup_hover: 0x38383c,
100impl ColorScheme {
63 popup_nested: 0x3a3a3e,
101 pub fn palette(&self, shade: Shade) -> &Palette {
64 popup_nested_hover: 0x47474c,
102 match shade {
65 reply_surface: 0x19191b,
103 Shade::Dark => &self.dark,
66 border: 0x262628,
104 Shade::Light => &self.light,
67 border_strong: 0x3f3f42,
105 Shade::HighContrast => &HIGH_CONTRAST,
68 foreground: 0xf4f4f5,
106 }
69 text_strong: 0xe4e4e7,
107 }
70 text_soft: 0xd4d4d8,
108}
71 text_muted: 0xa1a1a6,
109
72 text_faint: 0x8e8e93,
110const AVATAR_PALETTE: [u32; 6] = [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63];
73 accent: 0xce6a3b,
111
74 accent_text: 0xe08a5c,
112const DARK_BASE: Palette = Palette {
75 accent_soft: 0xf5c4a5,
113 shade: Shade::Dark,
76 accent_strong: 0xa84f27,
114 background: 0,
77 on_accent: 0x0f0f10,
115 surface: 0,
78 bubble_own: 0x4f2a1b,
116 surface_raised: 0,
79 bubble_other: 0x232325,
117 row_hover: 0,
80 reaction_on_own: 0x6b3a26,
118 popup: 0,
81 mention_background: 0x3a2a23,
119 popup_hover: 0,
82 mention_background_own: 0x3b1d11,
120 popup_nested: 0,
83 own_meta: 0xc9a28c,
121 popup_nested_hover: 0,
84 own_read: 0xf5c4a5,
122 reply_surface: 0,
85 drop_background: 0xce6a3b14,
123 border: 0,
86 selection: 0xce6a3b66,
124 border_strong: 0,
87 rule_own: 0x6a3a25,
125 foreground: 0,
88 badge_muted: 0x3f3f42,
126 text_strong: 0,
89 toast_mention: 0x2e1d15,
127 text_soft: 0,
90 green: 0x22c55e,
128 text_muted: 0,
91 red: 0xef4444,
129 text_faint: 0,
92 red_soft: 0xf87171,
130 accent: 0,
93 red_tint: 0xfca5a5,
131 accent_text: 0,
94 amber: 0xfbbf24,
132 accent_soft: 0,
133 accent_strong: 0,
134 on_accent: 0,
135 bubble_own: 0,
136 bubble_other: 0,
137 reaction_on_own: 0,
138 mention_background: 0,
139 mention_background_own: 0,
140 own_meta: 0,
141 own_read: 0,
142 drop_background: 0,
143 selection: 0,
144 rule_own: 0,
145 badge_muted: 0,
146 toast_mention: 0,
147 green: 0,
148 red: 0,
149 red_soft: 0,
150 red_tint: 0,
151 amber: 0,
95 out_of_office: 0xc239b3,
152 out_of_office: 0xc239b3,
96 close_button_hover: 0xc42b1c,
153 close_button_hover: 0,
97 close_button_pressed: 0xb5271a,
154 close_button_pressed: 0,
98 meeting_avatar: 0x4f52b2,
155 meeting_avatar: 0x4f52b2,
99 bot_avatar: 0x3a96dd,
156 bot_avatar: 0x3a96dd,
100 avatar_palette: [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63],
157 avatar_palette: AVATAR_PALETTE,
158 code_surface: 0x0000003d,
159 code_header_border: 0xffffff0f,
160 inline_code_fill: 0xffffff14,
161 inline_code_fill_own: 0x0000003d,
162 quote_fill: 0x00000052,
163 inline_code_border: 0xffffff1a,
164 table_header: 0xffffff0d,
165};
166
167const LIGHT_BASE: Palette = Palette {
168 shade: Shade::Light,
169 code_surface: 0x0000000a,
170 code_header_border: 0x0000000f,
171 inline_code_fill: 0x0000000d,
172 inline_code_fill_own: 0x0000000f,
173 quote_fill: 0x0000000a,
174 inline_code_border: 0x00000014,
175 table_header: 0x00000008,
176 ..DARK_BASE
177};
178
179pub const RUSTY_TEAMS: ColorScheme = ColorScheme {
180 id: "rusty-teams",
181 name: "Rusty Teams",
182 dark: Palette {
183 background: 0x0f0f10,
184 surface: 0x161617,
185 surface_raised: 0x232325,
186 row_hover: 0x1c1c1e,
187 popup: 0x2c2c2f,
188 popup_hover: 0x38383c,
189 popup_nested: 0x3a3a3e,
190 popup_nested_hover: 0x47474c,
191 reply_surface: 0x19191b,
192 border: 0x262628,
193 border_strong: 0x3f3f42,
194 foreground: 0xf4f4f5,
195 text_strong: 0xe4e4e7,
196 text_soft: 0xd4d4d8,
197 text_muted: 0xa1a1a6,
198 text_faint: 0x8e8e93,
199 accent: 0xce6a3b,
200 accent_text: 0xe08a5c,
201 accent_soft: 0xf5c4a5,
202 accent_strong: 0xa84f27,
203 on_accent: 0x0f0f10,
204 bubble_own: 0x4f2a1b,
205 bubble_other: 0x232325,
206 reaction_on_own: 0x6b3a26,
207 mention_background: 0x3a2a23,
208 mention_background_own: 0x3b1d11,
209 own_meta: 0xc9a28c,
210 own_read: 0xf5c4a5,
211 drop_background: 0xce6a3b14,
212 selection: 0xce6a3b66,
213 rule_own: 0x6a3a25,
214 badge_muted: 0x3f3f42,
215 toast_mention: 0x2e1d15,
216 green: 0x22c55e,
217 red: 0xef4444,
218 red_soft: 0xf87171,
219 red_tint: 0xfca5a5,
220 amber: 0xfbbf24,
221 close_button_hover: 0xc42b1c,
222 close_button_pressed: 0xb5271a,
223 ..DARK_BASE
224 },
225 light: Palette {
226 background: 0xe9e9eb,
227 surface: 0xf4f4f5,
228 surface_raised: 0xffffff,
229 row_hover: 0xfafafa,
230 popup: 0xffffff,
231 popup_hover: 0xf1f1f2,
232 popup_nested: 0xffffff,
233 popup_nested_hover: 0xebebed,
234 reply_surface: 0xf9f9fa,
235 border: 0xe2e2e5,
236 border_strong: 0xd0d0d4,
237 foreground: 0x18181b,
238 text_strong: 0x27272a,
239 text_soft: 0x3f3f46,
240 text_muted: 0x5f5f66,
241 text_faint: 0x6e6e76,
242 accent: 0xb4501f,
243 accent_text: 0xa84a1d,
244 accent_soft: 0x8f3d17,
245 accent_strong: 0x93421d,
246 on_accent: 0xffffff,
247 bubble_own: 0xfae6da,
248 bubble_other: 0xffffff,
249 reaction_on_own: 0xf2cfb9,
250 mention_background: 0xfbebe1,
251 mention_background_own: 0xf2cfb9,
252 own_meta: 0x7a5444,
253 own_read: 0xa84a1d,
254 drop_background: 0xb4501f14,
255 selection: 0xb4501f40,
256 rule_own: 0xecc3a8,
257 badge_muted: 0xd0d0d4,
258 toast_mention: 0xfbebe1,
259 green: 0x16a34a,
260 red: 0xc81e1e,
261 red_soft: 0xb91c1c,
262 red_tint: 0x991b1b,
263 amber: 0xc27c0e,
264 close_button_hover: 0xc42b1c,
265 close_button_pressed: 0xb5271a,
266 ..LIGHT_BASE
267 },
101};
268};
102
269
103pub const TEAMS: ColorScheme = ColorScheme {
270pub const TEAMS: ColorScheme = ColorScheme {
104 id: "teams",
271 id: "teams",
105 name: "Teams",
272 name: "Teams",
106 background: 0x0a0a0a,
273 dark: Palette {
107 surface: 0x1f1f1f,
274 background: 0x0a0a0a,
108 surface_raised: 0x2e2e2e,
275 surface: 0x1f1f1f,
109 row_hover: 0x292929,
276 surface_raised: 0x2e2e2e,
110 popup: 0x333333,
277 row_hover: 0x292929,
111 popup_hover: 0x3d3d3d,
278 popup: 0x333333,
112 popup_nested: 0x424242,
279 popup_hover: 0x3d3d3d,
113 popup_nested_hover: 0x4d4d4d,
280 popup_nested: 0x424242,
114 reply_surface: 0x242424,
281 popup_nested_hover: 0x4d4d4d,
115 border: 0x333333,
282 reply_surface: 0x242424,
116 border_strong: 0x3d3d3d,
283 border: 0x333333,
284 border_strong: 0x3d3d3d,
285 foreground: 0xffffff,
286 text_strong: 0xe0e0e0,
287 text_soft: 0xd6d6d6,
288 text_muted: 0xadadad,
289 text_faint: 0x999999,
290 accent: 0x5b5fc7,
291 accent_text: 0x7f85f5,
292 accent_soft: 0xaab1fa,
293 accent_strong: 0x444791,
294 on_accent: 0xffffff,
295 bubble_own: 0x2f2f4a,
296 bubble_other: 0x292929,
297 reaction_on_own: 0x383966,
298 mention_background: 0x2f2f4a,
299 mention_background_own: 0x3d3e78,
300 own_meta: 0xadadad,
301 own_read: 0xaab1fa,
302 drop_background: 0x5b5fc714,
303 selection: 0x5b5fc766,
304 rule_own: 0x444791,
305 badge_muted: 0x3d3d3d,
306 toast_mention: 0x2f2f4a,
307 green: 0x92c353,
308 red: 0xc4314b,
309 red_soft: 0xe37d80,
310 red_tint: 0xf1bbbc,
311 amber: 0xffaa44,
312 close_button_hover: 0xc4314b,
313 close_button_pressed: 0xa72037,
314 ..DARK_BASE
315 },
316 light: Palette {
317 background: 0xebebeb,
318 surface: 0xf5f5f5,
319 surface_raised: 0xffffff,
320 row_hover: 0xfafafa,
321 popup: 0xffffff,
322 popup_hover: 0xf5f5f5,
323 popup_nested: 0xffffff,
324 popup_nested_hover: 0xf0f0f0,
325 reply_surface: 0xfafafa,
326 border: 0xe0e0e0,
327 border_strong: 0xd1d1d1,
328 foreground: 0x242424,
329 text_strong: 0x333333,
330 text_soft: 0x424242,
331 text_muted: 0x616161,
332 text_faint: 0x707070,
333 accent: 0x5b5fc7,
334 accent_text: 0x5b5fc7,
335 accent_soft: 0x4f52b2,
336 accent_strong: 0x444791,
337 on_accent: 0xffffff,
338 bubble_own: 0xe8ebfa,
339 bubble_other: 0xffffff,
340 reaction_on_own: 0xdce0fa,
341 mention_background: 0xe8ebfa,
342 mention_background_own: 0xc5cbfa,
343 own_meta: 0x616161,
344 own_read: 0x4f52b2,
345 drop_background: 0x5b5fc714,
346 selection: 0x5b5fc740,
347 rule_own: 0xc5cbfa,
348 badge_muted: 0xd1d1d1,
349 toast_mention: 0xe8ebfa,
350 green: 0x13a10e,
351 red: 0xc4314b,
352 red_soft: 0xb10e1c,
353 red_tint: 0x8e192e,
354 amber: 0xc27c0e,
355 close_button_hover: 0xc4314b,
356 close_button_pressed: 0xa72037,
357 ..LIGHT_BASE
358 },
359};
360
361pub const HIGH_CONTRAST: Palette = Palette {
362 shade: Shade::HighContrast,
363 background: 0x000000,
364 surface: 0x000000,
365 surface_raised: 0x000000,
366 row_hover: 0x003b40,
367 popup: 0x000000,
368 popup_hover: 0x003b40,
369 popup_nested: 0x000000,
370 popup_nested_hover: 0x003b40,
371 reply_surface: 0x000000,
372 border: 0xffffff,
373 border_strong: 0xffffff,
117 foreground: 0xffffff,
374 foreground: 0xffffff,
118 text_strong: 0xe0e0e0,
375 text_strong: 0xffffff,
119 text_soft: 0xd6d6d6,
376 text_soft: 0xffffff,
120 text_muted: 0xadadad,
377 text_muted: 0xffffff,
121 text_faint: 0x999999,
378 text_faint: 0x3ff23f,
122 accent: 0x5b5fc7,
379 accent: 0x1aebff,
123 accent_text: 0x7f85f5,
380 accent_text: 0xffff00,
124 accent_soft: 0xaab1fa,
381 accent_soft: 0x1aebff,
125 accent_strong: 0x444791,
382 accent_strong: 0x1aebff,
126 on_accent: 0xffffff,
383 on_accent: 0x000000,
127 bubble_own: 0x2f2f4a,
384 bubble_own: 0x002e33,
128 bubble_other: 0x292929,
385 bubble_other: 0x000000,
129 reaction_on_own: 0x383966,
386 reaction_on_own: 0x003b40,
130 mention_background: 0x2f2f4a,
387 mention_background: 0x000000,
131 mention_background_own: 0x3d3e78,
388 mention_background_own: 0x000000,
132 own_meta: 0xadadad,
389 own_meta: 0xffffff,
133 own_read: 0xaab1fa,
390 own_read: 0x1aebff,
134 drop_background: 0x5b5fc714,
391 drop_background: 0x1aebff26,
135 selection: 0x5b5fc766,
392 selection: 0x1aebff80,
136 rule_own: 0x444791,
393 rule_own: 0xffffff,
137 badge_muted: 0x3d3d3d,
394 badge_muted: 0xffffff,
138 toast_mention: 0x2f2f4a,
395 toast_mention: 0x000000,
139 green: 0x92c353,
396 green: 0x3ff23f,
140 red: 0xc4314b,
397 red: 0xff4d4d,
141 red_soft: 0xe37d80,
398 red_soft: 0xff4d4d,
142 red_tint: 0xf1bbbc,
399 red_tint: 0xff4d4d,
143 amber: 0xffaa44,
400 amber: 0xffff00,
144 out_of_office: 0xc239b3,
145 close_button_hover: 0xc4314b,
401 close_button_hover: 0xc4314b,
146 close_button_pressed: 0xa72037,
402 close_button_pressed: 0xa72037,
147 meeting_avatar: 0x4f52b2,
403 code_surface: 0x000000ff,
148 bot_avatar: 0x3a96dd,
404 code_header_border: 0xffffffff,
149 avatar_palette: [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63],
405 inline_code_fill: 0x000000ff,
406 inline_code_fill_own: 0x000000ff,
407 quote_fill: 0x000000ff,
408 inline_code_border: 0xffffffff,
409 table_header: 0x000000ff,
410 ..DARK_BASE
150};
411};
151
412
152pub const SCHEMES: [&ColorScheme; 2] = [&RUSTY_TEAMS, &TEAMS];
413pub const SCHEMES: [&ColorScheme; 2] = [&RUSTY_TEAMS, &TEAMS];
153
414
154static ACTIVE_SCHEME: AtomicUsize = AtomicUsize::new(0);
415static ACTIVE_SCHEME: AtomicUsize = AtomicUsize::new(0);
416static ACTIVE_SHADE: AtomicU8 = AtomicU8::new(0);
155
417
156thread_local! {
418thread_local! {
157 static THREAD_SCHEME: Cell<Option<usize>> = const { Cell::new(None) };
419 static THREAD_SCHEME: Cell<Option<usize>> = const { Cell::new(None) };
420 static THREAD_SHADE: Cell<Option<Shade>> = const { Cell::new(None) };
158}
421}
159
422
160pub fn default_scheme() -> &'static ColorScheme {
423pub fn default_scheme() -> &'static ColorScheme {
@@ -179,20 +442,64 @@ pub fn active_scheme() -> &'static ColorScheme {
179 SCHEMES[index.min(SCHEMES.len() - 1)]
442 SCHEMES[index.min(SCHEMES.len() - 1)]
180}
443}
181
444
445pub fn active_shade() -> Shade {
446 THREAD_SHADE
447 .with(Cell::get)
448 .unwrap_or_else(|| Shade::from_index(ACTIVE_SHADE.load(Ordering::Relaxed)))
449}
450
451pub fn active_palette() -> &'static Palette {
452 active_scheme().palette(active_shade())
453}
454
182pub fn set_active_scheme(id: &str) {
455pub fn set_active_scheme(id: &str) {
183 ACTIVE_SCHEME.store(position(id), Ordering::Relaxed);
456 ACTIVE_SCHEME.store(position(id), Ordering::Relaxed);
184}
457}
185
458
459pub fn set_active_shade(shade: Shade) {
460 ACTIVE_SHADE.store(shade.index(), Ordering::Relaxed);
461}
462
186pub fn set_thread_scheme(id: Option<&str>) {
463pub fn set_thread_scheme(id: Option<&str>) {
187 THREAD_SCHEME.with(|cell| cell.set(id.map(position)));
464 THREAD_SCHEME.with(|cell| cell.set(id.map(position)));
188}
465}
189
466
467pub fn set_thread_shade(shade: Option<Shade>) {
468 THREAD_SHADE.with(|cell| cell.set(shade));
469}
470
471pub fn palettes() -> impl Iterator<Item = (&'static ColorScheme, &'static Palette)> {
472 SCHEMES.into_iter().flat_map(|scheme| {
473 Shade::ALL
474 .into_iter()
475 .map(move |shade| (scheme, scheme.palette(shade)))
476 })
477}
478
190#[cfg(test)]
479#[cfg(test)]
191mod tests {
480mod tests {
192 use std::collections::HashSet;
481 use std::collections::HashSet;
193
482
194 use super::*;
483 use super::*;
195
484
485 fn channel(hex: u32, shift: u32) -> f64 {
486 let value = f64::from((hex >> shift) & 0xff) / 255.;
487 if value <= 0.04045 {
488 value / 12.92
489 } else {
490 ((value + 0.055) / 1.055).powf(2.4)
491 }
492 }
493
494 fn luminance(hex: u32) -> f64 {
495 0.2126 * channel(hex, 16) + 0.7152 * channel(hex, 8) + 0.0722 * channel(hex, 0)
496 }
497
498 fn contrast(first: u32, second: u32) -> f64 {
499 let (first, second) = (luminance(first), luminance(second));
500 (first.max(second) + 0.05) / (first.min(second) + 0.05)
501 }
502
196 #[test]
503 #[test]
197 fn scheme_ids_and_names_are_unique() {
504 fn scheme_ids_and_names_are_unique() {
198 let ids: HashSet<_> = SCHEMES.iter().map(|scheme| scheme.id).collect();
505 let ids: HashSet<_> = SCHEMES.iter().map(|scheme| scheme.id).collect();
@@ -209,35 +516,112 @@ mod tests {
209 }
516 }
210
517
211 #[test]
518 #[test]
212 fn teams_scheme_uses_the_teams_dark_brand_ramp() {
519 fn teams_scheme_uses_the_teams_brand_ramp_in_both_shades() {
213 assert_eq!(TEAMS.accent_text, 0x7f85f5);
520 assert_eq!(TEAMS.dark.accent_text, 0x7f85f5);
214 assert_eq!(TEAMS.bubble_own, 0x2f2f4a);
521 assert_eq!(TEAMS.dark.bubble_own, 0x2f2f4a);
215 assert_eq!(TEAMS.surface, 0x1f1f1f);
522 assert_eq!(TEAMS.dark.surface, 0x1f1f1f);
523 assert_eq!(TEAMS.light.accent, 0x5b5fc7);
524 assert_eq!(TEAMS.light.bubble_own, 0xe8ebfa);
525 assert_eq!(TEAMS.light.foreground, 0x242424);
526 assert_eq!(TEAMS.light.background, 0xebebeb);
216 }
527 }
217
528
218 #[test]
529 #[test]
219 fn every_scheme_layers_its_surfaces_from_dark_to_light() {
530 fn every_palette_names_its_own_shade() {
220 for scheme in SCHEMES {
531 for scheme in SCHEMES {
532 for shade in Shade::ALL {
533 assert_eq!(scheme.palette(shade).shade, shade, "{}", scheme.id);
534 }
535 }
536 }
537
538 #[test]
539 fn dark_palettes_layer_their_surfaces_from_dark_to_light() {
540 for scheme in SCHEMES {
541 let palette = &scheme.dark;
221 let layers = [
542 let layers = [
222 scheme.background,
543 palette.background,
223 scheme.surface,
544 palette.surface,
224 scheme.reply_surface,
545 palette.reply_surface,
225 scheme.row_hover,
546 palette.row_hover,
226 scheme.surface_raised,
547 palette.surface_raised,
227 scheme.popup,
548 palette.popup,
228 scheme.popup_hover,
549 palette.popup_hover,
229 ];
550 ];
230 assert!(
551 assert!(
231 layers.windows(2).all(|pair| pair[0] < pair[1]),
552 layers.windows(2).all(|pair| pair[0] < pair[1]),
232 "{} surfaces are not ordered dark to light",
553 "{} surfaces are not ordered dark to light",
233 scheme.id
554 scheme.id
234 );
555 );
235 assert!(scheme.popup_nested > scheme.popup, "{}", scheme.id);
556 assert!(palette.popup_nested > palette.popup, "{}", scheme.id);
236 assert!(
557 assert!(
237 scheme.popup_nested_hover > scheme.popup_nested,
558 palette.popup_nested_hover > palette.popup_nested,
559 "{}",
560 scheme.id
561 );
562 }
563 }
564
565 #[test]
566 fn light_palettes_lift_islands_and_flyouts_off_the_window_ground() {
567 for scheme in SCHEMES {
568 let palette = &scheme.light;
569 assert!(palette.background < palette.surface, "{}", scheme.id);
570 assert!(palette.surface < palette.reply_surface, "{}", scheme.id);
571 assert!(palette.surface < palette.popup, "{}", scheme.id);
572 assert_ne!(palette.popup_hover, palette.popup, "{}", scheme.id);
573 assert_ne!(
574 palette.popup_nested_hover, palette.popup_nested,
238 "{}",
575 "{}",
239 scheme.id
576 scheme.id
240 );
577 );
578 assert_ne!(palette.row_hover, palette.surface, "{}", scheme.id);
579 }
580 }
581
582 #[test]
583 fn text_stays_readable_on_every_surface_of_every_palette() {
584 for (scheme, palette) in palettes() {
585 let grounds = [
586 palette.background,
587 palette.surface,
588 palette.reply_surface,
589 palette.row_hover,
590 palette.surface_raised,
591 palette.popup,
592 palette.bubble_other,
593 palette.bubble_own,
594 ];
595 let checks = [
596 ("foreground", palette.foreground, 4.5),
597 ("text_soft", palette.text_soft, 4.5),
598 ("text_muted", palette.text_muted, 3.),
599 ("text_faint", palette.text_faint, 2.5),
600 ("accent_text", palette.accent_text, 3.),
601 ];
602 for (name, text, minimum) in checks {
603 for ground in grounds {
604 let ratio = contrast(text, ground);
605 assert!(
606 ratio >= minimum,
607 "{} {:?}: {name} #{text:06x} on #{ground:06x} is {ratio:.2}",
608 scheme.id,
609 palette.shade
610 );
611 }
612 }
613 assert!(
614 contrast(palette.on_accent, palette.accent) >= 4.5,
615 "{} {:?}: on_accent",
616 scheme.id,
617 palette.shade
618 );
619 assert!(
620 contrast(palette.own_meta, palette.bubble_own) >= 3.,
621 "{} {:?}: own_meta",
622 scheme.id,
623 palette.shade
624 );
241 }
625 }
242 }
626 }
243
627
@@ -245,8 +629,13 @@ mod tests {
245 fn a_thread_override_wins_over_the_process_scheme() {
629 fn a_thread_override_wins_over_the_process_scheme() {
246 set_thread_scheme(Some("teams"));
630 set_thread_scheme(Some("teams"));
247 assert_eq!(active_scheme().id, "teams");
631 assert_eq!(active_scheme().id, "teams");
632 set_thread_shade(Some(Shade::Light));
633 assert_eq!(active_palette(), &TEAMS.light);
634 set_thread_shade(Some(Shade::HighContrast));
635 assert_eq!(active_palette(), &HIGH_CONTRAST);
248 set_thread_scheme(Some("unknown"));
636 set_thread_scheme(Some("unknown"));
249 assert_eq!(active_scheme().id, "rusty-teams");
637 assert_eq!(active_scheme().id, "rusty-teams");
250 set_thread_scheme(None);
638 set_thread_scheme(None);
639 set_thread_shade(None);
251 }
640 }
252}
641}
crates/app-base/src/zoom.rs added +927 −0
@@ -0,0 +1,927 @@
1 use std::cell::{Cell, RefCell};
2 use std::ffi::OsString;
3 use std::path::{Path, PathBuf};
4 use std::rc::{Rc, Weak};
5 use std::sync::Arc;
6
7 use futures_channel::oneshot;
8 use gpui_kit::*;
9 use raw_window_handle::{
10 DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
11 };
12
13 use crate::appearance::DEFAULT_ZOOM;
14
15 struct Shared {
16 factor: Cell<f32>,
17 executor: ForegroundExecutor,
18 windows: RefCell<Vec<Weak<WindowState>>>,
19 }
20
21 thread_local! {
22 static SHARED: RefCell<Option<Rc<Shared>>> = const { RefCell::new(None) };
23 }
24
25 pub fn factor() -> f32 {
26 SHARED.with(|shared| {
27 shared
28 .borrow()
29 .as_ref()
30 .map_or(DEFAULT_ZOOM, |shared| shared.factor.get())
31 })
32 }
33
34 pub fn set_factor(factor: f32) {
35 let Some(shared) = SHARED.with(|shared| shared.borrow().clone()) else {
36 return;
37 };
38 if (shared.factor.get() - factor).abs() < f32::EPSILON {
39 return;
40 }
41 shared.factor.set(factor);
42 let windows: Vec<Rc<WindowState>> = shared
43 .windows
44 .borrow_mut()
45 .drain(..)
46 .filter_map(|window| window.upgrade())
47 .collect();
48 shared
49 .windows
50 .borrow_mut()
51 .extend(windows.iter().map(Rc::downgrade));
52 shared
53 .executor
54 .spawn(async move {
55 for window in windows {
56 window.relayout();
57 }
58 })
59 .detach();
60 }
61
62 pub fn wrap(inner: Rc<dyn Platform>, initial_factor: f32) -> Rc<dyn Platform> {
63 let shared = Rc::new(Shared {
64 factor: Cell::new(initial_factor),
65 executor: inner.foreground_executor(),
66 windows: RefCell::new(Vec::new()),
67 });
68 SHARED.with(|slot| *slot.borrow_mut() = Some(shared.clone()));
69 Rc::new(ZoomPlatform { inner, shared })
70 }
71
72 pub fn zooms(params: &WindowParams) -> bool {
73 matches!(params.kind, WindowKind::Normal) && params.is_resizable
74 }
75
76 struct WindowState {
77 shared: Rc<Shared>,
78 zoomed: bool,
79 platform_size: Cell<Size<Pixels>>,
80 platform_scale: Cell<f32>,
81 on_resize: RefCell<Option<Box<dyn FnMut(Size<Pixels>, f32)>>>,
82 }
83
84 impl WindowState {
85 fn zoom(&self) -> f32 {
86 if self.zoomed {
87 self.shared.factor.get()
88 } else {
89 DEFAULT_ZOOM
90 }
91 }
92
93 fn relayout(&self) {
94 let zoom = self.zoom();
95 let size = self.platform_size.get();
96 let scale = self.platform_scale.get();
97 if let Ok(mut callback) = self.on_resize.try_borrow_mut()
98 && let Some(callback) = callback.as_mut()
99 {
100 callback(scale_size(size, 1. / zoom), scale * zoom);
101 }
102 }
103 }
104
105 fn scale_point(point: Point<Pixels>, factor: f32) -> Point<Pixels> {
106 gpui_kit::point(point.x * factor, point.y * factor)
107 }
108
109 fn scale_size(size: Size<Pixels>, factor: f32) -> Size<Pixels> {
110 gpui_kit::size(size.width * factor, size.height * factor)
111 }
112
113 fn scale_bounds(bounds: Bounds<Pixels>, factor: f32) -> Bounds<Pixels> {
114 Bounds {
115 origin: scale_point(bounds.origin, factor),
116 size: scale_size(bounds.size, factor),
117 }
118 }
119
120 fn unzoom_input(input: PlatformInput, zoom: f32) -> PlatformInput {
121 if (zoom - DEFAULT_ZOOM).abs() < f32::EPSILON {
122 return input;
123 }
124 let factor = 1. / zoom;
125 let scale = |point: Point<Pixels>| scale_point(point, factor);
126 match input {
127 PlatformInput::MouseDown(mut event) => {
128 event.position = scale(event.position);
129 PlatformInput::MouseDown(event)
130 }
131 PlatformInput::MouseUp(mut event) => {
132 event.position = scale(event.position);
133 PlatformInput::MouseUp(event)
134 }
135 PlatformInput::MousePressure(mut event) => {
136 event.position = scale(event.position);
137 PlatformInput::MousePressure(event)
138 }
139 PlatformInput::MouseMove(mut event) => {
140 event.position = scale(event.position);
141 PlatformInput::MouseMove(event)
142 }
143 PlatformInput::MouseExited(mut event) => {
144 event.position = scale(event.position);
145 PlatformInput::MouseExited(event)
146 }
147 PlatformInput::ScrollWheel(mut event) => {
148 event.position = scale(event.position);
149 if let ScrollDelta::Pixels(delta) = event.delta {
150 event.delta = ScrollDelta::Pixels(scale(delta));
151 }
152 PlatformInput::ScrollWheel(event)
153 }
154 PlatformInput::Pinch(mut event) => {
155 event.position = scale(event.position);
156 PlatformInput::Pinch(event)
157 }
158 PlatformInput::LongPress(mut event) => {
159 event.start_position = scale(event.start_position);
160 event.position = scale(event.position);
161 PlatformInput::LongPress(event)
162 }
163 PlatformInput::TouchDrag(mut event) => {
164 event.start_position = scale(event.start_position);
165 event.position = scale(event.position);
166 PlatformInput::TouchDrag(event)
167 }
168 PlatformInput::Touch(mut event) => {
169 event.position = scale(event.position);
170 event.predicted_position = event.predicted_position.map(scale);
171 PlatformInput::Touch(event)
172 }
173 PlatformInput::FileDrop(event) => PlatformInput::FileDrop(match event {
174 FileDropEvent::Entered { position, paths } => FileDropEvent::Entered {
175 position: scale(position),
176 paths,
177 },
178 FileDropEvent::Pending { position } => FileDropEvent::Pending {
179 position: scale(position),
180 },
181 FileDropEvent::Submit { position } => FileDropEvent::Submit {
182 position: scale(position),
183 },
184 other => other,
185 }),
186 other @ (PlatformInput::KeyDown(_)
187 | PlatformInput::KeyUp(_)
188 | PlatformInput::ModifiersChanged(_)) => other,
189 }
190 }
191
192 struct ZoomPlatform {
193 inner: Rc<dyn Platform>,
194 shared: Rc<Shared>,
195 }
196
197 impl Platform for ZoomPlatform {
198 fn background_executor(&self) -> BackgroundExecutor {
199 self.inner.background_executor()
200 }
201
202 fn foreground_executor(&self) -> ForegroundExecutor {
203 self.inner.foreground_executor()
204 }
205
206 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
207 self.inner.text_system()
208 }
209
210 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
211 self.inner.run(on_finish_launching)
212 }
213
214 fn quit(&self) {
215 self.inner.quit()
216 }
217
218 fn set_initial_windowing(&self, request: WindowingRequest) {
219 self.inner.set_initial_windowing(request)
220 }
221
222 fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> {
223 self.inner.request_windowing(request)
224 }
225
226 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>) {
227 self.inner.restart(binary_path, arguments)
228 }
229
230 fn activate(&self, ignoring_other_apps: bool) {
231 self.inner.activate(ignoring_other_apps)
232 }
233
234 fn set_activation_policy(&self, policy: ActivationPolicy) {
235 self.inner.set_activation_policy(policy)
236 }
237
238 fn hide(&self) {
239 self.inner.hide()
240 }
241
242 fn hide_other_apps(&self) {
243 self.inner.hide_other_apps()
244 }
245
246 fn unhide_other_apps(&self) {
247 self.inner.unhide_other_apps()
248 }
249
250 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
251 self.inner.displays()
252 }
253
254 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
255 self.inner.primary_display()
256 }
257
258 fn active_window(&self) -> Option<AnyWindowHandle> {
259 self.inner.active_window()
260 }
261
262 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
263 self.inner.window_stack()
264 }
265
266 fn is_screen_capture_supported(&self) -> bool {
267 self.inner.is_screen_capture_supported()
268 }
269
270 fn open_window(
271 &self,
272 handle: AnyWindowHandle,
273 options: WindowParams,
274 ) -> Result<Box<dyn PlatformWindow>> {
275 let zoomed = zooms(&options);
276 let inner = self.inner.open_window(handle, options)?;
277 let state = Rc::new(WindowState {
278 shared: self.shared.clone(),
279 zoomed,
280 platform_size: Cell::new(inner.content_size()),
281 platform_scale: Cell::new(inner.scale_factor()),
282 on_resize: RefCell::new(None),
283 });
284 self.shared.windows.borrow_mut().push(Rc::downgrade(&state));
285 Ok(Box::new(ZoomWindow { inner, state }))
286 }
287
288 fn window_appearance(&self) -> WindowAppearance {
289 self.inner.window_appearance()
290 }
291
292 fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
293 self.inner.set_window_appearance(appearance)
294 }
295
296 fn button_layout(&self) -> Option<WindowButtonLayout> {
297 self.inner.button_layout()
298 }
299
300 fn open_url(&self, url: &str) {
301 self.inner.open_url(url)
302 }
303
304 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
305 self.inner.on_open_urls(callback)
306 }
307
308 fn register_url_scheme(&self, url: &str) -> Task<Result<()>> {
309 self.inner.register_url_scheme(url)
310 }
311
312 fn prompt_for_paths(
313 &self,
314 options: PathPromptOptions,
315 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
316 self.inner.prompt_for_paths(options)
317 }
318
319 fn prompt_for_new_path(
320 &self,
321 directory: &Path,
322 suggested_name: Option<&str>,
323 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
324 self.inner.prompt_for_new_path(directory, suggested_name)
325 }
326
327 fn can_select_mixed_files_and_dirs(&self) -> bool {
328 self.inner.can_select_mixed_files_and_dirs()
329 }
330
331 fn reveal_path(&self, path: &Path) {
332 self.inner.reveal_path(path)
333 }
334
335 fn open_with_system(&self, path: &Path) {
336 self.inner.open_with_system(path)
337 }
338
339 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>) {
340 self.inner.on_quit(callback)
341 }
342
343 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
344 self.inner.on_reopen(callback)
345 }
346
347 fn on_system_sleep(&self, callback: Box<dyn FnMut()>) {
348 self.inner.on_system_sleep(callback)
349 }
350
351 fn on_system_wake(&self, callback: Box<dyn FnMut()>) {
352 self.inner.on_system_wake(callback)
353 }
354
355 fn on_app_lifecycle(&self, callback: Box<dyn FnMut(AppLifecyclePhase)>) {
356 self.inner.on_app_lifecycle(callback)
357 }
358
359 fn on_memory_warning(&self, callback: Box<dyn FnMut()>) {
360 self.inner.on_memory_warning(callback)
361 }
362
363 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
364 self.inner.gestures()
365 }
366
367 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
368 self.inner.set_menus(menus, keymap)
369 }
370
371 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
372 self.inner.get_menus()
373 }
374
375 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
376 self.inner.set_dock_menu(menu, keymap)
377 }
378
379 fn perform_dock_menu_action(&self, action: usize) {
380 self.inner.perform_dock_menu_action(action)
381 }
382
383 fn add_recent_document(&self, path: &Path) {
384 self.inner.add_recent_document(path)
385 }
386
387 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
388 self.inner.on_app_menu_action(callback)
389 }
390
391 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
392 self.inner.on_will_open_app_menu(callback)
393 }
394
395 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
396 self.inner.on_validate_app_menu_command(callback)
397 }
398
399 fn thermal_state(&self) -> ThermalState {
400 self.inner.thermal_state()
401 }
402
403 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
404 self.inner.on_thermal_state_change(callback)
405 }
406
407 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
408 self.inner.prevent_idle_sleep(reason)
409 }
410
411 fn set_app_identity(&self, identifier: &str, name: &str) {
412 self.inner.set_app_identity(identifier, name)
413 }
414
415 fn show_system_notification(&self, notification: SystemNotification) {
416 self.inner.show_system_notification(notification)
417 }
418
419 fn dismiss_system_notification(&self, tag: &str) {
420 self.inner.dismiss_system_notification(tag)
421 }
422
423 fn on_system_notification_response(
424 &self,
425 callback: Box<dyn FnMut(SystemNotificationResponse)>,
426 ) {
427 self.inner.on_system_notification_response(callback)
428 }
429
430 fn compositor_name(&self) -> &'static str {
431 self.inner.compositor_name()
432 }
433
434 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
435 self.inner.graphical_environment()
436 }
437
438 fn app_path(&self) -> Result<PathBuf> {
439 self.inner.app_path()
440 }
441
442 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
443 self.inner.path_for_auxiliary_executable(name)
444 }
445
446 fn set_cursor_style(&self, style: CursorStyle) {
447 self.inner.set_cursor_style(style)
448 }
449
450 fn hide_cursor_until_mouse_moves(&self) {
451 self.inner.hide_cursor_until_mouse_moves()
452 }
453
454 fn is_cursor_visible(&self) -> bool {
455 self.inner.is_cursor_visible()
456 }
457
458 fn should_auto_hide_scrollbars(&self) -> bool {
459 self.inner.should_auto_hide_scrollbars()
460 }
461
462 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
463 self.inner.read_from_clipboard()
464 }
465
466 fn write_to_clipboard(&self, item: ClipboardItem) {
467 self.inner.write_to_clipboard(item)
468 }
469
470 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
471 self.inner.read_from_clipboard_async()
472 }
473
474 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
475 fn read_from_primary(&self) -> Option<ClipboardItem> {
476 self.inner.read_from_primary()
477 }
478
479 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
480 fn write_to_primary(&self, item: ClipboardItem) {
481 self.inner.write_to_primary(item)
482 }
483
484 #[cfg(target_os = "macos")]
485 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
486 self.inner.read_from_find_pasteboard()
487 }
488
489 #[cfg(target_os = "macos")]
490 fn write_to_find_pasteboard(&self, item: ClipboardItem) {
491 self.inner.write_to_find_pasteboard(item)
492 }
493
494 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
495 self.inner.write_credentials(url, username, password)
496 }
497
498 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
499 self.inner.read_credentials(url)
500 }
501
502 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
503 self.inner.delete_credentials(url)
504 }
505
506 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
507 self.inner.keyboard_layout()
508 }
509
510 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
511 self.inner.keyboard_mapper()
512 }
513
514 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
515 self.inner.on_keyboard_layout_change(callback)
516 }
517 }
518
519 struct ZoomWindow {
520 inner: Box<dyn PlatformWindow>,
521 state: Rc<WindowState>,
522 }
523
524 impl HasWindowHandle for ZoomWindow {
525 fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
526 self.inner.window_handle()
527 }
528 }
529
530 impl HasDisplayHandle for ZoomWindow {
531 fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
532 self.inner.display_handle()
533 }
534 }
535
536 impl PlatformWindow for ZoomWindow {
537 fn bounds(&self) -> Bounds<Pixels> {
538 self.inner.bounds()
539 }
540
541 fn is_maximized(&self) -> bool {
542 self.inner.is_maximized()
543 }
544
545 fn window_bounds(&self) -> WindowBounds {
546 self.inner.window_bounds()
547 }
548
549 fn content_size(&self) -> Size<Pixels> {
550 scale_size(self.inner.content_size(), 1. / self.state.zoom())
551 }
552
553 fn on_visual_viewport_changed(&self, callback: Box<dyn FnMut()>) {
554 self.inner.on_visual_viewport_changed(callback)
555 }
556
557 fn prepare_frame(&self) -> bool {
558 self.inner.prepare_frame()
559 }
560
561 fn resize(&mut self, size: Size<Pixels>) {
562 let zoom = self.state.zoom();
563 self.inner.resize(scale_size(size, zoom))
564 }
565
566 fn scale_factor(&self) -> f32 {
567 self.inner.scale_factor() * self.state.zoom()
568 }
569
570 fn appearance(&self) -> WindowAppearance {
571 self.inner.appearance()
572 }
573
574 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
575 self.inner.display()
576 }
577
578 fn mouse_position(&self) -> Point<Pixels> {
579 scale_point(self.inner.mouse_position(), 1. / self.state.zoom())
580 }
581
582 fn modifiers(&self) -> Modifiers {
583 self.inner.modifiers()
584 }
585
586 fn capslock(&self) -> Capslock {
587 self.inner.capslock()
588 }
589
590 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
591 self.inner.set_input_handler(input_handler)
592 }
593
594 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
595 self.inner.take_input_handler()
596 }
597
598 fn set_text_input_configuration(&mut self, configuration: TextInputConfiguration) {
599 self.inner.set_text_input_configuration(configuration)
600 }
601
602 fn prompt(
603 &self,
604 level: PromptLevel,
605 msg: &str,
606 detail: Option<&str>,
607 answers: &[PromptButton],
608 ) -> Option<oneshot::Receiver<usize>> {
609 self.inner.prompt(level, msg, detail, answers)
610 }
611
612 fn activate(&self) {
613 self.inner.activate()
614 }
615
616 fn request_attention(&self) {
617 self.inner.request_attention()
618 }
619
620 fn is_active(&self) -> bool {
621 self.inner.is_active()
622 }
623
624 fn visibility(&self) -> WindowVisibility {
625 self.inner.visibility()
626 }
627
628 fn is_hovered(&self) -> bool {
629 self.inner.is_hovered()
630 }
631
632 fn background_appearance(&self) -> WindowBackgroundAppearance {
633 self.inner.background_appearance()
634 }
635
636 fn set_title(&mut self, title: &str) {
637 self.inner.set_title(title)
638 }
639
640 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
641 self.inner.set_background_appearance(background_appearance)
642 }
643
644 fn minimize(&self) {
645 self.inner.minimize()
646 }
647
648 fn zoom(&self) {
649 self.inner.zoom()
650 }
651
652 fn toggle_fullscreen(&self) {
653 self.inner.toggle_fullscreen()
654 }
655
656 fn is_fullscreen(&self) -> bool {
657 self.inner.is_fullscreen()
658 }
659
660 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
661 self.inner.frame_waker()
662 }
663
664 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
665 self.inner.on_request_frame(callback)
666 }
667
668 fn on_input(&self, mut callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
669 let state = self.state.clone();
670 self.inner.on_input(Box::new(move |input| {
671 callback(unzoom_input(input, state.zoom()))
672 }))
673 }
674
675 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
676 self.inner.on_active_status_change(callback)
677 }
678
679 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
680 self.inner.on_visibility_change(callback)
681 }
682
683 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
684 self.inner.on_hover_status_change(callback)
685 }
686
687 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
688 *self.state.on_resize.borrow_mut() = Some(callback);
689 let state = self.state.clone();
690 self.inner.on_resize(Box::new(move |size, scale| {
691 state.platform_size.set(size);
692 state.platform_scale.set(scale);
693 state.relayout();
694 }))
695 }
696
697 fn on_moved(&self, callback: Box<dyn FnMut()>) {
698 self.inner.on_moved(callback)
699 }
700
701 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
702 self.inner.on_should_close(callback)
703 }
704
705 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
706 self.inner.on_hit_test_window_control(callback)
707 }
708
709 fn on_close(&self, callback: Box<dyn FnOnce()>) {
710 self.inner.on_close(callback)
711 }
712
713 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
714 self.inner.on_appearance_changed(callback)
715 }
716
717 fn on_button_layout_changed(&self, callback: Box<dyn FnMut()>) {
718 self.inner.on_button_layout_changed(callback)
719 }
720
721 fn draw(&self, scene: &Scene) {
722 self.inner.draw(scene)
723 }
724
725 fn schedule_frame(&self) {
726 self.inner.schedule_frame()
727 }
728
729 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
730 self.inner.sprite_atlas()
731 }
732
733 fn is_subpixel_rendering_supported(&self) -> bool {
734 self.inner.is_subpixel_rendering_supported()
735 }
736
737 fn get_title(&self) -> String {
738 self.inner.get_title()
739 }
740
741 fn show_character_palette(&self) {
742 self.inner.show_character_palette()
743 }
744
745 fn titlebar_double_click(&self, is_resizable: bool, is_minimizable: bool) {
746 self.inner
747 .titlebar_double_click(is_resizable, is_minimizable)
748 }
749
750 fn native_window_state(&self) -> Option<Vec<u8>> {
751 self.inner.native_window_state()
752 }
753
754 fn restore_native_window_state(&self, state: &[u8]) {
755 self.inner.restore_native_window_state(state)
756 }
757
758 #[cfg(target_os = "windows")]
759 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
760 self.inner.get_raw_handle()
761 }
762
763 fn inner_window_bounds(&self) -> WindowBounds {
764 self.inner.inner_window_bounds()
765 }
766
767 fn request_decorations(&self, decorations: WindowDecorations) {
768 self.inner.request_decorations(decorations)
769 }
770
771 fn show_window_menu(&self, position: Point<Pixels>) {
772 self.inner
773 .show_window_menu(scale_point(position, self.state.zoom()))
774 }
775
776 fn start_window_move(&self) {
777 self.inner.start_window_move()
778 }
779
780 fn can_start_external_drag(&self) -> bool {
781 self.inner.can_start_external_drag()
782 }
783
784 fn start_external_drag(&self, payload: &ExternalDragPayload) -> bool {
785 self.inner.start_external_drag(payload)
786 }
787
788 fn start_window_resize(&self, edge: ResizeEdge) {
789 self.inner.start_window_resize(edge)
790 }
791
792 fn set_exclusive_zone(&self, zone: Pixels) {
793 self.inner.set_exclusive_zone(zone * self.state.zoom())
794 }
795
796 fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
797 let zoom = self.state.zoom();
798 let scaled: Option<Vec<Bounds<Pixels>>> = region.map(|region| {
799 region
800 .iter()
801 .map(|bounds| scale_bounds(*bounds, zoom))
802 .collect()
803 });
804 self.inner.set_input_region(scaled.as_deref())
805 }
806
807 fn window_decorations(&self) -> Decorations {
808 self.inner.window_decorations()
809 }
810
811 fn set_app_id(&mut self, app_id: &str) {
812 self.inner.set_app_id(app_id)
813 }
814
815 fn map_window(&mut self) -> Result<()> {
816 self.inner.map_window()
817 }
818
819 fn window_controls(&self) -> WindowControls {
820 self.inner.window_controls()
821 }
822
823 fn set_client_inset(&self, inset: Pixels) {
824 self.inner.set_client_inset(inset * self.state.zoom())
825 }
826
827 fn gpu_specs(&self) -> Option<GpuSpecs> {
828 self.inner.gpu_specs()
829 }
830
831 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
832 self.inner
833 .update_ime_position(scale_bounds(bounds, self.state.zoom()))
834 }
835
836 fn insets(&self) -> WindowInsets {
837 self.inner.insets()
838 }
839
840 fn on_insets_changed(&self, callback: Box<dyn FnMut(WindowInsets)>) {
841 self.inner.on_insets_changed(callback)
842 }
843
844 fn text_input_state_changed(&self, change: TextInputStateChange) {
845 self.inner.text_input_state_changed(change)
846 }
847
848 fn play_system_bell(&self) {
849 self.inner.play_system_bell()
850 }
851
852 fn a11y_init(&self, callbacks: A11yCallbacks) {
853 self.inner.a11y_init(callbacks)
854 }
855
856 fn a11y_tree_update(&self, tree_update: accesskit::TreeUpdate) {
857 self.inner.a11y_tree_update(tree_update)
858 }
859
860 fn a11y_update_window_bounds(&self) {
861 self.inner.a11y_update_window_bounds()
862 }
863 }
864
865 #[cfg(test)]
866 mod tests {
867 use gpui_kit::{
868 FileDropEvent, Modifiers, MouseButton, MouseDownEvent, PlatformInput, ScrollDelta,
869 ScrollWheelEvent, TouchPhase, point, px,
870 };
871
872 use super::unzoom_input;
873
874 #[test]
875 fn pointer_positions_move_into_the_zoomed_layout() {
876 let down = PlatformInput::MouseDown(MouseDownEvent {
877 button: MouseButton::Left,
878 position: point(px(300.), px(150.)),
879 modifiers: Modifiers::default(),
880 click_count: 1,
881 first_mouse: false,
882 });
883 let PlatformInput::MouseDown(event) = unzoom_input(down, 1.5) else {
884 panic!("mouse down stays a mouse down");
885 };
886 assert_eq!(event.position, point(px(200.), px(100.)));
887 }
888
889 #[test]
890 fn precise_scrolling_follows_the_finger_line_scrolling_keeps_its_lines() {
891 let wheel = |delta| {
892 PlatformInput::ScrollWheel(ScrollWheelEvent {
893 position: point(px(100.), px(100.)),
894 delta,
895 modifiers: Modifiers::default(),
896 touch_phase: TouchPhase::Moved,
897 })
898 };
899 let PlatformInput::ScrollWheel(pixels) =
900 unzoom_input(wheel(ScrollDelta::Pixels(point(px(0.), px(40.)))), 2.)
901 else {
902 panic!("scroll stays a scroll");
903 };
904 assert_eq!(pixels.position, point(px(50.), px(50.)));
905 assert!(
906 matches!(pixels.delta, ScrollDelta::Pixels(delta) if delta == point(px(0.), px(20.)))
907 );
908 let PlatformInput::ScrollWheel(lines) =
909 unzoom_input(wheel(ScrollDelta::Lines(point(0., 3.))), 2.)
910 else {
911 panic!("scroll stays a scroll");
912 };
913 assert!(matches!(lines.delta, ScrollDelta::Lines(delta) if delta == point(0., 3.)));
914 }
915
916 #[test]
917 fn file_drops_land_where_the_pointer_is() {
918 let drop = PlatformInput::FileDrop(FileDropEvent::Submit {
919 position: point(px(90.), px(30.)),
920 });
921 let PlatformInput::FileDrop(FileDropEvent::Submit { position }) = unzoom_input(drop, 1.25)
922 else {
923 panic!("drop stays a drop");
924 };
925 assert_eq!(position, point(px(72.), px(24.)));
926 }
927 }
@@ -0,0 +1,927 @@
1use std::cell::{Cell, RefCell};
2use std::ffi::OsString;
3use std::path::{Path, PathBuf};
4use std::rc::{Rc, Weak};
5use std::sync::Arc;
6
7use futures_channel::oneshot;
8use gpui_kit::*;
9use raw_window_handle::{
10 DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
11};
12
13use crate::appearance::DEFAULT_ZOOM;
14
15struct Shared {
16 factor: Cell<f32>,
17 executor: ForegroundExecutor,
18 windows: RefCell<Vec<Weak<WindowState>>>,
19}
20
21thread_local! {
22 static SHARED: RefCell<Option<Rc<Shared>>> = const { RefCell::new(None) };
23}
24
25pub fn factor() -> f32 {
26 SHARED.with(|shared| {
27 shared
28 .borrow()
29 .as_ref()
30 .map_or(DEFAULT_ZOOM, |shared| shared.factor.get())
31 })
32}
33
34pub fn set_factor(factor: f32) {
35 let Some(shared) = SHARED.with(|shared| shared.borrow().clone()) else {
36 return;
37 };
38 if (shared.factor.get() - factor).abs() < f32::EPSILON {
39 return;
40 }
41 shared.factor.set(factor);
42 let windows: Vec<Rc<WindowState>> = shared
43 .windows
44 .borrow_mut()
45 .drain(..)
46 .filter_map(|window| window.upgrade())
47 .collect();
48 shared
49 .windows
50 .borrow_mut()
51 .extend(windows.iter().map(Rc::downgrade));
52 shared
53 .executor
54 .spawn(async move {
55 for window in windows {
56 window.relayout();
57 }
58 })
59 .detach();
60}
61
62pub fn wrap(inner: Rc<dyn Platform>, initial_factor: f32) -> Rc<dyn Platform> {
63 let shared = Rc::new(Shared {
64 factor: Cell::new(initial_factor),
65 executor: inner.foreground_executor(),
66 windows: RefCell::new(Vec::new()),
67 });
68 SHARED.with(|slot| *slot.borrow_mut() = Some(shared.clone()));
69 Rc::new(ZoomPlatform { inner, shared })
70}
71
72pub fn zooms(params: &WindowParams) -> bool {
73 matches!(params.kind, WindowKind::Normal) && params.is_resizable
74}
75
76struct WindowState {
77 shared: Rc<Shared>,
78 zoomed: bool,
79 platform_size: Cell<Size<Pixels>>,
80 platform_scale: Cell<f32>,
81 on_resize: RefCell<Option<Box<dyn FnMut(Size<Pixels>, f32)>>>,
82}
83
84impl WindowState {
85 fn zoom(&self) -> f32 {
86 if self.zoomed {
87 self.shared.factor.get()
88 } else {
89 DEFAULT_ZOOM
90 }
91 }
92
93 fn relayout(&self) {
94 let zoom = self.zoom();
95 let size = self.platform_size.get();
96 let scale = self.platform_scale.get();
97 if let Ok(mut callback) = self.on_resize.try_borrow_mut()
98 && let Some(callback) = callback.as_mut()
99 {
100 callback(scale_size(size, 1. / zoom), scale * zoom);
101 }
102 }
103}
104
105fn scale_point(point: Point<Pixels>, factor: f32) -> Point<Pixels> {
106 gpui_kit::point(point.x * factor, point.y * factor)
107}
108
109fn scale_size(size: Size<Pixels>, factor: f32) -> Size<Pixels> {
110 gpui_kit::size(size.width * factor, size.height * factor)
111}
112
113fn scale_bounds(bounds: Bounds<Pixels>, factor: f32) -> Bounds<Pixels> {
114 Bounds {
115 origin: scale_point(bounds.origin, factor),
116 size: scale_size(bounds.size, factor),
117 }
118}
119
120fn unzoom_input(input: PlatformInput, zoom: f32) -> PlatformInput {
121 if (zoom - DEFAULT_ZOOM).abs() < f32::EPSILON {
122 return input;
123 }
124 let factor = 1. / zoom;
125 let scale = |point: Point<Pixels>| scale_point(point, factor);
126 match input {
127 PlatformInput::MouseDown(mut event) => {
128 event.position = scale(event.position);
129 PlatformInput::MouseDown(event)
130 }
131 PlatformInput::MouseUp(mut event) => {
132 event.position = scale(event.position);
133 PlatformInput::MouseUp(event)
134 }
135 PlatformInput::MousePressure(mut event) => {
136 event.position = scale(event.position);
137 PlatformInput::MousePressure(event)
138 }
139 PlatformInput::MouseMove(mut event) => {
140 event.position = scale(event.position);
141 PlatformInput::MouseMove(event)
142 }
143 PlatformInput::MouseExited(mut event) => {
144 event.position = scale(event.position);
145 PlatformInput::MouseExited(event)
146 }
147 PlatformInput::ScrollWheel(mut event) => {
148 event.position = scale(event.position);
149 if let ScrollDelta::Pixels(delta) = event.delta {
150 event.delta = ScrollDelta::Pixels(scale(delta));
151 }
152 PlatformInput::ScrollWheel(event)
153 }
154 PlatformInput::Pinch(mut event) => {
155 event.position = scale(event.position);
156 PlatformInput::Pinch(event)
157 }
158 PlatformInput::LongPress(mut event) => {
159 event.start_position = scale(event.start_position);
160 event.position = scale(event.position);
161 PlatformInput::LongPress(event)
162 }
163 PlatformInput::TouchDrag(mut event) => {
164 event.start_position = scale(event.start_position);
165 event.position = scale(event.position);
166 PlatformInput::TouchDrag(event)
167 }
168 PlatformInput::Touch(mut event) => {
169 event.position = scale(event.position);
170 event.predicted_position = event.predicted_position.map(scale);
171 PlatformInput::Touch(event)
172 }
173 PlatformInput::FileDrop(event) => PlatformInput::FileDrop(match event {
174 FileDropEvent::Entered { position, paths } => FileDropEvent::Entered {
175 position: scale(position),
176 paths,
177 },
178 FileDropEvent::Pending { position } => FileDropEvent::Pending {
179 position: scale(position),
180 },
181 FileDropEvent::Submit { position } => FileDropEvent::Submit {
182 position: scale(position),
183 },
184 other => other,
185 }),
186 other @ (PlatformInput::KeyDown(_)
187 | PlatformInput::KeyUp(_)
188 | PlatformInput::ModifiersChanged(_)) => other,
189 }
190}
191
192struct ZoomPlatform {
193 inner: Rc<dyn Platform>,
194 shared: Rc<Shared>,
195}
196
197impl Platform for ZoomPlatform {
198 fn background_executor(&self) -> BackgroundExecutor {
199 self.inner.background_executor()
200 }
201
202 fn foreground_executor(&self) -> ForegroundExecutor {
203 self.inner.foreground_executor()
204 }
205
206 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
207 self.inner.text_system()
208 }
209
210 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
211 self.inner.run(on_finish_launching)
212 }
213
214 fn quit(&self) {
215 self.inner.quit()
216 }
217
218 fn set_initial_windowing(&self, request: WindowingRequest) {
219 self.inner.set_initial_windowing(request)
220 }
221
222 fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> {
223 self.inner.request_windowing(request)
224 }
225
226 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>) {
227 self.inner.restart(binary_path, arguments)
228 }
229
230 fn activate(&self, ignoring_other_apps: bool) {
231 self.inner.activate(ignoring_other_apps)
232 }
233
234 fn set_activation_policy(&self, policy: ActivationPolicy) {
235 self.inner.set_activation_policy(policy)
236 }
237
238 fn hide(&self) {
239 self.inner.hide()
240 }
241
242 fn hide_other_apps(&self) {
243 self.inner.hide_other_apps()
244 }
245
246 fn unhide_other_apps(&self) {
247 self.inner.unhide_other_apps()
248 }
249
250 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
251 self.inner.displays()
252 }
253
254 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
255 self.inner.primary_display()
256 }
257
258 fn active_window(&self) -> Option<AnyWindowHandle> {
259 self.inner.active_window()
260 }
261
262 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
263 self.inner.window_stack()
264 }
265
266 fn is_screen_capture_supported(&self) -> bool {
267 self.inner.is_screen_capture_supported()
268 }
269
270 fn open_window(
271 &self,
272 handle: AnyWindowHandle,
273 options: WindowParams,
274 ) -> Result<Box<dyn PlatformWindow>> {
275 let zoomed = zooms(&options);
276 let inner = self.inner.open_window(handle, options)?;
277 let state = Rc::new(WindowState {
278 shared: self.shared.clone(),
279 zoomed,
280 platform_size: Cell::new(inner.content_size()),
281 platform_scale: Cell::new(inner.scale_factor()),
282 on_resize: RefCell::new(None),
283 });
284 self.shared.windows.borrow_mut().push(Rc::downgrade(&state));
285 Ok(Box::new(ZoomWindow { inner, state }))
286 }
287
288 fn window_appearance(&self) -> WindowAppearance {
289 self.inner.window_appearance()
290 }
291
292 fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
293 self.inner.set_window_appearance(appearance)
294 }
295
296 fn button_layout(&self) -> Option<WindowButtonLayout> {
297 self.inner.button_layout()
298 }
299
300 fn open_url(&self, url: &str) {
301 self.inner.open_url(url)
302 }
303
304 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
305 self.inner.on_open_urls(callback)
306 }
307
308 fn register_url_scheme(&self, url: &str) -> Task<Result<()>> {
309 self.inner.register_url_scheme(url)
310 }
311
312 fn prompt_for_paths(
313 &self,
314 options: PathPromptOptions,
315 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
316 self.inner.prompt_for_paths(options)
317 }
318
319 fn prompt_for_new_path(
320 &self,
321 directory: &Path,
322 suggested_name: Option<&str>,
323 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
324 self.inner.prompt_for_new_path(directory, suggested_name)
325 }
326
327 fn can_select_mixed_files_and_dirs(&self) -> bool {
328 self.inner.can_select_mixed_files_and_dirs()
329 }
330
331 fn reveal_path(&self, path: &Path) {
332 self.inner.reveal_path(path)
333 }
334
335 fn open_with_system(&self, path: &Path) {
336 self.inner.open_with_system(path)
337 }
338
339 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>) {
340 self.inner.on_quit(callback)
341 }
342
343 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
344 self.inner.on_reopen(callback)
345 }
346
347 fn on_system_sleep(&self, callback: Box<dyn FnMut()>) {
348 self.inner.on_system_sleep(callback)
349 }
350
351 fn on_system_wake(&self, callback: Box<dyn FnMut()>) {
352 self.inner.on_system_wake(callback)
353 }
354
355 fn on_app_lifecycle(&self, callback: Box<dyn FnMut(AppLifecyclePhase)>) {
356 self.inner.on_app_lifecycle(callback)
357 }
358
359 fn on_memory_warning(&self, callback: Box<dyn FnMut()>) {
360 self.inner.on_memory_warning(callback)
361 }
362
363 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
364 self.inner.gestures()
365 }
366
367 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
368 self.inner.set_menus(menus, keymap)
369 }
370
371 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
372 self.inner.get_menus()
373 }
374
375 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
376 self.inner.set_dock_menu(menu, keymap)
377 }
378
379 fn perform_dock_menu_action(&self, action: usize) {
380 self.inner.perform_dock_menu_action(action)
381 }
382
383 fn add_recent_document(&self, path: &Path) {
384 self.inner.add_recent_document(path)
385 }
386
387 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
388 self.inner.on_app_menu_action(callback)
389 }
390
391 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
392 self.inner.on_will_open_app_menu(callback)
393 }
394
395 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
396 self.inner.on_validate_app_menu_command(callback)
397 }
398
399 fn thermal_state(&self) -> ThermalState {
400 self.inner.thermal_state()
401 }
402
403 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
404 self.inner.on_thermal_state_change(callback)
405 }
406
407 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
408 self.inner.prevent_idle_sleep(reason)
409 }
410
411 fn set_app_identity(&self, identifier: &str, name: &str) {
412 self.inner.set_app_identity(identifier, name)
413 }
414
415 fn show_system_notification(&self, notification: SystemNotification) {
416 self.inner.show_system_notification(notification)
417 }
418
419 fn dismiss_system_notification(&self, tag: &str) {
420 self.inner.dismiss_system_notification(tag)
421 }
422
423 fn on_system_notification_response(
424 &self,
425 callback: Box<dyn FnMut(SystemNotificationResponse)>,
426 ) {
427 self.inner.on_system_notification_response(callback)
428 }
429
430 fn compositor_name(&self) -> &'static str {
431 self.inner.compositor_name()
432 }
433
434 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
435 self.inner.graphical_environment()
436 }
437
438 fn app_path(&self) -> Result<PathBuf> {
439 self.inner.app_path()
440 }
441
442 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
443 self.inner.path_for_auxiliary_executable(name)
444 }
445
446 fn set_cursor_style(&self, style: CursorStyle) {
447 self.inner.set_cursor_style(style)
448 }
449
450 fn hide_cursor_until_mouse_moves(&self) {
451 self.inner.hide_cursor_until_mouse_moves()
452 }
453
454 fn is_cursor_visible(&self) -> bool {
455 self.inner.is_cursor_visible()
456 }
457
458 fn should_auto_hide_scrollbars(&self) -> bool {
459 self.inner.should_auto_hide_scrollbars()
460 }
461
462 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
463 self.inner.read_from_clipboard()
464 }
465
466 fn write_to_clipboard(&self, item: ClipboardItem) {
467 self.inner.write_to_clipboard(item)
468 }
469
470 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
471 self.inner.read_from_clipboard_async()
472 }
473
474 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
475 fn read_from_primary(&self) -> Option<ClipboardItem> {
476 self.inner.read_from_primary()
477 }
478
479 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
480 fn write_to_primary(&self, item: ClipboardItem) {
481 self.inner.write_to_primary(item)
482 }
483
484 #[cfg(target_os = "macos")]
485 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
486 self.inner.read_from_find_pasteboard()
487 }
488
489 #[cfg(target_os = "macos")]
490 fn write_to_find_pasteboard(&self, item: ClipboardItem) {
491 self.inner.write_to_find_pasteboard(item)
492 }
493
494 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
495 self.inner.write_credentials(url, username, password)
496 }
497
498 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
499 self.inner.read_credentials(url)
500 }
501
502 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
503 self.inner.delete_credentials(url)
504 }
505
506 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
507 self.inner.keyboard_layout()
508 }
509
510 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
511 self.inner.keyboard_mapper()
512 }
513
514 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
515 self.inner.on_keyboard_layout_change(callback)
516 }
517}
518
519struct ZoomWindow {
520 inner: Box<dyn PlatformWindow>,
521 state: Rc<WindowState>,
522}
523
524impl HasWindowHandle for ZoomWindow {
525 fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
526 self.inner.window_handle()
527 }
528}
529
530impl HasDisplayHandle for ZoomWindow {
531 fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
532 self.inner.display_handle()
533 }
534}
535
536impl PlatformWindow for ZoomWindow {
537 fn bounds(&self) -> Bounds<Pixels> {
538 self.inner.bounds()
539 }
540
541 fn is_maximized(&self) -> bool {
542 self.inner.is_maximized()
543 }
544
545 fn window_bounds(&self) -> WindowBounds {
546 self.inner.window_bounds()
547 }
548
549 fn content_size(&self) -> Size<Pixels> {
550 scale_size(self.inner.content_size(), 1. / self.state.zoom())
551 }
552
553 fn on_visual_viewport_changed(&self, callback: Box<dyn FnMut()>) {
554 self.inner.on_visual_viewport_changed(callback)
555 }
556
557 fn prepare_frame(&self) -> bool {
558 self.inner.prepare_frame()
559 }
560
561 fn resize(&mut self, size: Size<Pixels>) {
562 let zoom = self.state.zoom();
563 self.inner.resize(scale_size(size, zoom))
564 }
565
566 fn scale_factor(&self) -> f32 {
567 self.inner.scale_factor() * self.state.zoom()
568 }
569
570 fn appearance(&self) -> WindowAppearance {
571 self.inner.appearance()
572 }
573
574 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
575 self.inner.display()
576 }
577
578 fn mouse_position(&self) -> Point<Pixels> {
579 scale_point(self.inner.mouse_position(), 1. / self.state.zoom())
580 }
581
582 fn modifiers(&self) -> Modifiers {
583 self.inner.modifiers()
584 }
585
586 fn capslock(&self) -> Capslock {
587 self.inner.capslock()
588 }
589
590 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
591 self.inner.set_input_handler(input_handler)
592 }
593
594 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
595 self.inner.take_input_handler()
596 }
597
598 fn set_text_input_configuration(&mut self, configuration: TextInputConfiguration) {
599 self.inner.set_text_input_configuration(configuration)
600 }
601
602 fn prompt(
603 &self,
604 level: PromptLevel,
605 msg: &str,
606 detail: Option<&str>,
607 answers: &[PromptButton],
608 ) -> Option<oneshot::Receiver<usize>> {
609 self.inner.prompt(level, msg, detail, answers)
610 }
611
612 fn activate(&self) {
613 self.inner.activate()
614 }
615
616 fn request_attention(&self) {
617 self.inner.request_attention()
618 }
619
620 fn is_active(&self) -> bool {
621 self.inner.is_active()
622 }
623
624 fn visibility(&self) -> WindowVisibility {
625 self.inner.visibility()
626 }
627
628 fn is_hovered(&self) -> bool {
629 self.inner.is_hovered()
630 }
631
632 fn background_appearance(&self) -> WindowBackgroundAppearance {
633 self.inner.background_appearance()
634 }
635
636 fn set_title(&mut self, title: &str) {
637 self.inner.set_title(title)
638 }
639
640 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
641 self.inner.set_background_appearance(background_appearance)
642 }
643
644 fn minimize(&self) {
645 self.inner.minimize()
646 }
647
648 fn zoom(&self) {
649 self.inner.zoom()
650 }
651
652 fn toggle_fullscreen(&self) {
653 self.inner.toggle_fullscreen()
654 }
655
656 fn is_fullscreen(&self) -> bool {
657 self.inner.is_fullscreen()
658 }
659
660 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
661 self.inner.frame_waker()
662 }
663
664 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
665 self.inner.on_request_frame(callback)
666 }
667
668 fn on_input(&self, mut callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
669 let state = self.state.clone();
670 self.inner.on_input(Box::new(move |input| {
671 callback(unzoom_input(input, state.zoom()))
672 }))
673 }
674
675 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
676 self.inner.on_active_status_change(callback)
677 }
678
679 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
680 self.inner.on_visibility_change(callback)
681 }
682
683 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
684 self.inner.on_hover_status_change(callback)
685 }
686
687 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
688 *self.state.on_resize.borrow_mut() = Some(callback);
689 let state = self.state.clone();
690 self.inner.on_resize(Box::new(move |size, scale| {
691 state.platform_size.set(size);
692 state.platform_scale.set(scale);
693 state.relayout();
694 }))
695 }
696
697 fn on_moved(&self, callback: Box<dyn FnMut()>) {
698 self.inner.on_moved(callback)
699 }
700
701 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
702 self.inner.on_should_close(callback)
703 }
704
705 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
706 self.inner.on_hit_test_window_control(callback)
707 }
708
709 fn on_close(&self, callback: Box<dyn FnOnce()>) {
710 self.inner.on_close(callback)
711 }
712
713 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
714 self.inner.on_appearance_changed(callback)
715 }
716
717 fn on_button_layout_changed(&self, callback: Box<dyn FnMut()>) {
718 self.inner.on_button_layout_changed(callback)
719 }
720
721 fn draw(&self, scene: &Scene) {
722 self.inner.draw(scene)
723 }
724
725 fn schedule_frame(&self) {
726 self.inner.schedule_frame()
727 }
728
729 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
730 self.inner.sprite_atlas()
731 }
732
733 fn is_subpixel_rendering_supported(&self) -> bool {
734 self.inner.is_subpixel_rendering_supported()
735 }
736
737 fn get_title(&self) -> String {
738 self.inner.get_title()
739 }
740
741 fn show_character_palette(&self) {
742 self.inner.show_character_palette()
743 }
744
745 fn titlebar_double_click(&self, is_resizable: bool, is_minimizable: bool) {
746 self.inner
747 .titlebar_double_click(is_resizable, is_minimizable)
748 }
749
750 fn native_window_state(&self) -> Option<Vec<u8>> {
751 self.inner.native_window_state()
752 }
753
754 fn restore_native_window_state(&self, state: &[u8]) {
755 self.inner.restore_native_window_state(state)
756 }
757
758 #[cfg(target_os = "windows")]
759 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
760 self.inner.get_raw_handle()
761 }
762
763 fn inner_window_bounds(&self) -> WindowBounds {
764 self.inner.inner_window_bounds()
765 }
766
767 fn request_decorations(&self, decorations: WindowDecorations) {
768 self.inner.request_decorations(decorations)
769 }
770
771 fn show_window_menu(&self, position: Point<Pixels>) {
772 self.inner
773 .show_window_menu(scale_point(position, self.state.zoom()))
774 }
775
776 fn start_window_move(&self) {
777 self.inner.start_window_move()
778 }
779
780 fn can_start_external_drag(&self) -> bool {
781 self.inner.can_start_external_drag()
782 }
783
784 fn start_external_drag(&self, payload: &ExternalDragPayload) -> bool {
785 self.inner.start_external_drag(payload)
786 }
787
788 fn start_window_resize(&self, edge: ResizeEdge) {
789 self.inner.start_window_resize(edge)
790 }
791
792 fn set_exclusive_zone(&self, zone: Pixels) {
793 self.inner.set_exclusive_zone(zone * self.state.zoom())
794 }
795
796 fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
797 let zoom = self.state.zoom();
798 let scaled: Option<Vec<Bounds<Pixels>>> = region.map(|region| {
799 region
800 .iter()
801 .map(|bounds| scale_bounds(*bounds, zoom))
802 .collect()
803 });
804 self.inner.set_input_region(scaled.as_deref())
805 }
806
807 fn window_decorations(&self) -> Decorations {
808 self.inner.window_decorations()
809 }
810
811 fn set_app_id(&mut self, app_id: &str) {
812 self.inner.set_app_id(app_id)
813 }
814
815 fn map_window(&mut self) -> Result<()> {
816 self.inner.map_window()
817 }
818
819 fn window_controls(&self) -> WindowControls {
820 self.inner.window_controls()
821 }
822
823 fn set_client_inset(&self, inset: Pixels) {
824 self.inner.set_client_inset(inset * self.state.zoom())
825 }
826
827 fn gpu_specs(&self) -> Option<GpuSpecs> {
828 self.inner.gpu_specs()
829 }
830
831 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
832 self.inner
833 .update_ime_position(scale_bounds(bounds, self.state.zoom()))
834 }
835
836 fn insets(&self) -> WindowInsets {
837 self.inner.insets()
838 }
839
840 fn on_insets_changed(&self, callback: Box<dyn FnMut(WindowInsets)>) {
841 self.inner.on_insets_changed(callback)
842 }
843
844 fn text_input_state_changed(&self, change: TextInputStateChange) {
845 self.inner.text_input_state_changed(change)
846 }
847
848 fn play_system_bell(&self) {
849 self.inner.play_system_bell()
850 }
851
852 fn a11y_init(&self, callbacks: A11yCallbacks) {
853 self.inner.a11y_init(callbacks)
854 }
855
856 fn a11y_tree_update(&self, tree_update: accesskit::TreeUpdate) {
857 self.inner.a11y_tree_update(tree_update)
858 }
859
860 fn a11y_update_window_bounds(&self) {
861 self.inner.a11y_update_window_bounds()
862 }
863}
864
865#[cfg(test)]
866mod tests {
867 use gpui_kit::{
868 FileDropEvent, Modifiers, MouseButton, MouseDownEvent, PlatformInput, ScrollDelta,
869 ScrollWheelEvent, TouchPhase, point, px,
870 };
871
872 use super::unzoom_input;
873
874 #[test]
875 fn pointer_positions_move_into_the_zoomed_layout() {
876 let down = PlatformInput::MouseDown(MouseDownEvent {
877 button: MouseButton::Left,
878 position: point(px(300.), px(150.)),
879 modifiers: Modifiers::default(),
880 click_count: 1,
881 first_mouse: false,
882 });
883 let PlatformInput::MouseDown(event) = unzoom_input(down, 1.5) else {
884 panic!("mouse down stays a mouse down");
885 };
886 assert_eq!(event.position, point(px(200.), px(100.)));
887 }
888
889 #[test]
890 fn precise_scrolling_follows_the_finger_line_scrolling_keeps_its_lines() {
891 let wheel = |delta| {
892 PlatformInput::ScrollWheel(ScrollWheelEvent {
893 position: point(px(100.), px(100.)),
894 delta,
895 modifiers: Modifiers::default(),
896 touch_phase: TouchPhase::Moved,
897 })
898 };
899 let PlatformInput::ScrollWheel(pixels) =
900 unzoom_input(wheel(ScrollDelta::Pixels(point(px(0.), px(40.)))), 2.)
901 else {
902 panic!("scroll stays a scroll");
903 };
904 assert_eq!(pixels.position, point(px(50.), px(50.)));
905 assert!(
906 matches!(pixels.delta, ScrollDelta::Pixels(delta) if delta == point(px(0.), px(20.)))
907 );
908 let PlatformInput::ScrollWheel(lines) =
909 unzoom_input(wheel(ScrollDelta::Lines(point(0., 3.))), 2.)
910 else {
911 panic!("scroll stays a scroll");
912 };
913 assert!(matches!(lines.delta, ScrollDelta::Lines(delta) if delta == point(0., 3.)));
914 }
915
916 #[test]
917 fn file_drops_land_where_the_pointer_is() {
918 let drop = PlatformInput::FileDrop(FileDropEvent::Submit {
919 position: point(px(90.), px(30.)),
920 });
921 let PlatformInput::FileDrop(FileDropEvent::Submit { position }) = unzoom_input(drop, 1.25)
922 else {
923 panic!("drop stays a drop");
924 };
925 assert_eq!(position, point(px(72.), px(24.)));
926 }
927}
crates/app-state/src/lib.rs +1 −1
@@ -48,5 +48,5 @@ pub use app_base::{
48 48 APP_NAME, appearance, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
49 49 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
50 50 emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
51 single_instance, stickers, theme, translation, updater, user_activity,
51 single_instance, stickers, theme, translation, updater, user_activity, zoom,
52 52 };
@@ -48,5 +48,5 @@ pub use app_base::{
48 APP_NAME, appearance, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
48 APP_NAME, appearance, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
49 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
49 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
50 emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
50 emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
51 single_instance, stickers, theme, translation, updater, user_activity,
51 single_instance, stickers, theme, translation, updater, user_activity, zoom,
52};
52};
crates/app-ui-kit/src/render/elements.rs +15 −4
@@ -7,8 +7,8 @@ use super::flow_text::{FlowSegment, FlowText};
7 7 use super::hooks::jump_to_quoted;
8 8 use super::selectable::{Pill, SelectableRichText};
9 9 use super::syntax::{self, Token};
10 use app_base::theme;
11 10 use crate::widgets::symbol;
11 use app_base::theme;
12 12
13 13 const LIST_GAP: f32 = 2.;
14 14 const MARKER_WIDTH: f32 = 18.;
@@ -449,14 +449,15 @@ fn readable(color: u32, own: bool) -> Hsla {
449 449 theme::bubble_other()
450 450 });
451 451 let mut foreground = rgb(color);
452 let target = if luminance(background) > 0.5 { 0. } else { 1. };
452 453 for _ in 0..10 {
453 454 if contrast(foreground, background) >= MIN_CONTRAST {
454 455 break;
455 456 }
456 457 foreground = Rgba {
457 r: foreground.r + (1. - foreground.r) * 0.2,
458 g: foreground.g + (1. - foreground.g) * 0.2,
459 b: foreground.b + (1. - foreground.b) * 0.2,
458 r: foreground.r + (target - foreground.r) * 0.2,
459 g: foreground.g + (target - foreground.g) * 0.2,
460 b: foreground.b + (target - foreground.b) * 0.2,
460 461 a: 1.,
461 462 };
462 463 }
@@ -499,4 +500,14 @@ mod tests {
499 500 fn light_text_color_stays_as_sent() {
500 501 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
501 502 }
503
504 #[test]
505 fn light_text_color_is_darkened_on_a_light_bubble() {
506 theme::set_thread_shade(Some(theme::Shade::Light));
507 let darkened = Rgba::from(readable(0xffd700, false));
508 let bubble = Rgba::from(theme::bubble_other());
509 theme::set_thread_shade(None);
510 assert!(contrast(darkened, bubble) >= MIN_CONTRAST);
511 assert!(darkened.r < 1.);
512 }
502 513 }
@@ -7,8 +7,8 @@ use super::flow_text::{FlowSegment, FlowText};
7use super::hooks::jump_to_quoted;
7use super::hooks::jump_to_quoted;
8use super::selectable::{Pill, SelectableRichText};
8use super::selectable::{Pill, SelectableRichText};
9use super::syntax::{self, Token};
9use super::syntax::{self, Token};
10use app_base::theme;
11use crate::widgets::symbol;
10use crate::widgets::symbol;
11use app_base::theme;
12
12
13const LIST_GAP: f32 = 2.;
13const LIST_GAP: f32 = 2.;
14const MARKER_WIDTH: f32 = 18.;
14const MARKER_WIDTH: f32 = 18.;
@@ -449,14 +449,15 @@ fn readable(color: u32, own: bool) -> Hsla {
449 theme::bubble_other()
449 theme::bubble_other()
450 });
450 });
451 let mut foreground = rgb(color);
451 let mut foreground = rgb(color);
452 let target = if luminance(background) > 0.5 { 0. } else { 1. };
452 for _ in 0..10 {
453 for _ in 0..10 {
453 if contrast(foreground, background) >= MIN_CONTRAST {
454 if contrast(foreground, background) >= MIN_CONTRAST {
454 break;
455 break;
455 }
456 }
456 foreground = Rgba {
457 foreground = Rgba {
457 r: foreground.r + (1. - foreground.r) * 0.2,
458 r: foreground.r + (target - foreground.r) * 0.2,
458 g: foreground.g + (1. - foreground.g) * 0.2,
459 g: foreground.g + (target - foreground.g) * 0.2,
459 b: foreground.b + (1. - foreground.b) * 0.2,
460 b: foreground.b + (target - foreground.b) * 0.2,
460 a: 1.,
461 a: 1.,
461 };
462 };
462 }
463 }
@@ -499,4 +500,14 @@ mod tests {
499 fn light_text_color_stays_as_sent() {
500 fn light_text_color_stays_as_sent() {
500 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
501 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
501 }
502 }
503
504 #[test]
505 fn light_text_color_is_darkened_on_a_light_bubble() {
506 theme::set_thread_shade(Some(theme::Shade::Light));
507 let darkened = Rgba::from(readable(0xffd700, false));
508 let bubble = Rgba::from(theme::bubble_other());
509 theme::set_thread_shade(None);
510 assert!(contrast(darkened, bubble) >= MIN_CONTRAST);
511 assert!(darkened.r < 1.);
512 }
502}
513}
crates/app/src/active_appearance.rs +120 −14
@@ -1,20 +1,35 @@
1 1 use gpui_kit::*;
2 2 use store::Store;
3 3
4 use crate::appearance::{self, AppIcon, AppearanceSettings};
4 use crate::appearance::{self, AppIcon, AppearanceSettings, SystemTheme, ThemeChoice};
5 5 use crate::theme::{self, ColorScheme};
6 use crate::zoom;
6 7
7 8 #[derive(Default)]
8 9 pub struct ActiveAppearance {
9 10 settings: AppearanceSettings,
11 system: SystemTheme,
10 12 }
11 13
12 14 impl Global for ActiveAppearance {}
13 15
16 pub fn system_theme(appearance: WindowAppearance) -> SystemTheme {
17 SystemTheme {
18 dark: matches!(
19 appearance,
20 WindowAppearance::Dark | WindowAppearance::VibrantDark
21 ),
22 high_contrast: appearance::system_high_contrast(),
23 }
24 }
25
14 26 pub fn install(store: &Store, cx: &mut App) {
15 27 let settings = appearance::load(store);
28 let system = system_theme(cx.window_appearance());
16 29 theme::set_active_scheme(settings.color_scheme.id);
17 cx.set_global(ActiveAppearance { settings });
30 theme::set_active_shade(settings.theme.shade(system));
31 zoom::set_factor(settings.zoom);
32 cx.set_global(ActiveAppearance { settings, system });
18 33 }
19 34
20 35 pub fn current(cx: &App) -> AppearanceSettings {
@@ -23,16 +38,56 @@ pub fn current(cx: &App) -> AppearanceSettings {
23 38 .unwrap_or_default()
24 39 }
25 40
41 fn system(cx: &App) -> SystemTheme {
42 cx.try_global::<ActiveAppearance>()
43 .map(|active| active.system)
44 .unwrap_or_default()
45 }
46
47 fn store_settings(settings: AppearanceSettings, store: &Store, cx: &mut App) {
48 appearance::save(store, &settings);
49 let system = system(cx);
50 cx.set_global(ActiveAppearance { settings, system });
51 }
52
53 fn restyle(cx: &mut App) {
54 let active = cx.global::<ActiveAppearance>();
55 let shade = active.settings.theme.shade(active.system);
56 let scheme = active.settings.color_scheme.id;
57 if theme::scheme().id != scheme || theme::shade() != shade {
58 theme::set_active_scheme(scheme);
59 theme::set_active_shade(shade);
60 theme::apply(cx);
61 }
62 cx.refresh_windows();
63 }
64
26 65 pub fn set_color_scheme(scheme: &'static ColorScheme, store: &Store, cx: &mut App) {
27 66 let settings = AppearanceSettings {
28 67 color_scheme: scheme,
29 68 ..current(cx)
30 69 };
31 appearance::save(store, &settings);
32 theme::set_active_scheme(scheme.id);
33 theme::apply(cx);
34 cx.set_global(ActiveAppearance { settings });
35 cx.refresh_windows();
70 store_settings(settings, store, cx);
71 restyle(cx);
72 }
73
74 pub fn set_theme(choice: ThemeChoice, store: &Store, cx: &mut App) {
75 let settings = AppearanceSettings {
76 theme: choice,
77 ..current(cx)
78 };
79 store_settings(settings, store, cx);
80 restyle(cx);
81 }
82
83 pub fn system_appearance_changed(appearance: WindowAppearance, cx: &mut App) {
84 let system = system_theme(appearance);
85 if cx.try_global::<ActiveAppearance>().is_none() || self::system(cx) == system {
86 return;
87 }
88 let settings = current(cx);
89 cx.set_global(ActiveAppearance { settings, system });
90 restyle(cx);
36 91 }
37 92
38 93 pub fn set_app_icon(icon: AppIcon, store: &Store, cx: &mut App) {
@@ -40,19 +95,33 @@ pub fn set_app_icon(icon: AppIcon, store: &Store, cx: &mut App) {
40 95 app_icon: icon,
41 96 ..current(cx)
42 97 };
43 appearance::save(store, &settings);
44 cx.set_global(ActiveAppearance { settings });
98 store_settings(settings, store, cx);
99 cx.refresh_windows();
100 }
101
102 pub fn set_zoom(zoom: f32, store: &Store, cx: &mut App) -> bool {
103 let current = current(cx);
104 if (current.zoom - zoom).abs() < f32::EPSILON {
105 return false;
106 }
107 let settings = AppearanceSettings { zoom, ..current };
108 store_settings(settings, store, cx);
109 zoom::set_factor(zoom);
45 110 cx.refresh_windows();
111 true
46 112 }
47 113
48 114 #[cfg(test)]
49 115 mod tests {
50 use gpui_kit::TestAppContext;
116 use gpui_kit::{TestAppContext, WindowAppearance};
51 117 use store::Store;
52 118
53 use super::{current, install, set_app_icon, set_color_scheme};
54 use crate::appearance::{self, AppIcon, AppearanceSettings};
55 use crate::theme;
119 use super::{
120 current, install, set_app_icon, set_color_scheme, set_theme, set_zoom,
121 system_appearance_changed,
122 };
123 use crate::appearance::{self, AppIcon, AppearanceSettings, ThemeChoice};
124 use crate::theme::{self, Shade};
56 125
57 126 #[gpui_kit::test]
58 127 fn switching_saves_and_applies_live(cx: &mut TestAppContext) {
@@ -61,16 +130,53 @@ mod tests {
61 130 gpui_kit::init(cx);
62 131 install(&store, cx);
63 132 theme::set_thread_scheme(None);
133 theme::set_thread_shade(None);
64 134 assert_eq!(current(cx), AppearanceSettings::default());
65 135 let teams = theme::scheme_by_id("teams").expect("teams scheme");
66 136 set_color_scheme(teams, &store, cx);
67 137 set_app_icon(AppIcon::MicrosoftTeams, &store, cx);
68 138 assert_eq!(theme::scheme().id, "teams");
69 assert_eq!(theme::accent(), theme::color(teams.accent));
139 assert_eq!(theme::accent(), theme::color(teams.dark.accent));
70 140 assert_eq!(appearance::load(&store), current(cx));
71 141 assert_eq!(current(cx).app_icon, AppIcon::MicrosoftTeams);
142 set_theme(ThemeChoice::Light, &store, cx);
143 assert_eq!(theme::shade(), Shade::Light);
144 assert_eq!(theme::background(), theme::color(teams.light.background));
145 assert_eq!(appearance::load(&store).theme, ThemeChoice::Light);
72 146 set_color_scheme(theme::default_scheme(), &store, cx);
147 set_theme(ThemeChoice::Dark, &store, cx);
73 148 assert_eq!(theme::scheme().id, "rusty-teams");
149 assert_eq!(theme::shade(), Shade::Dark);
150 });
151 }
152
153 #[gpui_kit::test]
154 fn follow_os_tracks_the_window_appearance_at_runtime(cx: &mut TestAppContext) {
155 let store = Store::open_in_memory().expect("in-memory store");
156 cx.update(|cx| {
157 gpui_kit::init(cx);
158 install(&store, cx);
159 set_theme(ThemeChoice::FollowOperatingSystem, &store, cx);
160 system_appearance_changed(WindowAppearance::Dark, cx);
161 assert_eq!(theme::shade(), Shade::Dark);
162 system_appearance_changed(WindowAppearance::Light, cx);
163 assert_eq!(theme::shade(), Shade::Light);
164 set_theme(ThemeChoice::Dark, &store, cx);
165 system_appearance_changed(WindowAppearance::Light, cx);
166 assert_eq!(theme::shade(), Shade::Dark);
167 });
168 }
169
170 #[gpui_kit::test]
171 fn zoom_is_saved_and_unchanged_steps_report_nothing(cx: &mut TestAppContext) {
172 let store = Store::open_in_memory().expect("in-memory store");
173 cx.update(|cx| {
174 gpui_kit::init(cx);
175 install(&store, cx);
176 assert!(set_zoom(1.25, &store, cx));
177 assert!(!set_zoom(1.25, &store, cx));
178 assert_eq!(appearance::load(&store).zoom, 1.25);
179 assert!(set_zoom(1., &store, cx));
74 180 });
75 181 }
76 182 }
@@ -1,20 +1,35 @@
1use gpui_kit::*;
1use gpui_kit::*;
2use store::Store;
2use store::Store;
3
3
4use crate::appearance::{self, AppIcon, AppearanceSettings};
4use crate::appearance::{self, AppIcon, AppearanceSettings, SystemTheme, ThemeChoice};
5use crate::theme::{self, ColorScheme};
5use crate::theme::{self, ColorScheme};
6use crate::zoom;
6
7
7#[derive(Default)]
8#[derive(Default)]
8pub struct ActiveAppearance {
9pub struct ActiveAppearance {
9 settings: AppearanceSettings,
10 settings: AppearanceSettings,
11 system: SystemTheme,
10}
12}
11
13
12impl Global for ActiveAppearance {}
14impl Global for ActiveAppearance {}
13
15
16pub fn system_theme(appearance: WindowAppearance) -> SystemTheme {
17 SystemTheme {
18 dark: matches!(
19 appearance,
20 WindowAppearance::Dark | WindowAppearance::VibrantDark
21 ),
22 high_contrast: appearance::system_high_contrast(),
23 }
24}
25
14pub fn install(store: &Store, cx: &mut App) {
26pub fn install(store: &Store, cx: &mut App) {
15 let settings = appearance::load(store);
27 let settings = appearance::load(store);
28 let system = system_theme(cx.window_appearance());
16 theme::set_active_scheme(settings.color_scheme.id);
29 theme::set_active_scheme(settings.color_scheme.id);
17 cx.set_global(ActiveAppearance { settings });
30 theme::set_active_shade(settings.theme.shade(system));
31 zoom::set_factor(settings.zoom);
32 cx.set_global(ActiveAppearance { settings, system });
18}
33}
19
34
20pub fn current(cx: &App) -> AppearanceSettings {
35pub fn current(cx: &App) -> AppearanceSettings {
@@ -23,16 +38,56 @@ pub fn current(cx: &App) -> AppearanceSettings {
23 .unwrap_or_default()
38 .unwrap_or_default()
24}
39}
25
40
41fn system(cx: &App) -> SystemTheme {
42 cx.try_global::<ActiveAppearance>()
43 .map(|active| active.system)
44 .unwrap_or_default()
45}
46
47fn store_settings(settings: AppearanceSettings, store: &Store, cx: &mut App) {
48 appearance::save(store, &settings);
49 let system = system(cx);
50 cx.set_global(ActiveAppearance { settings, system });
51}
52
53fn restyle(cx: &mut App) {
54 let active = cx.global::<ActiveAppearance>();
55 let shade = active.settings.theme.shade(active.system);
56 let scheme = active.settings.color_scheme.id;
57 if theme::scheme().id != scheme || theme::shade() != shade {
58 theme::set_active_scheme(scheme);
59 theme::set_active_shade(shade);
60 theme::apply(cx);
61 }
62 cx.refresh_windows();
63}
64
26pub fn set_color_scheme(scheme: &'static ColorScheme, store: &Store, cx: &mut App) {
65pub fn set_color_scheme(scheme: &'static ColorScheme, store: &Store, cx: &mut App) {
27 let settings = AppearanceSettings {
66 let settings = AppearanceSettings {
28 color_scheme: scheme,
67 color_scheme: scheme,
29 ..current(cx)
68 ..current(cx)
30 };
69 };
31 appearance::save(store, &settings);
70 store_settings(settings, store, cx);
32 theme::set_active_scheme(scheme.id);
71 restyle(cx);
33 theme::apply(cx);
72}
34 cx.set_global(ActiveAppearance { settings });
73
35 cx.refresh_windows();
74pub fn set_theme(choice: ThemeChoice, store: &Store, cx: &mut App) {
75 let settings = AppearanceSettings {
76 theme: choice,
77 ..current(cx)
78 };
79 store_settings(settings, store, cx);
80 restyle(cx);
81}
82
83pub fn system_appearance_changed(appearance: WindowAppearance, cx: &mut App) {
84 let system = system_theme(appearance);
85 if cx.try_global::<ActiveAppearance>().is_none() || self::system(cx) == system {
86 return;
87 }
88 let settings = current(cx);
89 cx.set_global(ActiveAppearance { settings, system });
90 restyle(cx);
36}
91}
37
92
38pub fn set_app_icon(icon: AppIcon, store: &Store, cx: &mut App) {
93pub fn set_app_icon(icon: AppIcon, store: &Store, cx: &mut App) {
@@ -40,19 +95,33 @@ pub fn set_app_icon(icon: AppIcon, store: &Store, cx: &mut App) {
40 app_icon: icon,
95 app_icon: icon,
41 ..current(cx)
96 ..current(cx)
42 };
97 };
43 appearance::save(store, &settings);
98 store_settings(settings, store, cx);
44 cx.set_global(ActiveAppearance { settings });
99 cx.refresh_windows();
100}
101
102pub fn set_zoom(zoom: f32, store: &Store, cx: &mut App) -> bool {
103 let current = current(cx);
104 if (current.zoom - zoom).abs() < f32::EPSILON {
105 return false;
106 }
107 let settings = AppearanceSettings { zoom, ..current };
108 store_settings(settings, store, cx);
109 zoom::set_factor(zoom);
45 cx.refresh_windows();
110 cx.refresh_windows();
111 true
46}
112}
47
113
48#[cfg(test)]
114#[cfg(test)]
49mod tests {
115mod tests {
50 use gpui_kit::TestAppContext;
116 use gpui_kit::{TestAppContext, WindowAppearance};
51 use store::Store;
117 use store::Store;
52
118
53 use super::{current, install, set_app_icon, set_color_scheme};
119 use super::{
54 use crate::appearance::{self, AppIcon, AppearanceSettings};
120 current, install, set_app_icon, set_color_scheme, set_theme, set_zoom,
55 use crate::theme;
121 system_appearance_changed,
122 };
123 use crate::appearance::{self, AppIcon, AppearanceSettings, ThemeChoice};
124 use crate::theme::{self, Shade};
56
125
57 #[gpui_kit::test]
126 #[gpui_kit::test]
58 fn switching_saves_and_applies_live(cx: &mut TestAppContext) {
127 fn switching_saves_and_applies_live(cx: &mut TestAppContext) {
@@ -61,16 +130,53 @@ mod tests {
61 gpui_kit::init(cx);
130 gpui_kit::init(cx);
62 install(&store, cx);
131 install(&store, cx);
63 theme::set_thread_scheme(None);
132 theme::set_thread_scheme(None);
133 theme::set_thread_shade(None);
64 assert_eq!(current(cx), AppearanceSettings::default());
134 assert_eq!(current(cx), AppearanceSettings::default());
65 let teams = theme::scheme_by_id("teams").expect("teams scheme");
135 let teams = theme::scheme_by_id("teams").expect("teams scheme");
66 set_color_scheme(teams, &store, cx);
136 set_color_scheme(teams, &store, cx);
67 set_app_icon(AppIcon::MicrosoftTeams, &store, cx);
137 set_app_icon(AppIcon::MicrosoftTeams, &store, cx);
68 assert_eq!(theme::scheme().id, "teams");
138 assert_eq!(theme::scheme().id, "teams");
69 assert_eq!(theme::accent(), theme::color(teams.accent));
139 assert_eq!(theme::accent(), theme::color(teams.dark.accent));
70 assert_eq!(appearance::load(&store), current(cx));
140 assert_eq!(appearance::load(&store), current(cx));
71 assert_eq!(current(cx).app_icon, AppIcon::MicrosoftTeams);
141 assert_eq!(current(cx).app_icon, AppIcon::MicrosoftTeams);
142 set_theme(ThemeChoice::Light, &store, cx);
143 assert_eq!(theme::shade(), Shade::Light);
144 assert_eq!(theme::background(), theme::color(teams.light.background));
145 assert_eq!(appearance::load(&store).theme, ThemeChoice::Light);
72 set_color_scheme(theme::default_scheme(), &store, cx);
146 set_color_scheme(theme::default_scheme(), &store, cx);
147 set_theme(ThemeChoice::Dark, &store, cx);
73 assert_eq!(theme::scheme().id, "rusty-teams");
148 assert_eq!(theme::scheme().id, "rusty-teams");
149 assert_eq!(theme::shade(), Shade::Dark);
150 });
151 }
152
153 #[gpui_kit::test]
154 fn follow_os_tracks_the_window_appearance_at_runtime(cx: &mut TestAppContext) {
155 let store = Store::open_in_memory().expect("in-memory store");
156 cx.update(|cx| {
157 gpui_kit::init(cx);
158 install(&store, cx);
159 set_theme(ThemeChoice::FollowOperatingSystem, &store, cx);
160 system_appearance_changed(WindowAppearance::Dark, cx);
161 assert_eq!(theme::shade(), Shade::Dark);
162 system_appearance_changed(WindowAppearance::Light, cx);
163 assert_eq!(theme::shade(), Shade::Light);
164 set_theme(ThemeChoice::Dark, &store, cx);
165 system_appearance_changed(WindowAppearance::Light, cx);
166 assert_eq!(theme::shade(), Shade::Dark);
167 });
168 }
169
170 #[gpui_kit::test]
171 fn zoom_is_saved_and_unchanged_steps_report_nothing(cx: &mut TestAppContext) {
172 let store = Store::open_in_memory().expect("in-memory store");
173 cx.update(|cx| {
174 gpui_kit::init(cx);
175 install(&store, cx);
176 assert!(set_zoom(1.25, &store, cx));
177 assert!(!set_zoom(1.25, &store, cx));
178 assert_eq!(appearance::load(&store).zoom, 1.25);
179 assert!(set_zoom(1., &store, cx));
74 });
180 });
75 }
181 }
76}
182}
crates/app/src/layout_guard.rs +31 −3
@@ -315,6 +315,7 @@ mod frames {
315 315 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
316 316 const TOLERANCE: f32 = 0.5;
317 317 const KNOWN_VIOLATIONS: &[&str] = &[];
318 const ZOOM_STEP: f32 = 1.25;
318 319
319 320 type Tag = (&'static str, Bounds<Pixels>);
320 321
@@ -730,11 +731,31 @@ mod frames {
730 731
731 732 #[gpui_kit::test]
732 733 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
734 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
735 }
736
737 #[gpui_kit::test]
738 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
739 let (width, height) = SIZES[1];
740 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
741 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
742 }
743
744 fn check_layout(
745 cx: &mut TestAppContext,
746 sizes: &[(f32, f32)],
747 zoom: f32,
748 known_violations: &[&str],
749 ) {
733 750 let (handle, app) = mount(cx);
751 let platform_scale = cx
752 .update_window(handle, |_, window, _| window.scale_factor())
753 .expect("test window");
754 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
734 755 let mut visual = VisualTestContext::from_window(handle, cx);
735 756 let mut seen_known = HashSet::new();
736 757 let mut unexpected = Vec::new();
737 for (width, height) in SIZES {
758 for &(width, height) in sizes {
738 759 visual.simulate_resize(size(px(width), px(height)));
739 760 let window = Bounds {
740 761 origin: point(px(0.), px(0.)),
@@ -919,7 +940,7 @@ mod frames {
919 940 }
920 941 for (key, message) in found {
921 942 let full_key = format!("{screen_name}@{width}x{height}:{key}");
922 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
943 if known_violations.contains(&full_key.as_str()) {
923 944 seen_known.insert(full_key);
924 945 } else {
925 946 unexpected.push(format!("{full_key}: {message}"));
@@ -927,7 +948,7 @@ mod frames {
927 948 }
928 949 }
929 950 }
930 let stale: Vec<String> = KNOWN_VIOLATIONS
951 let stale: Vec<String> = known_violations
931 952 .iter()
932 953 .filter(|key| !seen_known.contains(**key))
933 954 .map(|key| format!("stale known violation, remove it: {key}"))
@@ -1195,6 +1216,13 @@ mod frames {
1195 1216 crate::theme::set_thread_scheme(None);
1196 1217 }
1197 1218
1219 #[gpui_kit::test]
1220 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1221 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1222 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1223 crate::theme::set_thread_shade(None);
1224 }
1225
1198 1226 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1199 1227 let (handle, state) = mount_with(cx, true);
1200 1228 let mut visual = VisualTestContext::from_window(handle, cx);
@@ -315,6 +315,7 @@ mod frames {
315 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
315 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
316 const TOLERANCE: f32 = 0.5;
316 const TOLERANCE: f32 = 0.5;
317 const KNOWN_VIOLATIONS: &[&str] = &[];
317 const KNOWN_VIOLATIONS: &[&str] = &[];
318 const ZOOM_STEP: f32 = 1.25;
318
319
319 type Tag = (&'static str, Bounds<Pixels>);
320 type Tag = (&'static str, Bounds<Pixels>);
320
321
@@ -730,11 +731,31 @@ mod frames {
730
731
731 #[gpui_kit::test]
732 #[gpui_kit::test]
732 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
733 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
734 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
735 }
736
737 #[gpui_kit::test]
738 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
739 let (width, height) = SIZES[1];
740 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
741 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
742 }
743
744 fn check_layout(
745 cx: &mut TestAppContext,
746 sizes: &[(f32, f32)],
747 zoom: f32,
748 known_violations: &[&str],
749 ) {
733 let (handle, app) = mount(cx);
750 let (handle, app) = mount(cx);
751 let platform_scale = cx
752 .update_window(handle, |_, window, _| window.scale_factor())
753 .expect("test window");
754 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
734 let mut visual = VisualTestContext::from_window(handle, cx);
755 let mut visual = VisualTestContext::from_window(handle, cx);
735 let mut seen_known = HashSet::new();
756 let mut seen_known = HashSet::new();
736 let mut unexpected = Vec::new();
757 let mut unexpected = Vec::new();
737 for (width, height) in SIZES {
758 for &(width, height) in sizes {
738 visual.simulate_resize(size(px(width), px(height)));
759 visual.simulate_resize(size(px(width), px(height)));
739 let window = Bounds {
760 let window = Bounds {
740 origin: point(px(0.), px(0.)),
761 origin: point(px(0.), px(0.)),
@@ -919,7 +940,7 @@ mod frames {
919 }
940 }
920 for (key, message) in found {
941 for (key, message) in found {
921 let full_key = format!("{screen_name}@{width}x{height}:{key}");
942 let full_key = format!("{screen_name}@{width}x{height}:{key}");
922 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
943 if known_violations.contains(&full_key.as_str()) {
923 seen_known.insert(full_key);
944 seen_known.insert(full_key);
924 } else {
945 } else {
925 unexpected.push(format!("{full_key}: {message}"));
946 unexpected.push(format!("{full_key}: {message}"));
@@ -927,7 +948,7 @@ mod frames {
927 }
948 }
928 }
949 }
929 }
950 }
930 let stale: Vec<String> = KNOWN_VIOLATIONS
951 let stale: Vec<String> = known_violations
931 .iter()
952 .iter()
932 .filter(|key| !seen_known.contains(**key))
953 .filter(|key| !seen_known.contains(**key))
933 .map(|key| format!("stale known violation, remove it: {key}"))
954 .map(|key| format!("stale known violation, remove it: {key}"))
@@ -1195,6 +1216,13 @@ mod frames {
1195 crate::theme::set_thread_scheme(None);
1216 crate::theme::set_thread_scheme(None);
1196 }
1217 }
1197
1218
1219 #[gpui_kit::test]
1220 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1221 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1222 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1223 crate::theme::set_thread_shade(None);
1224 }
1225
1198 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1226 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1199 let (handle, state) = mount_with(cx, true);
1227 let (handle, state) = mount_with(cx, true);
1200 let mut visual = VisualTestContext::from_window(handle, cx);
1228 let mut visual = VisualTestContext::from_window(handle, cx);
crates/app/src/main.rs +3 −1
@@ -178,7 +178,9 @@ fn main() {
178 178 backend::start(store.clone(), transport, !arguments.read_only, activity)
179 179 });
180 180
181 let mut application = gpui_kit::application();
181 let startup_zoom = appearance::load(&store).zoom;
182 let platform = zoom::wrap(gpui_kit::platform::current_platform(false), startup_zoom);
183 let mut application = Application::with_platform(platform);
182 184 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
183 185 application = application.with_http_client(Arc::new(http_client));
184 186 }
@@ -178,7 +178,9 @@ fn main() {
178 backend::start(store.clone(), transport, !arguments.read_only, activity)
178 backend::start(store.clone(), transport, !arguments.read_only, activity)
179 });
179 });
180
180
181 let mut application = gpui_kit::application();
181 let startup_zoom = appearance::load(&store).zoom;
182 let platform = zoom::wrap(gpui_kit::platform::current_platform(false), startup_zoom);
183 let mut application = Application::with_platform(platform);
182 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
184 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
183 application = application.with_http_client(Arc::new(http_client));
185 application = application.with_http_client(Arc::new(http_client));
184 }
186 }
crates/app/src/notify/toast.rs +2 −2
@@ -367,12 +367,12 @@ impl ToastView {
367 367 .items_center()
368 368 .justify_center()
369 369 .rounded(px(8.))
370 .child(symbol("keyboard_return", 20., white()))
370 .child(symbol("keyboard_return", 20., theme::text()))
371 371 .when(empty, |button| button.opacity(0.4))
372 372 .when(!empty, |button| {
373 373 button
374 374 .cursor_pointer()
375 .hover(|button| button.bg(white().opacity(0.1)))
375 .hover(|button| button.bg(theme::popup_hover()))
376 376 .on_click(cx.listener(|this, _, window, cx| {
377 377 cx.stop_propagation();
378 378 this.submit(window, cx);
@@ -367,12 +367,12 @@ impl ToastView {
367 .items_center()
367 .items_center()
368 .justify_center()
368 .justify_center()
369 .rounded(px(8.))
369 .rounded(px(8.))
370 .child(symbol("keyboard_return", 20., white()))
370 .child(symbol("keyboard_return", 20., theme::text()))
371 .when(empty, |button| button.opacity(0.4))
371 .when(empty, |button| button.opacity(0.4))
372 .when(!empty, |button| {
372 .when(!empty, |button| {
373 button
373 button
374 .cursor_pointer()
374 .cursor_pointer()
375 .hover(|button| button.bg(white().opacity(0.1)))
375 .hover(|button| button.bg(theme::popup_hover()))
376 .on_click(cx.listener(|this, _, window, cx| {
376 .on_click(cx.listener(|this, _, window, cx| {
377 cx.stop_propagation();
377 cx.stop_propagation();
378 this.submit(window, cx);
378 this.submit(window, cx);
crates/app/src/settings/appearance.rs +37 −13
@@ -2,11 +2,11 @@ use gpui_kit::component::{h_flex, v_flex};
2 2 use gpui_kit::prelude::FluentBuilder as _;
3 3 use gpui_kit::*;
4 4
5 use super::rows::{ROW_INSET, caption, titled};
5 use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
6 6 use crate::active_appearance;
7 7 use crate::app_state::AppState;
8 use crate::appearance::AppIcon;
9 use crate::theme::{self, ColorScheme};
8 use crate::appearance::{AppIcon, ThemeChoice};
9 use crate::theme::{self, Palette};
10 10 use crate::views::title_bar::app_icon_image;
11 11
12 12 const TILE_WIDTH: f32 = 168.;
@@ -19,6 +19,9 @@ const PREVIEW_ICON_SIZE: f32 = 48.;
19 19 const RADIO_SIZE: f32 = 16.;
20 20 const RADIO_DOT_SIZE: f32 = 8.;
21 21 const COLOR_SCHEME_DETAIL: &str = "The colors to use for Rusty Teams";
22 const THEME_TITLE: &str = "Theme";
23 const THEME_DETAIL: &str = "The theme to use for Teams";
24 const THEME_SELECT_WIDTH: f32 = 240.;
22 25 #[cfg(windows)]
23 26 const APP_ICON_DETAIL: &str =
24 27 "Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe";
@@ -33,7 +36,7 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
33 36 SharedString::from(format!("settings-color-scheme-{}", scheme.id)),
34 37 scheme.name,
35 38 scheme.id == current.color_scheme.id,
36 scheme_preview(scheme),
39 scheme_preview(scheme.palette(theme::shade())),
37 40 )
38 41 .on_click(move |_, _, cx| {
39 42 let store = app.read(cx).store.clone();
@@ -53,9 +56,30 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
53 56 active_appearance::set_app_icon(icon, &store, cx);
54 57 })
55 58 });
59 let theme_choices = ThemeChoice::ALL
60 .into_iter()
61 .map(|choice| {
62 let app = app.clone();
63 Choice::new(choice.label(), choice == current.theme, move |cx| {
64 let store = app.read(cx).store.clone();
65 active_appearance::set_theme(choice, &store, cx);
66 })
67 })
68 .collect();
56 69 v_flex()
57 70 .w_full()
58 71 .child(caption("THEME"))
72 .child(control_row(
73 THEME_TITLE,
74 THEME_DETAIL,
75 select_with_width(
76 "settings-theme",
77 current.theme.label(),
78 THEME_SELECT_WIDTH,
79 false,
80 theme_choices,
81 ),
82 ))
59 83 .child(choice_group(
60 84 "Color scheme",
61 85 COLOR_SCHEME_DETAIL,
@@ -148,10 +172,10 @@ fn preview_frame(background: Hsla) -> Div {
148 172 .bg(background)
149 173 }
150 174
151 fn scheme_preview(scheme: &ColorScheme) -> Div {
175 fn scheme_preview(palette: &Palette) -> Div {
152 176 let fill = |hex: u32| theme::color(hex);
153 177 let bubble = |hex: u32, width: f32| div().w(px(width)).h(px(12.)).rounded(px(6.)).bg(fill(hex));
154 preview_frame(fill(scheme.background)).child(
178 preview_frame(fill(palette.background)).child(
155 179 h_flex()
156 180 .size_full()
157 181 .p(px(6.))
@@ -166,9 +190,9 @@ fn scheme_preview(scheme: &ColorScheme) -> Div {
166 190 div()
167 191 .size(px(10.))
168 192 .rounded(px(3.))
169 .bg(fill(scheme.surface_raised)),
193 .bg(fill(palette.surface_raised)),
170 194 )
171 .child(div().size(px(10.)).rounded(px(3.)).bg(fill(scheme.accent))),
195 .child(div().size(px(10.)).rounded(px(3.)).bg(fill(palette.accent))),
172 196 )
173 197 .child(
174 198 v_flex()
@@ -177,14 +201,14 @@ fn scheme_preview(scheme: &ColorScheme) -> Div {
177 201 .p(px(8.))
178 202 .gap(px(6.))
179 203 .rounded(px(6.))
180 .bg(fill(scheme.surface))
181 .child(h_flex().child(bubble(scheme.bubble_other, 64.)))
182 .child(h_flex().justify_end().child(bubble(scheme.bubble_own, 52.)))
183 .child(h_flex().child(bubble(scheme.bubble_other, 40.)))
204 .bg(fill(palette.surface))
205 .child(h_flex().child(bubble(palette.bubble_other, 64.)))
206 .child(h_flex().justify_end().child(bubble(palette.bubble_own, 52.)))
207 .child(h_flex().child(bubble(palette.bubble_other, 40.)))
184 208 .child(
185 209 h_flex()
186 210 .justify_end()
187 .child(div().size(px(12.)).rounded_full().bg(fill(scheme.accent))),
211 .child(div().size(px(12.)).rounded_full().bg(fill(palette.accent))),
188 212 ),
189 213 ),
190 214 )
@@ -2,11 +2,11 @@ use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
3use gpui_kit::*;
4
4
5use super::rows::{ROW_INSET, caption, titled};
5use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
6use crate::active_appearance;
6use crate::active_appearance;
7use crate::app_state::AppState;
7use crate::app_state::AppState;
8use crate::appearance::AppIcon;
8use crate::appearance::{AppIcon, ThemeChoice};
9use crate::theme::{self, ColorScheme};
9use crate::theme::{self, Palette};
10use crate::views::title_bar::app_icon_image;
10use crate::views::title_bar::app_icon_image;
11
11
12const TILE_WIDTH: f32 = 168.;
12const TILE_WIDTH: f32 = 168.;
@@ -19,6 +19,9 @@ const PREVIEW_ICON_SIZE: f32 = 48.;
19const RADIO_SIZE: f32 = 16.;
19const RADIO_SIZE: f32 = 16.;
20const RADIO_DOT_SIZE: f32 = 8.;
20const RADIO_DOT_SIZE: f32 = 8.;
21const COLOR_SCHEME_DETAIL: &str = "The colors to use for Rusty Teams";
21const COLOR_SCHEME_DETAIL: &str = "The colors to use for Rusty Teams";
22const THEME_TITLE: &str = "Theme";
23const THEME_DETAIL: &str = "The theme to use for Teams";
24const THEME_SELECT_WIDTH: f32 = 240.;
22#[cfg(windows)]
25#[cfg(windows)]
23const APP_ICON_DETAIL: &str =
26const APP_ICON_DETAIL: &str =
24 "Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe";
27 "Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe";
@@ -33,7 +36,7 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
33 SharedString::from(format!("settings-color-scheme-{}", scheme.id)),
36 SharedString::from(format!("settings-color-scheme-{}", scheme.id)),
34 scheme.name,
37 scheme.name,
35 scheme.id == current.color_scheme.id,
38 scheme.id == current.color_scheme.id,
36 scheme_preview(scheme),
39 scheme_preview(scheme.palette(theme::shade())),
37 )
40 )
38 .on_click(move |_, _, cx| {
41 .on_click(move |_, _, cx| {
39 let store = app.read(cx).store.clone();
42 let store = app.read(cx).store.clone();
@@ -53,9 +56,30 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
53 active_appearance::set_app_icon(icon, &store, cx);
56 active_appearance::set_app_icon(icon, &store, cx);
54 })
57 })
55 });
58 });
59 let theme_choices = ThemeChoice::ALL
60 .into_iter()
61 .map(|choice| {
62 let app = app.clone();
63 Choice::new(choice.label(), choice == current.theme, move |cx| {
64 let store = app.read(cx).store.clone();
65 active_appearance::set_theme(choice, &store, cx);
66 })
67 })
68 .collect();
56 v_flex()
69 v_flex()
57 .w_full()
70 .w_full()
58 .child(caption("THEME"))
71 .child(caption("THEME"))
72 .child(control_row(
73 THEME_TITLE,
74 THEME_DETAIL,
75 select_with_width(
76 "settings-theme",
77 current.theme.label(),
78 THEME_SELECT_WIDTH,
79 false,
80 theme_choices,
81 ),
82 ))
59 .child(choice_group(
83 .child(choice_group(
60 "Color scheme",
84 "Color scheme",
61 COLOR_SCHEME_DETAIL,
85 COLOR_SCHEME_DETAIL,
@@ -148,10 +172,10 @@ fn preview_frame(background: Hsla) -> Div {
148 .bg(background)
172 .bg(background)
149}
173}
150
174
151fn scheme_preview(scheme: &ColorScheme) -> Div {
175fn scheme_preview(palette: &Palette) -> Div {
152 let fill = |hex: u32| theme::color(hex);
176 let fill = |hex: u32| theme::color(hex);
153 let bubble = |hex: u32, width: f32| div().w(px(width)).h(px(12.)).rounded(px(6.)).bg(fill(hex));
177 let bubble = |hex: u32, width: f32| div().w(px(width)).h(px(12.)).rounded(px(6.)).bg(fill(hex));
154 preview_frame(fill(scheme.background)).child(
178 preview_frame(fill(palette.background)).child(
155 h_flex()
179 h_flex()
156 .size_full()
180 .size_full()
157 .p(px(6.))
181 .p(px(6.))
@@ -166,9 +190,9 @@ fn scheme_preview(scheme: &ColorScheme) -> Div {
166 div()
190 div()
167 .size(px(10.))
191 .size(px(10.))
168 .rounded(px(3.))
192 .rounded(px(3.))
169 .bg(fill(scheme.surface_raised)),
193 .bg(fill(palette.surface_raised)),
170 )
194 )
171 .child(div().size(px(10.)).rounded(px(3.)).bg(fill(scheme.accent))),
195 .child(div().size(px(10.)).rounded(px(3.)).bg(fill(palette.accent))),
172 )
196 )
173 .child(
197 .child(
174 v_flex()
198 v_flex()
@@ -177,14 +201,14 @@ fn scheme_preview(scheme: &ColorScheme) -> Div {
177 .p(px(8.))
201 .p(px(8.))
178 .gap(px(6.))
202 .gap(px(6.))
179 .rounded(px(6.))
203 .rounded(px(6.))
180 .bg(fill(scheme.surface))
204 .bg(fill(palette.surface))
181 .child(h_flex().child(bubble(scheme.bubble_other, 64.)))
205 .child(h_flex().child(bubble(palette.bubble_other, 64.)))
182 .child(h_flex().justify_end().child(bubble(scheme.bubble_own, 52.)))
206 .child(h_flex().justify_end().child(bubble(palette.bubble_own, 52.)))
183 .child(h_flex().child(bubble(scheme.bubble_other, 40.)))
207 .child(h_flex().child(bubble(palette.bubble_other, 40.)))
184 .child(
208 .child(
185 h_flex()
209 h_flex()
186 .justify_end()
210 .justify_end()
187 .child(div().size(px(12.)).rounded_full().bg(fill(scheme.accent))),
211 .child(div().size(px(12.)).rounded_full().bg(fill(palette.accent))),
188 ),
212 ),
189 ),
213 ),
190 )
214 )
crates/app/src/views/composer.rs +2 −2
@@ -2667,7 +2667,7 @@ impl Render for Composer {
2667 2667 .items_center()
2668 2668 .justify_center()
2669 2669 .rounded(px(8.))
2670 .child(symbol("keyboard_return", 20., white()))
2670 .child(symbol("keyboard_return", 20., theme::text()))
2671 2671 .on_mouse_down(
2672 2672 MouseButton::Right,
2673 2673 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
@@ -2676,7 +2676,7 @@ impl Render for Composer {
2676 2676 .when(can_send, |button| {
2677 2677 button
2678 2678 .cursor_pointer()
2679 .hover(|button| button.bg(white().opacity(0.1)))
2679 .hover(|button| button.bg(theme::popup_hover()))
2680 2680 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2681 2681 });
2682 2682 let fun = can_attach.then(|| {
@@ -2667,7 +2667,7 @@ impl Render for Composer {
2667 .items_center()
2667 .items_center()
2668 .justify_center()
2668 .justify_center()
2669 .rounded(px(8.))
2669 .rounded(px(8.))
2670 .child(symbol("keyboard_return", 20., white()))
2670 .child(symbol("keyboard_return", 20., theme::text()))
2671 .on_mouse_down(
2671 .on_mouse_down(
2672 MouseButton::Right,
2672 MouseButton::Right,
2673 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
2673 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
@@ -2676,7 +2676,7 @@ impl Render for Composer {
2676 .when(can_send, |button| {
2676 .when(can_send, |button| {
2677 button
2677 button
2678 .cursor_pointer()
2678 .cursor_pointer()
2679 .hover(|button| button.bg(white().opacity(0.1)))
2679 .hover(|button| button.bg(theme::popup_hover()))
2680 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2680 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2681 });
2681 });
2682 let fun = can_attach.then(|| {
2682 let fun = can_attach.then(|| {
crates/app/src/views/image_viewer.rs +4 −0
@@ -10,6 +10,7 @@ use gpui_kit::*;
10 10 use image::{Frame, ImageReader};
11 11
12 12 use super::avatar::person_avatar;
13 use super::shortcuts::{ZoomIn, ZoomOut, ZoomReset};
13 14 use super::widgets::symbol;
14 15 use crate::app_state::AppState;
15 16 use crate::downloads;
@@ -985,6 +986,9 @@ impl Render for ImageViewer {
985 986 .bg(rgba(BACKDROP))
986 987 .occlude()
987 988 .on_key_down(cx.listener(Self::on_key_down))
989 .on_action(cx.listener(|this, _: &ZoomIn, window, cx| this.zoom_step(1, window, cx)))
990 .on_action(cx.listener(|this, _: &ZoomOut, window, cx| this.zoom_step(-1, window, cx)))
991 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| this.zoom_fit(cx)))
988 992 .on_scroll_wheel(cx.listener(Self::on_wheel))
989 993 .on_mouse_move(cx.listener(Self::on_mouse_move))
990 994 .on_mouse_up(
@@ -10,6 +10,7 @@ use gpui_kit::*;
10use image::{Frame, ImageReader};
10use image::{Frame, ImageReader};
11
11
12use super::avatar::person_avatar;
12use super::avatar::person_avatar;
13use super::shortcuts::{ZoomIn, ZoomOut, ZoomReset};
13use super::widgets::symbol;
14use super::widgets::symbol;
14use crate::app_state::AppState;
15use crate::app_state::AppState;
15use crate::downloads;
16use crate::downloads;
@@ -985,6 +986,9 @@ impl Render for ImageViewer {
985 .bg(rgba(BACKDROP))
986 .bg(rgba(BACKDROP))
986 .occlude()
987 .occlude()
987 .on_key_down(cx.listener(Self::on_key_down))
988 .on_key_down(cx.listener(Self::on_key_down))
989 .on_action(cx.listener(|this, _: &ZoomIn, window, cx| this.zoom_step(1, window, cx)))
990 .on_action(cx.listener(|this, _: &ZoomOut, window, cx| this.zoom_step(-1, window, cx)))
991 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| this.zoom_fit(cx)))
988 .on_scroll_wheel(cx.listener(Self::on_wheel))
992 .on_scroll_wheel(cx.listener(Self::on_wheel))
989 .on_mouse_move(cx.listener(Self::on_mouse_move))
993 .on_mouse_move(cx.listener(Self::on_mouse_move))
990 .on_mouse_up(
994 .on_mouse_up(
crates/app/src/views/mod.rs +1 −0
@@ -77,6 +77,7 @@ pub mod title_bar;
77 77 pub mod toolbar_placement;
78 78 pub mod transfer_picker;
79 79 pub mod translation_line;
80 pub mod window_zoom;
80 81
81 82 pub use app_ui_kit::{
82 83 card_chart, channel_tabs, draft_style, reaction_proposal_pill, scroll_edge, widgets,
@@ -77,6 +77,7 @@ pub mod title_bar;
77pub mod toolbar_placement;
77pub mod toolbar_placement;
78pub mod transfer_picker;
78pub mod transfer_picker;
79pub mod translation_line;
79pub mod translation_line;
80pub mod window_zoom;
80
81
81pub use app_ui_kit::{
82pub use app_ui_kit::{
82 card_chart, channel_tabs, draft_style, reaction_proposal_pill, scroll_edge, widgets,
83 card_chart, channel_tabs, draft_style, reaction_proposal_pill, scroll_edge, widgets,
crates/app/src/views/shell.rs +11 −1
@@ -22,8 +22,10 @@ use super::shortcuts::{
22 22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
23 23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 ToggleCallHand, ToggleCallShare, ZoomShareIn, ZoomShareOut, ZoomShareReset,
25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
26 ZoomShareReset,
26 27 };
28 use super::window_zoom::{WindowZoom, change_zoom};
27 29 use super::call_pop_out::zoom_listener;
28 30 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
29 31 use super::sidebar::SidebarView;
@@ -140,6 +142,7 @@ pub struct AppShell {
140 142 _agent_subscription: Option<Subscription>,
141 143 _escape_observation: Subscription,
142 144 _activation_observation: Subscription,
145 _appearance_observation: Subscription,
143 146 }
144 147
145 148 impl AppShell {
@@ -287,6 +290,9 @@ impl AppShell {
287 290 .update(cx, |state, cx| state.escape_call_fullscreen(cx));
288 291 }
289 292 });
293 let appearance_observation = cx.observe_window_appearance(window, |_, window, cx| {
294 crate::active_appearance::system_appearance_changed(window.appearance(), cx);
295 });
290 296 let activation_observation = cx.observe_window_activation(window, |this, window, cx| {
291 297 if window.is_window_active() {
292 298 this.state
@@ -330,6 +336,7 @@ impl AppShell {
330 336 _agent_subscription: agent_subscription,
331 337 _escape_observation: escape_observation,
332 338 _activation_observation: activation_observation,
339 _appearance_observation: appearance_observation,
333 340 };
334 341 shell.apply_open_target(cx);
335 342 shell
@@ -1027,6 +1034,9 @@ impl Render for AppShell {
1027 1034 this.state
1028 1035 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
1029 1036 }))
1037 .on_action(cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)))
1038 .on_action(cx.listener(|this, _: &ZoomOut, _, cx| change_zoom(&this.state, WindowZoom::Out, cx)))
1039 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| change_zoom(&this.state, WindowZoom::Reset, cx)))
1030 1040 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1031 1041 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1032 1042 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
@@ -22,8 +22,10 @@ use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 ToggleCallHand, ToggleCallShare, ZoomShareIn, ZoomShareOut, ZoomShareReset,
25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
26 ZoomShareReset,
26};
27};
28use super::window_zoom::{WindowZoom, change_zoom};
27use super::call_pop_out::zoom_listener;
29use super::call_pop_out::zoom_listener;
28use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
30use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
29use super::sidebar::SidebarView;
31use super::sidebar::SidebarView;
@@ -140,6 +142,7 @@ pub struct AppShell {
140 _agent_subscription: Option<Subscription>,
142 _agent_subscription: Option<Subscription>,
141 _escape_observation: Subscription,
143 _escape_observation: Subscription,
142 _activation_observation: Subscription,
144 _activation_observation: Subscription,
145 _appearance_observation: Subscription,
143}
146}
144
147
145impl AppShell {
148impl AppShell {
@@ -287,6 +290,9 @@ impl AppShell {
287 .update(cx, |state, cx| state.escape_call_fullscreen(cx));
290 .update(cx, |state, cx| state.escape_call_fullscreen(cx));
288 }
291 }
289 });
292 });
293 let appearance_observation = cx.observe_window_appearance(window, |_, window, cx| {
294 crate::active_appearance::system_appearance_changed(window.appearance(), cx);
295 });
290 let activation_observation = cx.observe_window_activation(window, |this, window, cx| {
296 let activation_observation = cx.observe_window_activation(window, |this, window, cx| {
291 if window.is_window_active() {
297 if window.is_window_active() {
292 this.state
298 this.state
@@ -330,6 +336,7 @@ impl AppShell {
330 _agent_subscription: agent_subscription,
336 _agent_subscription: agent_subscription,
331 _escape_observation: escape_observation,
337 _escape_observation: escape_observation,
332 _activation_observation: activation_observation,
338 _activation_observation: activation_observation,
339 _appearance_observation: appearance_observation,
333 };
340 };
334 shell.apply_open_target(cx);
341 shell.apply_open_target(cx);
335 shell
342 shell
@@ -1027,6 +1034,9 @@ impl Render for AppShell {
1027 this.state
1034 this.state
1028 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
1035 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
1029 }))
1036 }))
1037 .on_action(cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)))
1038 .on_action(cx.listener(|this, _: &ZoomOut, _, cx| change_zoom(&this.state, WindowZoom::Out, cx)))
1039 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| change_zoom(&this.state, WindowZoom::Reset, cx)))
1030 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1040 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1031 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1041 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1032 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
1042 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
crates/app/src/views/shortcuts.rs +54 −4
@@ -10,8 +10,15 @@ use super::actions::{
10 10 const TEXT_FIELD_CONTEXT: &str = "Input";
11 11 const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
12 12 const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
13 const ALTERNATE_KEYS: &[(&str, &str)] =
14 &[("alt-shift-=", "alt-shift-+"), ("ctrl-alt-=", "ctrl-alt-+")];
13 const ALTERNATE_KEYS: &[(&str, &str)] = &[
14 ("Zoom in on shared content", "alt-shift-+"),
15 ("Insert column or row", "ctrl-alt-+"),
16 ("Zoom in", "ctrl-+"),
17 ("Zoom in", "ctrl-shift-="),
18 ("Zoom in", "ctrl-shift-+"),
19 ("Zoom out", "ctrl-_"),
20 ("Zoom out", "ctrl-shift--"),
21 ];
15 22
16 23 actions!(
17 24 teams,
@@ -40,7 +47,10 @@ actions!(
40 47 ZoomShareOut,
41 48 ZoomShareReset,
42 49 ShowShortcuts,
43 OpenSettings
50 OpenSettings,
51 ZoomIn,
52 ZoomOut,
53 ZoomReset
44 54 ]
45 55 );
46 56
@@ -107,6 +117,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
107 117 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
108 118 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
109 119 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
120 shortcut!(General, OutsideComposer, "Zoom in", "ctrl-=", Some("cmd-="), ZoomIn),
121 shortcut!(General, GlobalOverTextFields, "Zoom out", "ctrl--", Some("cmd--"), ZoomOut),
122 shortcut!(General, GlobalOverTextFields, "Reset zoom level", "ctrl-0", Some("cmd-0"), ZoomReset),
110 123 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
111 124 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
112 125 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
@@ -171,7 +184,7 @@ impl Shortcut {
171 184 keys.extend(
172 185 ALTERNATE_KEYS
173 186 .iter()
174 .filter(|(primary, _)| *primary == self.keys)
187 .filter(|(label, _)| *label == self.label)
175 188 .map(|(_, alternate)| *alternate),
176 189 );
177 190 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
@@ -356,6 +369,43 @@ mod tests {
356 369 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
357 370 }
358 371
372 #[gpui_kit::test]
373 fn zoom_keys_match_teams_and_leave_the_composer_subscript_alone(cx: &mut TestAppContext) {
374 registered(cx);
375 let action_of = |label: &str| {
376 action_name(
377 SHORTCUTS
378 .iter()
379 .find(|shortcut| shortcut.label == label)
380 .unwrap(),
381 )
382 };
383 for (keys, label) in [
384 ("ctrl-=", "Zoom in"),
385 ("ctrl-+", "Zoom in"),
386 ("ctrl-shift-=", "Zoom in"),
387 ("ctrl--", "Zoom out"),
388 ("ctrl-_", "Zoom out"),
389 ("ctrl-0", "Reset zoom level"),
390 ] {
391 assert_eq!(
392 bound_action(cx, keys, &["AppShell"]),
393 Some(action_of(label)),
394 "{keys}"
395 );
396 }
397 let typing = ["AppShell", "Composer", "Input"];
398 assert_eq!(
399 bound_action(cx, "ctrl-=", &typing),
400 Some(action_of("Subscript"))
401 );
402 assert_eq!(
403 bound_action(cx, "ctrl--", &typing),
404 Some(action_of("Zoom out"))
405 );
406 assert_eq!(display_keys("ctrl-="), "Ctrl+Plus");
407 }
408
359 409 #[gpui_kit::test]
360 410 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
361 411 registered(cx);
@@ -10,8 +10,15 @@ use super::actions::{
10const TEXT_FIELD_CONTEXT: &str = "Input";
10const TEXT_FIELD_CONTEXT: &str = "Input";
11const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
11const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
12const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
12const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
13const ALTERNATE_KEYS: &[(&str, &str)] =
13const ALTERNATE_KEYS: &[(&str, &str)] = &[
14 &[("alt-shift-=", "alt-shift-+"), ("ctrl-alt-=", "ctrl-alt-+")];
14 ("Zoom in on shared content", "alt-shift-+"),
15 ("Insert column or row", "ctrl-alt-+"),
16 ("Zoom in", "ctrl-+"),
17 ("Zoom in", "ctrl-shift-="),
18 ("Zoom in", "ctrl-shift-+"),
19 ("Zoom out", "ctrl-_"),
20 ("Zoom out", "ctrl-shift--"),
21];
15
22
16actions!(
23actions!(
17 teams,
24 teams,
@@ -40,7 +47,10 @@ actions!(
40 ZoomShareOut,
47 ZoomShareOut,
41 ZoomShareReset,
48 ZoomShareReset,
42 ShowShortcuts,
49 ShowShortcuts,
43 OpenSettings
50 OpenSettings,
51 ZoomIn,
52 ZoomOut,
53 ZoomReset
44 ]
54 ]
45);
55);
46
56
@@ -107,6 +117,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
107 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
117 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
108 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
118 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
109 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
119 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
120 shortcut!(General, OutsideComposer, "Zoom in", "ctrl-=", Some("cmd-="), ZoomIn),
121 shortcut!(General, GlobalOverTextFields, "Zoom out", "ctrl--", Some("cmd--"), ZoomOut),
122 shortcut!(General, GlobalOverTextFields, "Reset zoom level", "ctrl-0", Some("cmd-0"), ZoomReset),
110 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
123 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
111 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
124 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
112 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
125 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
@@ -171,7 +184,7 @@ impl Shortcut {
171 keys.extend(
184 keys.extend(
172 ALTERNATE_KEYS
185 ALTERNATE_KEYS
173 .iter()
186 .iter()
174 .filter(|(primary, _)| *primary == self.keys)
187 .filter(|(label, _)| *label == self.label)
175 .map(|(_, alternate)| *alternate),
188 .map(|(_, alternate)| *alternate),
176 );
189 );
177 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
190 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
@@ -356,6 +369,43 @@ mod tests {
356 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
369 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
357 }
370 }
358
371
372 #[gpui_kit::test]
373 fn zoom_keys_match_teams_and_leave_the_composer_subscript_alone(cx: &mut TestAppContext) {
374 registered(cx);
375 let action_of = |label: &str| {
376 action_name(
377 SHORTCUTS
378 .iter()
379 .find(|shortcut| shortcut.label == label)
380 .unwrap(),
381 )
382 };
383 for (keys, label) in [
384 ("ctrl-=", "Zoom in"),
385 ("ctrl-+", "Zoom in"),
386 ("ctrl-shift-=", "Zoom in"),
387 ("ctrl--", "Zoom out"),
388 ("ctrl-_", "Zoom out"),
389 ("ctrl-0", "Reset zoom level"),
390 ] {
391 assert_eq!(
392 bound_action(cx, keys, &["AppShell"]),
393 Some(action_of(label)),
394 "{keys}"
395 );
396 }
397 let typing = ["AppShell", "Composer", "Input"];
398 assert_eq!(
399 bound_action(cx, "ctrl-=", &typing),
400 Some(action_of("Subscript"))
401 );
402 assert_eq!(
403 bound_action(cx, "ctrl--", &typing),
404 Some(action_of("Zoom out"))
405 );
406 assert_eq!(display_keys("ctrl-="), "Ctrl+Plus");
407 }
408
359 #[gpui_kit::test]
409 #[gpui_kit::test]
360 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
410 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
361 registered(cx);
411 registered(cx);
crates/app/src/views/status_menu.rs +5 −1
@@ -197,6 +197,7 @@ fn status_menu(
197 197 let translation_app = context.app.clone();
198 198 let general_app = context.app.clone();
199 199 let call_app = context.app.clone();
200 let zoom_app = context.app.clone();
200 201 let row_label = match &context.summary.until {
201 202 Some(until) => format!("{} {until}", context.summary.label),
202 203 None => context.summary.label.to_owned(),
@@ -265,7 +266,10 @@ fn status_menu(
265 266 general_app
266 267 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
267 268 }),
268 );
269 )
270 .item(PopupMenuItem::element(move |_, cx| {
271 super::window_zoom::menu_row(&zoom_app, cx)
272 }));
269 273 if !demo {
270 274 return popup;
271 275 }
@@ -197,6 +197,7 @@ fn status_menu(
197 let translation_app = context.app.clone();
197 let translation_app = context.app.clone();
198 let general_app = context.app.clone();
198 let general_app = context.app.clone();
199 let call_app = context.app.clone();
199 let call_app = context.app.clone();
200 let zoom_app = context.app.clone();
200 let row_label = match &context.summary.until {
201 let row_label = match &context.summary.until {
201 Some(until) => format!("{} {until}", context.summary.label),
202 Some(until) => format!("{} {until}", context.summary.label),
202 None => context.summary.label.to_owned(),
203 None => context.summary.label.to_owned(),
@@ -265,7 +266,10 @@ fn status_menu(
265 general_app
266 general_app
266 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
267 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
267 }),
268 }),
268 );
269 )
270 .item(PopupMenuItem::element(move |_, cx| {
271 super::window_zoom::menu_row(&zoom_app, cx)
272 }));
269 if !demo {
273 if !demo {
270 return popup;
274 return popup;
271 }
275 }
crates/app/src/views/window_zoom.rs added +182 −0
@@ -0,0 +1,182 @@
1 use gpui_kit::component::{h_flex, tooltip::Tooltip};
2 use gpui_kit::prelude::FluentBuilder as _;
3 use gpui_kit::*;
4
5 use super::widgets::symbol;
6 use crate::active_appearance;
7 use crate::app_state::AppState;
8 use crate::appearance::{self, DEFAULT_ZOOM};
9 use crate::theme;
10
11 const ZOOM_LABEL: &str = "Zoom";
12 const ZOOM_IN_LABEL: &str = "Zoom in";
13 const ZOOM_OUT_LABEL: &str = "Zoom out";
14 const ZOOM_RESET_LABEL: &str = "Reset zoom";
15 const DEFAULT_PERCENT: u32 = 100;
16 const MINIMUM_TOAST_PERCENT: u32 = 60;
17 const MAXIMUM_TOAST_PERCENT: u32 = 400;
18 const MENU_ROUNDING: u32 = 5;
19 const BUTTON_SIZE: f32 = 28.;
20 const BUTTON_ICON: f32 = 18.;
21 const BUTTON_RADIUS: f32 = 6.;
22 const DISABLED_OPACITY: f32 = 0.4;
23
24 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25 pub enum WindowZoom {
26 In,
27 Out,
28 Reset,
29 }
30
31 impl WindowZoom {
32 fn next(self, zoom: f32) -> f32 {
33 match self {
34 WindowZoom::In => appearance::zoom_in(zoom),
35 WindowZoom::Out => appearance::zoom_out(zoom),
36 WindowZoom::Reset => DEFAULT_ZOOM,
37 }
38 }
39 }
40
41 pub fn toast_text(previous_percent: u32, percent: u32) -> String {
42 let state = if percent == DEFAULT_PERCENT {
43 "Default size"
44 } else if percent <= MINIMUM_TOAST_PERCENT {
45 "Minimum zoom"
46 } else if percent >= MAXIMUM_TOAST_PERCENT {
47 "Maximum zoom"
48 } else if percent > previous_percent {
49 "Zoomed in"
50 } else {
51 "Zoomed out"
52 };
53 format!("{percent}% \u{b7} {state}")
54 }
55
56 pub fn menu_level(zoom: f32) -> String {
57 let percent = appearance::zoom_percent(zoom);
58 let rounded = (percent + MENU_ROUNDING / 2) / MENU_ROUNDING * MENU_ROUNDING;
59 format!("({rounded})%")
60 }
61
62 pub fn change_zoom(app: &Entity<AppState>, change: WindowZoom, cx: &mut App) {
63 let previous = active_appearance::current(cx).zoom;
64 let next = change.next(previous);
65 let store = app.read(cx).store.clone();
66 if !active_appearance::set_zoom(next, &store, cx) {
67 return;
68 }
69 let text = toast_text(
70 appearance::zoom_percent(previous),
71 appearance::zoom_percent(next),
72 );
73 app.update(cx, |state, cx| state.raise_notice(text, None, cx));
74 }
75
76 fn zoom_button(
77 app: &Entity<AppState>,
78 id: &'static str,
79 glyph: &'static str,
80 label: &'static str,
81 change: WindowZoom,
82 enabled: bool,
83 ) -> Stateful<Div> {
84 let app = app.clone();
85 div()
86 .id(id)
87 .size(px(BUTTON_SIZE))
88 .flex_none()
89 .flex()
90 .items_center()
91 .justify_center()
92 .rounded(px(BUTTON_RADIUS))
93 .child(symbol(glyph, BUTTON_ICON, theme::text()))
94 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
95 .when(!enabled, |button| button.opacity(DISABLED_OPACITY))
96 .when(enabled, |button| {
97 button
98 .cursor_pointer()
99 .hover(|button| button.bg(theme::popup_hover()))
100 })
101 .on_click(move |_, _, cx| {
102 cx.stop_propagation();
103 if enabled {
104 change_zoom(&app, change, cx);
105 }
106 })
107 }
108
109 pub fn menu_row(app: &Entity<AppState>, cx: &App) -> Div {
110 let zoom = active_appearance::current(cx).zoom;
111 let zoomed = appearance::zoom_percent(zoom) != DEFAULT_PERCENT;
112 h_flex()
113 .w_full()
114 .gap(px(8.))
115 .items_center()
116 .justify_between()
117 .child(div().text_color(theme::text()).child(ZOOM_LABEL))
118 .child(
119 h_flex()
120 .flex_none()
121 .gap(px(2.))
122 .items_center()
123 .child(zoom_button(
124 app,
125 "window-zoom-out",
126 "zoom_out",
127 ZOOM_OUT_LABEL,
128 WindowZoom::Out,
129 true,
130 ))
131 .child(
132 div()
133 .debug_selector(|| "window-zoom-level".into())
134 .text_color(theme::text_muted())
135 .child(menu_level(zoom)),
136 )
137 .child(zoom_button(
138 app,
139 "window-zoom-in",
140 "zoom_in",
141 ZOOM_IN_LABEL,
142 WindowZoom::In,
143 true,
144 ))
145 .child(zoom_button(
146 app,
147 "window-zoom-reset",
148 "refresh",
149 ZOOM_RESET_LABEL,
150 WindowZoom::Reset,
151 zoomed,
152 )),
153 )
154 }
155
156 #[cfg(test)]
157 mod tests {
158 use super::{WindowZoom, menu_level, toast_text};
159
160 #[test]
161 fn toast_texts_follow_the_teams_zoom_toast() {
162 assert_eq!(toast_text(100, 110), "110% \u{b7} Zoomed in");
163 assert_eq!(toast_text(110, 100), "100% \u{b7} Default size");
164 assert_eq!(toast_text(90, 80), "80% \u{b7} Zoomed out");
165 assert_eq!(toast_text(67, 50), "50% \u{b7} Minimum zoom");
166 assert_eq!(toast_text(300, 400), "400% \u{b7} Maximum zoom");
167 }
168
169 #[test]
170 fn the_menu_rounds_the_level_to_five_like_teams() {
171 assert_eq!(menu_level(1.), "(100)%");
172 assert_eq!(menu_level(0.67), "(65)%");
173 assert_eq!(menu_level(1.75), "(175)%");
174 }
175
176 #[test]
177 fn reset_always_returns_to_the_default_size() {
178 assert_eq!(WindowZoom::Reset.next(2.5), 1.);
179 assert_eq!(WindowZoom::In.next(1.), 1.1);
180 assert_eq!(WindowZoom::Out.next(1.), 0.9);
181 }
182 }
@@ -0,0 +1,182 @@
1use gpui_kit::component::{h_flex, tooltip::Tooltip};
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
4
5use super::widgets::symbol;
6use crate::active_appearance;
7use crate::app_state::AppState;
8use crate::appearance::{self, DEFAULT_ZOOM};
9use crate::theme;
10
11const ZOOM_LABEL: &str = "Zoom";
12const ZOOM_IN_LABEL: &str = "Zoom in";
13const ZOOM_OUT_LABEL: &str = "Zoom out";
14const ZOOM_RESET_LABEL: &str = "Reset zoom";
15const DEFAULT_PERCENT: u32 = 100;
16const MINIMUM_TOAST_PERCENT: u32 = 60;
17const MAXIMUM_TOAST_PERCENT: u32 = 400;
18const MENU_ROUNDING: u32 = 5;
19const BUTTON_SIZE: f32 = 28.;
20const BUTTON_ICON: f32 = 18.;
21const BUTTON_RADIUS: f32 = 6.;
22const DISABLED_OPACITY: f32 = 0.4;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum WindowZoom {
26 In,
27 Out,
28 Reset,
29}
30
31impl WindowZoom {
32 fn next(self, zoom: f32) -> f32 {
33 match self {
34 WindowZoom::In => appearance::zoom_in(zoom),
35 WindowZoom::Out => appearance::zoom_out(zoom),
36 WindowZoom::Reset => DEFAULT_ZOOM,
37 }
38 }
39}
40
41pub fn toast_text(previous_percent: u32, percent: u32) -> String {
42 let state = if percent == DEFAULT_PERCENT {
43 "Default size"
44 } else if percent <= MINIMUM_TOAST_PERCENT {
45 "Minimum zoom"
46 } else if percent >= MAXIMUM_TOAST_PERCENT {
47 "Maximum zoom"
48 } else if percent > previous_percent {
49 "Zoomed in"
50 } else {
51 "Zoomed out"
52 };
53 format!("{percent}% \u{b7} {state}")
54}
55
56pub fn menu_level(zoom: f32) -> String {
57 let percent = appearance::zoom_percent(zoom);
58 let rounded = (percent + MENU_ROUNDING / 2) / MENU_ROUNDING * MENU_ROUNDING;
59 format!("({rounded})%")
60}
61
62pub fn change_zoom(app: &Entity<AppState>, change: WindowZoom, cx: &mut App) {
63 let previous = active_appearance::current(cx).zoom;
64 let next = change.next(previous);
65 let store = app.read(cx).store.clone();
66 if !active_appearance::set_zoom(next, &store, cx) {
67 return;
68 }
69 let text = toast_text(
70 appearance::zoom_percent(previous),
71 appearance::zoom_percent(next),
72 );
73 app.update(cx, |state, cx| state.raise_notice(text, None, cx));
74}
75
76fn zoom_button(
77 app: &Entity<AppState>,
78 id: &'static str,
79 glyph: &'static str,
80 label: &'static str,
81 change: WindowZoom,
82 enabled: bool,
83) -> Stateful<Div> {
84 let app = app.clone();
85 div()
86 .id(id)
87 .size(px(BUTTON_SIZE))
88 .flex_none()
89 .flex()
90 .items_center()
91 .justify_center()
92 .rounded(px(BUTTON_RADIUS))
93 .child(symbol(glyph, BUTTON_ICON, theme::text()))
94 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
95 .when(!enabled, |button| button.opacity(DISABLED_OPACITY))
96 .when(enabled, |button| {
97 button
98 .cursor_pointer()
99 .hover(|button| button.bg(theme::popup_hover()))
100 })
101 .on_click(move |_, _, cx| {
102 cx.stop_propagation();
103 if enabled {
104 change_zoom(&app, change, cx);
105 }
106 })
107}
108
109pub fn menu_row(app: &Entity<AppState>, cx: &App) -> Div {
110 let zoom = active_appearance::current(cx).zoom;
111 let zoomed = appearance::zoom_percent(zoom) != DEFAULT_PERCENT;
112 h_flex()
113 .w_full()
114 .gap(px(8.))
115 .items_center()
116 .justify_between()
117 .child(div().text_color(theme::text()).child(ZOOM_LABEL))
118 .child(
119 h_flex()
120 .flex_none()
121 .gap(px(2.))
122 .items_center()
123 .child(zoom_button(
124 app,
125 "window-zoom-out",
126 "zoom_out",
127 ZOOM_OUT_LABEL,
128 WindowZoom::Out,
129 true,
130 ))
131 .child(
132 div()
133 .debug_selector(|| "window-zoom-level".into())
134 .text_color(theme::text_muted())
135 .child(menu_level(zoom)),
136 )
137 .child(zoom_button(
138 app,
139 "window-zoom-in",
140 "zoom_in",
141 ZOOM_IN_LABEL,
142 WindowZoom::In,
143 true,
144 ))
145 .child(zoom_button(
146 app,
147 "window-zoom-reset",
148 "refresh",
149 ZOOM_RESET_LABEL,
150 WindowZoom::Reset,
151 zoomed,
152 )),
153 )
154}
155
156#[cfg(test)]
157mod tests {
158 use super::{WindowZoom, menu_level, toast_text};
159
160 #[test]
161 fn toast_texts_follow_the_teams_zoom_toast() {
162 assert_eq!(toast_text(100, 110), "110% \u{b7} Zoomed in");
163 assert_eq!(toast_text(110, 100), "100% \u{b7} Default size");
164 assert_eq!(toast_text(90, 80), "80% \u{b7} Zoomed out");
165 assert_eq!(toast_text(67, 50), "50% \u{b7} Minimum zoom");
166 assert_eq!(toast_text(300, 400), "400% \u{b7} Maximum zoom");
167 }
168
169 #[test]
170 fn the_menu_rounds_the_level_to_five_like_teams() {
171 assert_eq!(menu_level(1.), "(100)%");
172 assert_eq!(menu_level(0.67), "(65)%");
173 assert_eq!(menu_level(1.75), "(175)%");
174 }
175
176 #[test]
177 fn reset_always_returns_to_the_default_size() {
178 assert_eq!(WindowZoom::Reset.next(2.5), 1.);
179 assert_eq!(WindowZoom::In.next(1.), 1.1);
180 assert_eq!(WindowZoom::Out.next(1.), 0.9);
181 }
182}