BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/channels-parity

# Conflicts:
#	crates/app/src/views/conversation.rs

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
d2d8b71e73ce276c28c007167ab910893def8937
74 files changed +5474 −619
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",
GUARDRAILS.md +1 −0
@@ -24,6 +24,7 @@ Rules for every change, by people and by agents. If a rule here and a habit else
24 24 | Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
25 25 | Performance | Faster, less memory, offline reading from the cache. |
26 26 | Platform | OS-native toasts, tray, title bar and sounds. |
27 | Call windows | Daniel-approved (2026-10-17): a call stays in the main window with the sidebar, Teams opens its own meeting window. A window share leaves the main window as it is (side by side), Teams minimizes it. Only our own window behaviour, nothing others see changes. |
27 28 | Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28 29 | Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29 30
@@ -24,6 +24,7 @@ Rules for every change, by people and by agents. If a rule here and a habit else
24| Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
24| Local bugs | Fix Teams bugs that are purely local (rendering, scroll, focus). Anything touching server data or other people stays as Teams does it. |
25| Performance | Faster, less memory, offline reading from the cache. |
25| Performance | Faster, less memory, offline reading from the cache. |
26| Platform | OS-native toasts, tray, title bar and sounds. |
26| Platform | OS-native toasts, tray, title bar and sounds. |
27| Call windows | Daniel-approved (2026-10-17): a call stays in the main window with the sidebar, Teams opens its own meeting window. A window share leaves the main window as it is (side by side), Teams minimizes it. Only our own window behaviour, nothing others see changes. |
27| Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28| Own features | MCP, agents, session inbox: allowed when nobody else can tell. Nothing sent automatically, no own message formats. |
28| Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29| Own settings | Settings Teams does not know stay in the local DB, never in Teams account properties. |
29
30
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/avatar_image.rs +145 −47
@@ -1,45 +1,107 @@
1 1 use std::io::Cursor;
2 use std::sync::{Arc, Mutex};
2 3
4 use gpui_kit::RenderImage;
3 5 use image::imageops::FilterType;
4 use image::{ImageFormat, Rgba, RgbaImage};
6 use image::{Frame, ImageFormat, ImageReader, RgbaImage};
5 7
6 const TEXTURE_SIZE: u32 = 100;
7 const MARGIN: f32 = 2.;
8 const MAX_TEXTURES: usize = 8;
9 const SOURCE_SIDE: u32 = 240;
10 const SOURCE_LIMIT: u32 = 2 * SOURCE_SIDE;
8 11
9 pub fn circular_png(bytes: &[u8]) -> Option<Vec<u8>> {
10 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
11 let side = decoded.width().min(decoded.height());
12 let left = (decoded.width() - side) / 2;
13 let top = (decoded.height() - side) / 2;
14 let square = image::imageops::crop_imm(&decoded, left, top, side, side).to_image();
15 let mut resized =
16 image::imageops::resize(&square, TEXTURE_SIZE, TEXTURE_SIZE, FilterType::Lanczos3);
17 apply_circle_mask(&mut resized);
12 pub struct AvatarPhoto {
13 bytes: Vec<u8>,
14 textures: Mutex<Vec<(u32, Arc<RenderImage>)>>,
15 }
16
17 pub struct Texture {
18 pub image: Arc<RenderImage>,
19 pub evicted: Option<Arc<RenderImage>>,
20 }
21
22 impl AvatarPhoto {
23 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
24 let (width, height) = ImageReader::new(Cursor::new(&bytes))
25 .with_guessed_format()
26 .ok()?
27 .into_dimensions()
28 .ok()?;
29 if width == 0 || height == 0 {
30 return None;
31 }
32 let bytes = if width.max(height) > SOURCE_LIMIT {
33 shrunk_source(&bytes)?
34 } else {
35 bytes
36 };
37 Some(Self {
38 bytes,
39 textures: Mutex::new(Vec::new()),
40 })
41 }
42
43 pub fn texture(&self, side: u32) -> Option<Texture> {
44 let mut textures = self.textures.lock().ok()?;
45 if let Some(position) = textures.iter().position(|(cached, _)| *cached == side) {
46 let entry = textures.remove(position);
47 let image = entry.1.clone();
48 textures.push(entry);
49 return Some(Texture {
50 image,
51 evicted: None,
52 });
53 }
54 let pixels = square_texture(&self.bytes, side)?;
55 let image = Arc::new(RenderImage::new(vec![Frame::new(pixels)]));
56 let evicted = (textures.len() >= MAX_TEXTURES).then(|| textures.remove(0).1);
57 textures.push((side, image.clone()));
58 Some(Texture { image, evicted })
59 }
60 }
61
62 fn shrunk_source(bytes: &[u8]) -> Option<Vec<u8>> {
63 let mut source = square_texture(bytes, SOURCE_SIDE)?;
64 for pixel in source.pixels_mut() {
65 pixel.0.swap(0, 2);
66 }
18 67 let mut encoded = Vec::new();
19 resized
68 source
20 69 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
21 70 .ok()?;
22 71 Some(encoded)
23 72 }
24 73
25 fn apply_circle_mask(texture: &mut RgbaImage) {
26 let center = TEXTURE_SIZE as f32 / 2.;
27 let radius = center - MARGIN;
28 for (x, y, pixel) in texture.enumerate_pixels_mut() {
29 let distance =
30 ((x as f32 + 0.5 - center).powi(2) + (y as f32 + 0.5 - center).powi(2)).sqrt();
31 let coverage = (radius + 0.5 - distance).clamp(0., 1.);
32 let Rgba([red, green, blue, alpha]) = *pixel;
33 *pixel = Rgba([red, green, blue, (alpha as f32 * coverage).round() as u8]);
34 }
74 pub fn device_span(start: f32, end: f32, scale_factor: f32) -> u32 {
75 let snapped =
76 round_half_toward_zero(end * scale_factor) - round_half_toward_zero(start * scale_factor);
77 snapped.max(1.) as u32
78 }
79
80 fn round_half_toward_zero(value: f32) -> f32 {
81 value.signum() * (value.abs() - 0.5).ceil()
35 82 }
36 83
37 pub fn visible_fraction() -> f32 {
38 (TEXTURE_SIZE as f32 - 2. * MARGIN) / TEXTURE_SIZE as f32
84 pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {
85 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
86 let crop = decoded.width().min(decoded.height());
87 let left = (decoded.width() - crop) / 2;
88 let top = (decoded.height() - crop) / 2;
89 let square = image::imageops::crop_imm(&decoded, left, top, crop, crop).to_image();
90 let mut texture = if crop == side {
91 square
92 } else {
93 image::imageops::resize(&square, side, side, FilterType::Lanczos3)
94 };
95 for pixel in texture.pixels_mut() {
96 pixel.0.swap(0, 2);
97 }
98 Some(texture)
39 99 }
40 100
41 101 #[cfg(test)]
42 102 mod tests {
103 use image::Rgba;
104
43 105 use super::*;
44 106
45 107 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
@@ -53,35 +115,71 @@ mod tests {
53 115 }
54 116
55 117 #[test]
56 fn texture_edges_are_transparent_and_center_is_opaque() {
57 let masked = image::load_from_memory(&circular_png(&solid_jpeg(48, 48)).unwrap())
58 .unwrap()
59 .to_rgba8();
60 assert_eq!(masked.dimensions(), (TEXTURE_SIZE, TEXTURE_SIZE));
61 let middle = TEXTURE_SIZE / 2;
62 for (x, y) in [
63 (middle, 0),
64 (middle, TEXTURE_SIZE - 1),
65 (0, middle),
66 (TEXTURE_SIZE - 1, middle),
67 (0, 0),
68 ] {
69 assert_eq!(
70 masked.get_pixel(x, y)[3],
71 0,
72 "edge pixel {x},{y} must be transparent"
73 );
74 }
75 assert_eq!(masked.get_pixel(middle, middle)[3], 255);
118 fn texture_matches_the_device_pixels_and_is_bgra() {
119 let texture = square_texture(&solid_jpeg(240, 240), 39).unwrap();
120 assert_eq!(texture.dimensions(), (39, 39));
121 let Rgba([blue, _, red, alpha]) = *texture.get_pixel(19, 19);
122 assert!(
123 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
124 "{blue} {red}"
125 );
126 assert_eq!(alpha, 255);
76 127 }
77 128
78 129 #[test]
79 130 fn non_square_photos_are_center_cropped() {
80 assert!(circular_png(&solid_jpeg(64, 40)).is_some());
131 assert_eq!(
132 square_texture(&solid_jpeg(64, 40), 60)
133 .unwrap()
134 .dimensions(),
135 (60, 60)
136 );
137 }
138
139 #[test]
140 fn device_span_follows_the_snapped_bounds() {
141 assert_eq!(device_span(0., 26., 1.), 26);
142 assert_eq!(device_span(0., 28., 1.5), 42);
143 assert_eq!(device_span(10.5, 36.5, 1.5), 39);
144 assert_eq!(device_span(10.1, 36.1, 1.5), 39);
145 assert_eq!(device_span(0., 32., 1.25), 40);
146 assert_eq!(device_span(0., 0.1, 1.), 1);
147 assert_eq!(device_span(-3.5, 22.5, 1.), 25);
148 }
149
150 #[test]
151 fn textures_are_cached_per_side_and_evict_the_oldest() {
152 let photo = AvatarPhoto::from_bytes(solid_jpeg(48, 48)).unwrap();
153 let first = photo.texture(32).unwrap();
154 let again = photo.texture(32).unwrap();
155 assert_eq!(first.image.id, again.image.id);
156 assert!(again.evicted.is_none());
157 for side in 33..33 + MAX_TEXTURES as u32 - 1 {
158 assert!(photo.texture(side).unwrap().evicted.is_none());
159 }
160 let overflow = photo.texture(100).unwrap();
161 assert_eq!(overflow.evicted.map(|image| image.id), Some(first.image.id));
162 }
163
164 #[test]
165 fn large_originals_are_kept_at_the_source_side() {
166 let photo = AvatarPhoto::from_bytes(solid_jpeg(1200, 900)).unwrap();
167 let dimensions = image::load_from_memory(&photo.bytes)
168 .unwrap()
169 .to_rgba8()
170 .dimensions();
171 assert_eq!(dimensions, (SOURCE_SIDE, SOURCE_SIDE));
172 let texture = photo.texture(20).unwrap().image;
173 let raw = texture.as_bytes(0).unwrap().to_vec();
174 let Rgba([blue, _, red, _]) = *RgbaImage::from_raw(20, 20, raw).unwrap().get_pixel(10, 10);
175 assert!(
176 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
177 "{blue} {red}"
178 );
81 179 }
82 180
83 181 #[test]
84 182 fn garbage_bytes_fall_back() {
85 assert!(circular_png(b"not an image").is_none());
183 assert!(AvatarPhoto::from_bytes(b"not an image".to_vec()).is_none());
86 184 }
87 185 }
@@ -1,45 +1,107 @@
1use std::io::Cursor;
1use std::io::Cursor;
2use std::sync::{Arc, Mutex};
2
3
4use gpui_kit::RenderImage;
3use image::imageops::FilterType;
5use image::imageops::FilterType;
4use image::{ImageFormat, Rgba, RgbaImage};
6use image::{Frame, ImageFormat, ImageReader, RgbaImage};
5
7
6const TEXTURE_SIZE: u32 = 100;
8const MAX_TEXTURES: usize = 8;
7const MARGIN: f32 = 2.;
9const SOURCE_SIDE: u32 = 240;
10const SOURCE_LIMIT: u32 = 2 * SOURCE_SIDE;
8
11
9pub fn circular_png(bytes: &[u8]) -> Option<Vec<u8>> {
12pub struct AvatarPhoto {
10 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
13 bytes: Vec<u8>,
11 let side = decoded.width().min(decoded.height());
14 textures: Mutex<Vec<(u32, Arc<RenderImage>)>>,
12 let left = (decoded.width() - side) / 2;
15}
13 let top = (decoded.height() - side) / 2;
16
14 let square = image::imageops::crop_imm(&decoded, left, top, side, side).to_image();
17pub struct Texture {
15 let mut resized =
18 pub image: Arc<RenderImage>,
16 image::imageops::resize(&square, TEXTURE_SIZE, TEXTURE_SIZE, FilterType::Lanczos3);
19 pub evicted: Option<Arc<RenderImage>>,
17 apply_circle_mask(&mut resized);
20}
21
22impl AvatarPhoto {
23 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
24 let (width, height) = ImageReader::new(Cursor::new(&bytes))
25 .with_guessed_format()
26 .ok()?
27 .into_dimensions()
28 .ok()?;
29 if width == 0 || height == 0 {
30 return None;
31 }
32 let bytes = if width.max(height) > SOURCE_LIMIT {
33 shrunk_source(&bytes)?
34 } else {
35 bytes
36 };
37 Some(Self {
38 bytes,
39 textures: Mutex::new(Vec::new()),
40 })
41 }
42
43 pub fn texture(&self, side: u32) -> Option<Texture> {
44 let mut textures = self.textures.lock().ok()?;
45 if let Some(position) = textures.iter().position(|(cached, _)| *cached == side) {
46 let entry = textures.remove(position);
47 let image = entry.1.clone();
48 textures.push(entry);
49 return Some(Texture {
50 image,
51 evicted: None,
52 });
53 }
54 let pixels = square_texture(&self.bytes, side)?;
55 let image = Arc::new(RenderImage::new(vec![Frame::new(pixels)]));
56 let evicted = (textures.len() >= MAX_TEXTURES).then(|| textures.remove(0).1);
57 textures.push((side, image.clone()));
58 Some(Texture { image, evicted })
59 }
60}
61
62fn shrunk_source(bytes: &[u8]) -> Option<Vec<u8>> {
63 let mut source = square_texture(bytes, SOURCE_SIDE)?;
64 for pixel in source.pixels_mut() {
65 pixel.0.swap(0, 2);
66 }
18 let mut encoded = Vec::new();
67 let mut encoded = Vec::new();
19 resized
68 source
20 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
69 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
21 .ok()?;
70 .ok()?;
22 Some(encoded)
71 Some(encoded)
23}
72}
24
73
25fn apply_circle_mask(texture: &mut RgbaImage) {
74pub fn device_span(start: f32, end: f32, scale_factor: f32) -> u32 {
26 let center = TEXTURE_SIZE as f32 / 2.;
75 let snapped =
27 let radius = center - MARGIN;
76 round_half_toward_zero(end * scale_factor) - round_half_toward_zero(start * scale_factor);
28 for (x, y, pixel) in texture.enumerate_pixels_mut() {
77 snapped.max(1.) as u32
29 let distance =
78}
30 ((x as f32 + 0.5 - center).powi(2) + (y as f32 + 0.5 - center).powi(2)).sqrt();
79
31 let coverage = (radius + 0.5 - distance).clamp(0., 1.);
80fn round_half_toward_zero(value: f32) -> f32 {
32 let Rgba([red, green, blue, alpha]) = *pixel;
81 value.signum() * (value.abs() - 0.5).ceil()
33 *pixel = Rgba([red, green, blue, (alpha as f32 * coverage).round() as u8]);
34 }
35}
82}
36
83
37pub fn visible_fraction() -> f32 {
84pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {
38 (TEXTURE_SIZE as f32 - 2. * MARGIN) / TEXTURE_SIZE as f32
85 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
86 let crop = decoded.width().min(decoded.height());
87 let left = (decoded.width() - crop) / 2;
88 let top = (decoded.height() - crop) / 2;
89 let square = image::imageops::crop_imm(&decoded, left, top, crop, crop).to_image();
90 let mut texture = if crop == side {
91 square
92 } else {
93 image::imageops::resize(&square, side, side, FilterType::Lanczos3)
94 };
95 for pixel in texture.pixels_mut() {
96 pixel.0.swap(0, 2);
97 }
98 Some(texture)
39}
99}
40
100
41#[cfg(test)]
101#[cfg(test)]
42mod tests {
102mod tests {
103 use image::Rgba;
104
43 use super::*;
105 use super::*;
44
106
45 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
107 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
@@ -53,35 +115,71 @@ mod tests {
53 }
115 }
54
116
55 #[test]
117 #[test]
56 fn texture_edges_are_transparent_and_center_is_opaque() {
118 fn texture_matches_the_device_pixels_and_is_bgra() {
57 let masked = image::load_from_memory(&circular_png(&solid_jpeg(48, 48)).unwrap())
119 let texture = square_texture(&solid_jpeg(240, 240), 39).unwrap();
58 .unwrap()
120 assert_eq!(texture.dimensions(), (39, 39));
59 .to_rgba8();
121 let Rgba([blue, _, red, alpha]) = *texture.get_pixel(19, 19);
60 assert_eq!(masked.dimensions(), (TEXTURE_SIZE, TEXTURE_SIZE));
122 assert!(
61 let middle = TEXTURE_SIZE / 2;
123 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
62 for (x, y) in [
124 "{blue} {red}"
63 (middle, 0),
125 );
64 (middle, TEXTURE_SIZE - 1),
126 assert_eq!(alpha, 255);
65 (0, middle),
66 (TEXTURE_SIZE - 1, middle),
67 (0, 0),
68 ] {
69 assert_eq!(
70 masked.get_pixel(x, y)[3],
71 0,
72 "edge pixel {x},{y} must be transparent"
73 );
74 }
75 assert_eq!(masked.get_pixel(middle, middle)[3], 255);
76 }
127 }
77
128
78 #[test]
129 #[test]
79 fn non_square_photos_are_center_cropped() {
130 fn non_square_photos_are_center_cropped() {
80 assert!(circular_png(&solid_jpeg(64, 40)).is_some());
131 assert_eq!(
132 square_texture(&solid_jpeg(64, 40), 60)
133 .unwrap()
134 .dimensions(),
135 (60, 60)
136 );
137 }
138
139 #[test]
140 fn device_span_follows_the_snapped_bounds() {
141 assert_eq!(device_span(0., 26., 1.), 26);
142 assert_eq!(device_span(0., 28., 1.5), 42);
143 assert_eq!(device_span(10.5, 36.5, 1.5), 39);
144 assert_eq!(device_span(10.1, 36.1, 1.5), 39);
145 assert_eq!(device_span(0., 32., 1.25), 40);
146 assert_eq!(device_span(0., 0.1, 1.), 1);
147 assert_eq!(device_span(-3.5, 22.5, 1.), 25);
148 }
149
150 #[test]
151 fn textures_are_cached_per_side_and_evict_the_oldest() {
152 let photo = AvatarPhoto::from_bytes(solid_jpeg(48, 48)).unwrap();
153 let first = photo.texture(32).unwrap();
154 let again = photo.texture(32).unwrap();
155 assert_eq!(first.image.id, again.image.id);
156 assert!(again.evicted.is_none());
157 for side in 33..33 + MAX_TEXTURES as u32 - 1 {
158 assert!(photo.texture(side).unwrap().evicted.is_none());
159 }
160 let overflow = photo.texture(100).unwrap();
161 assert_eq!(overflow.evicted.map(|image| image.id), Some(first.image.id));
162 }
163
164 #[test]
165 fn large_originals_are_kept_at_the_source_side() {
166 let photo = AvatarPhoto::from_bytes(solid_jpeg(1200, 900)).unwrap();
167 let dimensions = image::load_from_memory(&photo.bytes)
168 .unwrap()
169 .to_rgba8()
170 .dimensions();
171 assert_eq!(dimensions, (SOURCE_SIDE, SOURCE_SIDE));
172 let texture = photo.texture(20).unwrap().image;
173 let raw = texture.as_bytes(0).unwrap().to_vec();
174 let Rgba([blue, _, red, _]) = *RgbaImage::from_raw(20, 20, raw).unwrap().get_pixel(10, 10);
175 assert!(
176 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
177 "{blue} {red}"
178 );
81 }
179 }
82
180
83 #[test]
181 #[test]
84 fn garbage_bytes_fall_back() {
182 fn garbage_bytes_fall_back() {
85 assert!(circular_png(b"not an image").is_none());
183 assert!(AvatarPhoto::from_bytes(b"not an image".to_vec()).is_none());
86 }
184 }
87}
185}
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/notify/platform/stub.rs +2 −0
@@ -34,6 +34,8 @@ pub fn show_window_inactive(_handle: NativeHandle) {}
34 34
35 35 pub fn exclude_from_capture(_handle: NativeHandle) {}
36 36
37 pub fn include_in_capture(_handle: NativeHandle) {}
38
37 39 #[cfg(target_os = "linux")]
38 40 pub fn make_window_click_through(window: &Window) {
39 41 super::x11_input::make_input_transparent(window);
@@ -34,6 +34,8 @@ pub fn show_window_inactive(_handle: NativeHandle) {}
34
34
35pub fn exclude_from_capture(_handle: NativeHandle) {}
35pub fn exclude_from_capture(_handle: NativeHandle) {}
36
36
37pub fn include_in_capture(_handle: NativeHandle) {}
38
37#[cfg(target_os = "linux")]
39#[cfg(target_os = "linux")]
38pub fn make_window_click_through(window: &Window) {
40pub fn make_window_click_through(window: &Window) {
39 super::x11_input::make_input_transparent(window);
41 super::x11_input::make_input_transparent(window);
crates/app-base/src/notify/platform/windows_impl.rs +7 −1
@@ -34,7 +34,7 @@ use windows::Win32::UI::WindowsAndMessaging::{
34 34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
35 35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
36 36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WM_SETICON, WS_CAPTION,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_SETICON, WS_CAPTION,
38 38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
39 39 };
40 40 use windows::core::{BOOL, PCWSTR, w};
@@ -272,6 +272,12 @@ pub fn exclude_from_capture(handle: NativeHandle) {
272 272 }
273 273 }
274 274
275 pub fn include_in_capture(handle: NativeHandle) {
276 unsafe {
277 let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_NONE);
278 }
279 }
280
275 281 pub fn make_window_click_through(window: &Window) {
276 282 if let Some(handle) = native_handle(window) {
277 283 make_click_through(handle);
@@ -34,7 +34,7 @@ use windows::Win32::UI::WindowsAndMessaging::{
34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
34 SW_SHOWNOACTIVATE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
35 SWP_NOZORDER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SendMessageW, SetForegroundWindow,
36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
36 SetLayeredWindowAttributes, SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WM_SETICON, WS_CAPTION,
37 ShowWindow, SystemParametersInfoW, WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_SETICON, WS_CAPTION,
38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
38 WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP, WS_THICKFRAME,
39};
39};
40use windows::core::{BOOL, PCWSTR, w};
40use windows::core::{BOOL, PCWSTR, w};
@@ -272,6 +272,12 @@ pub fn exclude_from_capture(handle: NativeHandle) {
272 }
272 }
273}
273}
274
274
275pub fn include_in_capture(handle: NativeHandle) {
276 unsafe {
277 let _ = SetWindowDisplayAffinity(hwnd(handle), WDA_NONE);
278 }
279}
280
275pub fn make_window_click_through(window: &Window) {
281pub fn make_window_click_through(window: &Window) {
276 if let Some(handle) = native_handle(window) {
282 if let Some(handle) = native_handle(window) {
277 make_click_through(handle);
283 make_click_through(handle);
crates/app-base/src/read_state.rs +28 −0
@@ -19,12 +19,40 @@ pub fn plan_read(window_active: bool, chat_unread: bool, trigger: ReadTrigger) -
19 19 })
20 20 }
21 21
22 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
23 pub enum JumpTarget {
24 LastRead(usize),
25 Newest,
26 }
27
28 pub fn jump_target(
29 last_read_index: Option<usize>,
30 top_item: usize,
31 scrolled_up: bool,
32 ) -> Option<JumpTarget> {
33 match last_read_index {
34 _ if scrolled_up => Some(JumpTarget::Newest),
35 Some(index) if index < top_item => Some(JumpTarget::LastRead(index)),
36 _ => None,
37 }
38 }
39
22 40 #[cfg(test)]
23 41 mod tests {
24 42 use std::collections::HashMap;
25 43
26 44 use super::*;
27 45
46 #[test]
47 fn jump_goes_to_last_read_from_the_newest_and_to_the_newest_from_anywhere_else() {
48 assert_eq!(jump_target(Some(4), 10, false), Some(JumpTarget::LastRead(4)));
49 assert_eq!(jump_target(Some(4), 2, true), Some(JumpTarget::Newest));
50 assert_eq!(jump_target(Some(4), 3, true), Some(JumpTarget::Newest));
51 assert_eq!(jump_target(None, 3, true), Some(JumpTarget::Newest));
52 assert_eq!(jump_target(Some(4), 4, false), None);
53 assert_eq!(jump_target(None, 0, false), None);
54 }
55
28 56 struct LocalState {
29 57 unread_counts: HashMap<String, u32>,
30 58 unread: bool,
@@ -19,12 +19,40 @@ pub fn plan_read(window_active: bool, chat_unread: bool, trigger: ReadTrigger) -
19 })
19 })
20}
20}
21
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum JumpTarget {
24 LastRead(usize),
25 Newest,
26}
27
28pub fn jump_target(
29 last_read_index: Option<usize>,
30 top_item: usize,
31 scrolled_up: bool,
32) -> Option<JumpTarget> {
33 match last_read_index {
34 _ if scrolled_up => Some(JumpTarget::Newest),
35 Some(index) if index < top_item => Some(JumpTarget::LastRead(index)),
36 _ => None,
37 }
38}
39
22#[cfg(test)]
40#[cfg(test)]
23mod tests {
41mod tests {
24 use std::collections::HashMap;
42 use std::collections::HashMap;
25
43
26 use super::*;
44 use super::*;
27
45
46 #[test]
47 fn jump_goes_to_last_read_from_the_newest_and_to_the_newest_from_anywhere_else() {
48 assert_eq!(jump_target(Some(4), 10, false), Some(JumpTarget::LastRead(4)));
49 assert_eq!(jump_target(Some(4), 2, true), Some(JumpTarget::Newest));
50 assert_eq!(jump_target(Some(4), 3, true), Some(JumpTarget::Newest));
51 assert_eq!(jump_target(None, 3, true), Some(JumpTarget::Newest));
52 assert_eq!(jump_target(Some(4), 4, false), None);
53 assert_eq!(jump_target(None, 0, false), None);
54 }
55
28 struct LocalState {
56 struct LocalState {
29 unread_counts: HashMap<String, u32>,
57 unread_counts: HashMap<String, u32>,
30 unread: bool,
58 unread: bool,
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-call-model/src/demo.rs +13 −3
@@ -104,6 +104,8 @@ pub enum DemoScene {
104 104 Mini,
105 105 MiniOff,
106 106 MiniShare,
107 GalleryShare,
108 WindowShare,
107 109 Blocked,
108 110 Removed,
109 111 Dropped,
@@ -126,6 +128,8 @@ impl DemoScene {
126 128 "mini" => DemoScene::Mini,
127 129 "mini-off" => DemoScene::MiniOff,
128 130 "mini-share" => DemoScene::MiniShare,
131 "gallery-share" => DemoScene::GalleryShare,
132 "window-share" => DemoScene::WindowShare,
129 133 "blocked" => DemoScene::Blocked,
130 134 "removed" => DemoScene::Removed,
131 135 "dropped" => DemoScene::Dropped,
@@ -163,7 +167,9 @@ impl DemoScene {
163 167 pub fn guests(self) -> Option<usize> {
164 168 match self {
165 169 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
166 DemoScene::Sharing => Some(DEMO_SHARING_GUESTS),
170 DemoScene::Sharing | DemoScene::GalleryShare | DemoScene::WindowShare => {
171 Some(DEMO_SHARING_GUESTS)
172 }
167 173 _ => None,
168 174 }
169 175 }
@@ -186,6 +192,7 @@ impl DemoScene {
186 192
187 193 pub const DEMO_GALLERY_GUESTS: usize = 12;
188 194 const DEMO_SHARING_GUESTS: usize = 9;
195 const DEMO_SHARED_WINDOW: &str = "Standup board";
189 196 const BREAKOUT_AT_TICKS: u32 = 20;
190 197 const WHITEBOARD_AT_TICKS: u32 = 5;
191 198 const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
@@ -269,7 +276,7 @@ fn demo_share_sources() -> Vec<ShareSource> {
269 276 title: String::new(),
270 277 },
271 278 window(2, "Release notes - Docs"),
272 window(3, "Standup board"),
279 window(3, DEMO_SHARED_WINDOW),
273 280 window(4, "Terminal"),
274 281 ]
275 282 }
@@ -451,9 +458,12 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
451 458 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
452 459 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
453 460 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
454 DemoScene::MiniShare => {
461 DemoScene::MiniShare | DemoScene::GalleryShare => {
455 462 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
456 463 }
464 DemoScene::WindowShare => {
465 control.send(CallUpdate::LocalShare(Some(DEMO_SHARED_WINDOW.to_owned())))
466 }
457 467 DemoScene::Call
458 468 | DemoScene::Mini
459 469 | DemoScene::MiniOff
@@ -104,6 +104,8 @@ pub enum DemoScene {
104 Mini,
104 Mini,
105 MiniOff,
105 MiniOff,
106 MiniShare,
106 MiniShare,
107 GalleryShare,
108 WindowShare,
107 Blocked,
109 Blocked,
108 Removed,
110 Removed,
109 Dropped,
111 Dropped,
@@ -126,6 +128,8 @@ impl DemoScene {
126 "mini" => DemoScene::Mini,
128 "mini" => DemoScene::Mini,
127 "mini-off" => DemoScene::MiniOff,
129 "mini-off" => DemoScene::MiniOff,
128 "mini-share" => DemoScene::MiniShare,
130 "mini-share" => DemoScene::MiniShare,
131 "gallery-share" => DemoScene::GalleryShare,
132 "window-share" => DemoScene::WindowShare,
129 "blocked" => DemoScene::Blocked,
133 "blocked" => DemoScene::Blocked,
130 "removed" => DemoScene::Removed,
134 "removed" => DemoScene::Removed,
131 "dropped" => DemoScene::Dropped,
135 "dropped" => DemoScene::Dropped,
@@ -163,7 +167,9 @@ impl DemoScene {
163 pub fn guests(self) -> Option<usize> {
167 pub fn guests(self) -> Option<usize> {
164 match self {
168 match self {
165 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
169 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
166 DemoScene::Sharing => Some(DEMO_SHARING_GUESTS),
170 DemoScene::Sharing | DemoScene::GalleryShare | DemoScene::WindowShare => {
171 Some(DEMO_SHARING_GUESTS)
172 }
167 _ => None,
173 _ => None,
168 }
174 }
169 }
175 }
@@ -186,6 +192,7 @@ impl DemoScene {
186
192
187pub const DEMO_GALLERY_GUESTS: usize = 12;
193pub const DEMO_GALLERY_GUESTS: usize = 12;
188const DEMO_SHARING_GUESTS: usize = 9;
194const DEMO_SHARING_GUESTS: usize = 9;
195const DEMO_SHARED_WINDOW: &str = "Standup board";
189const BREAKOUT_AT_TICKS: u32 = 20;
196const BREAKOUT_AT_TICKS: u32 = 20;
190const WHITEBOARD_AT_TICKS: u32 = 5;
197const WHITEBOARD_AT_TICKS: u32 = 5;
191const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
198const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
@@ -269,7 +276,7 @@ fn demo_share_sources() -> Vec<ShareSource> {
269 title: String::new(),
276 title: String::new(),
270 },
277 },
271 window(2, "Release notes - Docs"),
278 window(2, "Release notes - Docs"),
272 window(3, "Standup board"),
279 window(3, DEMO_SHARED_WINDOW),
273 window(4, "Terminal"),
280 window(4, "Terminal"),
274 ]
281 ]
275}
282}
@@ -451,9 +458,12 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
451 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
458 DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
452 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
459 DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
453 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
460 DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
454 DemoScene::MiniShare => {
461 DemoScene::MiniShare | DemoScene::GalleryShare => {
455 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
462 control.send(CallUpdate::LocalShare(Some("Entire screen".to_owned())))
456 }
463 }
464 DemoScene::WindowShare => {
465 control.send(CallUpdate::LocalShare(Some(DEMO_SHARED_WINDOW.to_owned())))
466 }
457 DemoScene::Call
467 DemoScene::Call
458 | DemoScene::Mini
468 | DemoScene::Mini
459 | DemoScene::MiniOff
469 | DemoScene::MiniOff
crates/app-state/src/app_state.rs +37 −4
@@ -90,6 +90,7 @@ pub struct AppState {
90 90 pub selection: Option<Selection>,
91 91 pub late_arrivals: LateArrivals,
92 92 pub new_chat: bool,
93 pub new_chat_people: Vec<store::MemberRecord>,
93 94 pub connection: ConnectionState,
94 95 pub live: LiveState,
95 96 pub last_sync: Option<DateTime<Utc>>,
@@ -108,6 +109,7 @@ pub struct AppState {
108 109 pub live_retry: Option<Arc<tokio::sync::Notify>>,
109 110 pub notice_count: u64,
110 111 pub keep_unread: Option<String>,
112 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
111 113 pub typing: TypingState,
112 114 typing_timer_running: bool,
113 115 pub local_previews: HashMap<String, LocalPreview>,
@@ -237,6 +239,7 @@ impl AppState {
237 239 selection: None,
238 240 late_arrivals: LateArrivals::default(),
239 241 new_chat: false,
242 new_chat_people: Vec::new(),
240 243 connection: if mode.demo {
241 244 ConnectionState::Online
242 245 } else {
@@ -259,6 +262,7 @@ impl AppState {
259 262 live_retry: None,
260 263 notice_count: 0,
261 264 keep_unread: None,
265 restorable_deletes: Default::default(),
262 266 typing: TypingState::default(),
263 267 typing_timer_running: false,
264 268 local_previews: HashMap::new(),
@@ -683,6 +687,32 @@ impl AppState {
683 687 conversation_id: &str,
684 688 folder_id: Option<&str>,
685 689 cx: &mut Context<Self>,
690 ) {
691 self.place_chat(conversation_id, folder_id, None, cx);
692 }
693
694 pub fn drop_chat_on(
695 &mut self,
696 conversation_id: &str,
697 target_conversation_id: &str,
698 folder_id: &str,
699 cx: &mut Context<Self>,
700 ) {
701 if conversation_id == target_conversation_id {
702 return;
703 }
704 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
705 return;
706 };
707 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
708 }
709
710 pub fn place_chat(
711 &mut self,
712 conversation_id: &str,
713 folder_id: Option<&str>,
714 index: Option<usize>,
715 cx: &mut Context<Self>,
686 716 ) {
687 717 if self.mode.read_only {
688 718 return;
@@ -691,13 +721,16 @@ impl AppState {
691 721 .directory
692 722 .folder_of(conversation_id)
693 723 .map(|folder| folder.id.clone());
694 self.directory.assign(conversation_id, folder_id);
724 self.directory.place(conversation_id, folder_id, index);
695 725 if let Some(engine) = self.engine.clone() {
696 726 let previous = previous_folder.clone();
697 727 let done = match (folder_id, previous.as_deref()) {
698 (Some(folder_id), _) => {
699 Some(data::move_to_folder(&engine, conversation_id, folder_id))
700 }
728 (Some(folder_id), _) => Some(data::move_to_folder(
729 &engine,
730 conversation_id,
731 folder_id,
732 index,
733 )),
701 734 (None, Some(previous)) => {
702 735 Some(data::remove_from_folder(&engine, conversation_id, previous))
703 736 }
@@ -90,6 +90,7 @@ pub struct AppState {
90 pub selection: Option<Selection>,
90 pub selection: Option<Selection>,
91 pub late_arrivals: LateArrivals,
91 pub late_arrivals: LateArrivals,
92 pub new_chat: bool,
92 pub new_chat: bool,
93 pub new_chat_people: Vec<store::MemberRecord>,
93 pub connection: ConnectionState,
94 pub connection: ConnectionState,
94 pub live: LiveState,
95 pub live: LiveState,
95 pub last_sync: Option<DateTime<Utc>>,
96 pub last_sync: Option<DateTime<Utc>>,
@@ -108,6 +109,7 @@ pub struct AppState {
108 pub live_retry: Option<Arc<tokio::sync::Notify>>,
109 pub live_retry: Option<Arc<tokio::sync::Notify>>,
109 pub notice_count: u64,
110 pub notice_count: u64,
110 pub keep_unread: Option<String>,
111 pub keep_unread: Option<String>,
112 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
111 pub typing: TypingState,
113 pub typing: TypingState,
112 typing_timer_running: bool,
114 typing_timer_running: bool,
113 pub local_previews: HashMap<String, LocalPreview>,
115 pub local_previews: HashMap<String, LocalPreview>,
@@ -237,6 +239,7 @@ impl AppState {
237 selection: None,
239 selection: None,
238 late_arrivals: LateArrivals::default(),
240 late_arrivals: LateArrivals::default(),
239 new_chat: false,
241 new_chat: false,
242 new_chat_people: Vec::new(),
240 connection: if mode.demo {
243 connection: if mode.demo {
241 ConnectionState::Online
244 ConnectionState::Online
242 } else {
245 } else {
@@ -259,6 +262,7 @@ impl AppState {
259 live_retry: None,
262 live_retry: None,
260 notice_count: 0,
263 notice_count: 0,
261 keep_unread: None,
264 keep_unread: None,
265 restorable_deletes: Default::default(),
262 typing: TypingState::default(),
266 typing: TypingState::default(),
263 typing_timer_running: false,
267 typing_timer_running: false,
264 local_previews: HashMap::new(),
268 local_previews: HashMap::new(),
@@ -683,6 +687,32 @@ impl AppState {
683 conversation_id: &str,
687 conversation_id: &str,
684 folder_id: Option<&str>,
688 folder_id: Option<&str>,
685 cx: &mut Context<Self>,
689 cx: &mut Context<Self>,
690 ) {
691 self.place_chat(conversation_id, folder_id, None, cx);
692 }
693
694 pub fn drop_chat_on(
695 &mut self,
696 conversation_id: &str,
697 target_conversation_id: &str,
698 folder_id: &str,
699 cx: &mut Context<Self>,
700 ) {
701 if conversation_id == target_conversation_id {
702 return;
703 }
704 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
705 return;
706 };
707 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
708 }
709
710 pub fn place_chat(
711 &mut self,
712 conversation_id: &str,
713 folder_id: Option<&str>,
714 index: Option<usize>,
715 cx: &mut Context<Self>,
686 ) {
716 ) {
687 if self.mode.read_only {
717 if self.mode.read_only {
688 return;
718 return;
@@ -691,13 +721,16 @@ impl AppState {
691 .directory
721 .directory
692 .folder_of(conversation_id)
722 .folder_of(conversation_id)
693 .map(|folder| folder.id.clone());
723 .map(|folder| folder.id.clone());
694 self.directory.assign(conversation_id, folder_id);
724 self.directory.place(conversation_id, folder_id, index);
695 if let Some(engine) = self.engine.clone() {
725 if let Some(engine) = self.engine.clone() {
696 let previous = previous_folder.clone();
726 let previous = previous_folder.clone();
697 let done = match (folder_id, previous.as_deref()) {
727 let done = match (folder_id, previous.as_deref()) {
698 (Some(folder_id), _) => {
728 (Some(folder_id), _) => Some(data::move_to_folder(
699 Some(data::move_to_folder(&engine, conversation_id, folder_id))
729 &engine,
700 }
730 conversation_id,
731 folder_id,
732 index,
733 )),
701 (None, Some(previous)) => {
734 (None, Some(previous)) => {
702 Some(data::remove_from_folder(&engine, conversation_id, previous))
735 Some(data::remove_from_folder(&engine, conversation_id, previous))
703 }
736 }
crates/app-state/src/call/mod.rs +1 −0
@@ -14,6 +14,7 @@ pub mod prejoin;
14 14 pub mod record_load;
15 15 pub mod reminder;
16 16 pub mod share_actions;
17 pub mod share_overlay;
17 18 pub mod schedule;
18 19 pub mod target;
19 20 pub mod view_actions;
@@ -14,6 +14,7 @@ pub mod prejoin;
14pub mod record_load;
14pub mod record_load;
15pub mod reminder;
15pub mod reminder;
16pub mod share_actions;
16pub mod share_actions;
17pub mod share_overlay;
17pub mod schedule;
18pub mod schedule;
18pub mod target;
19pub mod target;
19pub mod view_actions;
20pub mod view_actions;
crates/app-state/src/call/overlay_layout.rs +0 −11
@@ -117,10 +117,6 @@ pub fn mini_work_area(
117 117 .unwrap_or(main)
118 118 }
119 119
120 pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {
121 call_active && main_minimized
122 }
123
124 120 pub fn parse_position(text: &str) -> Option<(i32, i32)> {
125 121 let (left, top) = text.split_once(',')?;
126 122 Some((left.trim().parse().ok()?, top.trim().parse().ok()?))
@@ -276,13 +272,6 @@ mod tests {
276 272 assert_eq!((rect.width(), rect.height()), (640, 360));
277 273 }
278 274
279 #[test]
280 fn mini_shows_only_in_a_call_with_the_main_window_minimized() {
281 assert!(mini_wanted(true, true));
282 assert!(!mini_wanted(true, false));
283 assert!(!mini_wanted(false, true));
284 }
285
286 275 #[test]
287 276 fn position_round_trips() {
288 277 assert_eq!(
@@ -117,10 +117,6 @@ pub fn mini_work_area(
117 .unwrap_or(main)
117 .unwrap_or(main)
118}
118}
119
119
120pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {
121 call_active && main_minimized
122}
123
124pub fn parse_position(text: &str) -> Option<(i32, i32)> {
120pub fn parse_position(text: &str) -> Option<(i32, i32)> {
125 let (left, top) = text.split_once(',')?;
121 let (left, top) = text.split_once(',')?;
126 Some((left.trim().parse().ok()?, top.trim().parse().ok()?))
122 Some((left.trim().parse().ok()?, top.trim().parse().ok()?))
@@ -276,13 +272,6 @@ mod tests {
276 assert_eq!((rect.width(), rect.height()), (640, 360));
272 assert_eq!((rect.width(), rect.height()), (640, 360));
277 }
273 }
278
274
279 #[test]
280 fn mini_shows_only_in_a_call_with_the_main_window_minimized() {
281 assert!(mini_wanted(true, true));
282 assert!(!mini_wanted(true, false));
283 assert!(!mini_wanted(false, true));
284 }
285
286 #[test]
275 #[test]
287 fn position_round_trips() {
276 fn position_round_trips() {
288 assert_eq!(
277 assert_eq!(
crates/app-state/src/call/share_overlay.rs added +434 −0
@@ -0,0 +1,434 @@
1 use calling::ShareKind;
2
3 use super::model::{CallModel, Tile, TileState};
4 use crate::notify::platform::{ScreenRect, WorkArea};
5
6 pub const GALLERY_WIDTH: f32 = 192.;
7 pub const GALLERY_INSET: f32 = 3.;
8 pub const GALLERY_TILE_WIDTH: f32 = GALLERY_WIDTH - 2. * GALLERY_INSET;
9 pub const GALLERY_TILE_HEIGHT: f32 = GALLERY_TILE_WIDTH * 9. / 16.;
10 pub const GALLERY_TITLE_HEIGHT: f32 = 32.;
11 pub const GALLERY_CONTROLS_HEIGHT: f32 = 40.;
12 pub const GALLERY_DIVIDER_HEIGHT: f32 = 20.;
13 pub const GALLERY_MAX_TILES: usize = 4;
14 pub const GALLERY_MARGIN: f32 = 30.;
15 pub const GALLERY_POSITION_KEY: &str = "call_gallery_position";
16 pub const MINIMIZE_OVERLAP_PERCENT: i64 = 5;
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 pub enum LocalShare {
20 None,
21 Screen,
22 Window,
23 }
24
25 impl LocalShare {
26 pub fn of(kind: Option<ShareKind>, sharing: bool) -> LocalShare {
27 match (sharing, kind) {
28 (false, _) => LocalShare::None,
29 (true, Some(ShareKind::Window)) => LocalShare::Window,
30 (true, _) => LocalShare::Screen,
31 }
32 }
33 }
34
35 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
36 pub enum Monitor {
37 None,
38 Mini,
39 Gallery,
40 }
41
42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43 pub enum Surface {
44 Main,
45 ShareBar,
46 Border,
47 Mini,
48 Gallery,
49 }
50
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub struct OverlayPlan {
53 pub monitor: Monitor,
54 pub share_bar: bool,
55 pub exclude_main: bool,
56 }
57
58 pub fn overlay_plan(
59 in_call: bool,
60 share: LocalShare,
61 main_minimized: bool,
62 speaker_only: bool,
63 ) -> OverlayPlan {
64 let monitor = match (in_call && main_minimized, share) {
65 (false, _) => Monitor::None,
66 (true, LocalShare::None) => Monitor::Mini,
67 (true, _) if speaker_only => Monitor::Mini,
68 (true, _) => Monitor::Gallery,
69 };
70 OverlayPlan {
71 monitor,
72 share_bar: in_call && share != LocalShare::None,
73 exclude_main: excluded_from_capture(Surface::Main, share),
74 }
75 }
76
77 pub fn excluded_from_capture(surface: Surface, share: LocalShare) -> bool {
78 match surface {
79 Surface::Main => share == LocalShare::Screen,
80 Surface::ShareBar | Surface::Border | Surface::Mini | Surface::Gallery => true,
81 }
82 }
83
84 fn overlap_area(first: ScreenRect, second: ScreenRect) -> i64 {
85 let width = (first.right.min(second.right) - first.left.max(second.left)).max(0);
86 let height = (first.bottom.min(second.bottom) - first.top.max(second.top)).max(0);
87 i64::from(width) * i64::from(height)
88 }
89
90 pub fn minimize_on_share_start(
91 share: LocalShare,
92 main: Option<ScreenRect>,
93 shared: Option<ScreenRect>,
94 ) -> bool {
95 if share != LocalShare::Screen {
96 return false;
97 }
98 let (Some(main), Some(shared)) = (main, shared) else {
99 return true;
100 };
101 let main_area = i64::from(main.width().max(0)) * i64::from(main.height().max(0));
102 if main_area == 0 {
103 return true;
104 }
105 overlap_area(main, shared) * 100 >= MINIMIZE_OVERLAP_PERCENT * main_area
106 }
107
108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
109 pub struct GalleryLayout {
110 pub tiles: usize,
111 pub overflow: usize,
112 pub divider: bool,
113 pub self_tile: bool,
114 }
115
116 impl GalleryLayout {
117 pub fn height(&self) -> f32 {
118 let segments = self.tiles + usize::from(self.self_tile);
119 let gaps = (segments + usize::from(self.divider)).saturating_sub(1);
120 GALLERY_TITLE_HEIGHT
121 + GALLERY_INSET
122 + segments as f32 * GALLERY_TILE_HEIGHT
123 + if self.divider {
124 GALLERY_DIVIDER_HEIGHT
125 } else {
126 0.
127 }
128 + gaps as f32 * GALLERY_INSET
129 + GALLERY_INSET
130 + GALLERY_CONTROLS_HEIGHT
131 }
132 }
133
134 pub fn gallery_layout(others: usize, self_tile: bool, available_height: f32) -> GalleryLayout {
135 let build = |tiles: usize| GalleryLayout {
136 tiles,
137 overflow: others - tiles,
138 divider: others > 0 && self_tile,
139 self_tile,
140 };
141 let mut layout = build(others.min(GALLERY_MAX_TILES));
142 while layout.tiles > 1 && layout.height() > available_height {
143 layout = build(layout.tiles - 1);
144 }
145 layout
146 }
147
148 pub fn gallery_available_height(work: WorkArea) -> f32 {
149 (work.bottom - work.top) as f32 / work.scale - 2. * GALLERY_MARGIN
150 }
151
152 pub fn gallery_rect(
153 work: WorkArea,
154 layout: GalleryLayout,
155 origin: Option<(i32, i32)>,
156 ) -> ScreenRect {
157 let scaled = |logical: f32| (logical * work.scale).round() as i32;
158 let width = scaled(GALLERY_WIDTH);
159 let height = scaled(layout.height());
160 let margin = scaled(GALLERY_MARGIN);
161 let (left, top) =
162 origin.unwrap_or((work.right - width - margin, work.bottom - height - margin));
163 let left = left.clamp(work.left, (work.right - width).max(work.left));
164 let top = top.clamp(work.top, (work.bottom - height).max(work.top));
165 ScreenRect {
166 left,
167 top,
168 right: left + width,
169 bottom: top + height,
170 }
171 }
172
173 fn prioritized(model: &CallModel, tile: &Tile) -> bool {
174 model.is_pinned(&tile.mri) || tile.spotlight.is_some() || tile.hand.is_some()
175 }
176
177 pub fn gallery_candidates(model: &CallModel) -> Vec<&Tile> {
178 let mut tiles: Vec<&Tile> = model
179 .layout_tiles()
180 .into_iter()
181 .filter(|tile| tile.state == TileState::Present)
182 .collect();
183 tiles.sort_by_key(|tile| {
184 (
185 !prioritized(model, tile),
186 !(model.tile_speaking(tile) || model.is_recent_speaker(&tile.mri)),
187 )
188 });
189 tiles
190 }
191
192 #[cfg(test)]
193 mod tests {
194 use super::*;
195
196 fn work(scale: f32) -> WorkArea {
197 WorkArea {
198 left: 0,
199 top: 0,
200 right: 1920,
201 bottom: 1040,
202 scale,
203 }
204 }
205
206 fn rect(left: i32, top: i32, right: i32, bottom: i32) -> ScreenRect {
207 ScreenRect {
208 left,
209 top,
210 right,
211 bottom,
212 }
213 }
214
215 #[test]
216 fn decision_table() {
217 use LocalShare::*;
218 use Monitor as M;
219 let rows = [
220 (None, false, M::None, false, false),
221 (None, true, M::Mini, false, false),
222 (Screen, false, M::None, true, true),
223 (Screen, true, M::Gallery, true, true),
224 (Window, false, M::None, true, false),
225 (Window, true, M::Gallery, true, false),
226 ];
227 for (share, minimized, monitor, share_bar, exclude_main) in rows {
228 assert_eq!(
229 overlay_plan(true, share, minimized, false),
230 OverlayPlan {
231 monitor,
232 share_bar,
233 exclude_main
234 },
235 "{share:?} minimized={minimized}"
236 );
237 }
238 }
239
240 #[test]
241 fn speaker_only_swaps_the_gallery_for_the_mini_tile() {
242 let plan = overlay_plan(true, LocalShare::Screen, true, true);
243 assert_eq!(plan.monitor, Monitor::Mini);
244 assert!(plan.exclude_main);
245 assert_eq!(
246 overlay_plan(true, LocalShare::None, true, true).monitor,
247 Monitor::Mini
248 );
249 }
250
251 #[test]
252 fn nothing_shows_outside_a_call() {
253 let plan = overlay_plan(false, LocalShare::None, true, false);
254 assert_eq!(plan.monitor, Monitor::None);
255 assert!(!plan.share_bar);
256 }
257
258 #[test]
259 fn overlays_are_always_excluded_and_main_only_for_a_screen() {
260 for share in [LocalShare::None, LocalShare::Screen, LocalShare::Window] {
261 for surface in [
262 Surface::ShareBar,
263 Surface::Border,
264 Surface::Mini,
265 Surface::Gallery,
266 ] {
267 assert!(excluded_from_capture(surface, share));
268 }
269 }
270 assert!(excluded_from_capture(Surface::Main, LocalShare::Screen));
271 assert!(!excluded_from_capture(Surface::Main, LocalShare::Window));
272 assert!(!excluded_from_capture(Surface::Main, LocalShare::None));
273 }
274
275 #[test]
276 fn unknown_source_kind_counts_as_a_screen() {
277 assert_eq!(LocalShare::of(None, true), LocalShare::Screen);
278 assert_eq!(
279 LocalShare::of(Some(ShareKind::Window), true),
280 LocalShare::Window
281 );
282 assert_eq!(
283 LocalShare::of(Some(ShareKind::Screen), false),
284 LocalShare::None
285 );
286 }
287
288 #[test]
289 fn screen_share_minimizes_only_when_the_main_window_is_on_the_shared_monitor() {
290 let monitor = rect(0, 0, 1920, 1080);
291 let on_monitor = Some(rect(100, 100, 1100, 800));
292 let other_monitor = Some(rect(2000, 100, 3000, 800));
293 let edge = Some(rect(1880, 0, 2880, 1000));
294 assert!(minimize_on_share_start(
295 LocalShare::Screen,
296 on_monitor,
297 Some(monitor)
298 ));
299 assert!(!minimize_on_share_start(
300 LocalShare::Screen,
301 other_monitor,
302 Some(monitor)
303 ));
304 assert!(!minimize_on_share_start(
305 LocalShare::Screen,
306 edge,
307 Some(monitor)
308 ));
309 assert!(minimize_on_share_start(
310 LocalShare::Screen,
311 None,
312 Some(monitor)
313 ));
314 assert!(minimize_on_share_start(
315 LocalShare::Screen,
316 on_monitor,
317 None
318 ));
319 }
320
321 #[test]
322 fn window_share_and_no_share_never_minimize() {
323 let monitor = Some(rect(0, 0, 1920, 1080));
324 assert!(!minimize_on_share_start(
325 LocalShare::Window,
326 monitor,
327 monitor
328 ));
329 assert!(!minimize_on_share_start(LocalShare::None, monitor, monitor));
330 }
331
332 #[test]
333 fn gallery_stacks_four_tiles_a_divider_and_the_own_tile() {
334 let layout = gallery_layout(9, true, 2000.);
335 assert_eq!(
336 layout,
337 GalleryLayout {
338 tiles: 4,
339 overflow: 5,
340 divider: true,
341 self_tile: true
342 }
343 );
344 let expected = GALLERY_TITLE_HEIGHT
345 + 5. * GALLERY_TILE_HEIGHT
346 + GALLERY_DIVIDER_HEIGHT
347 + 7. * GALLERY_INSET
348 + GALLERY_CONTROLS_HEIGHT;
349 assert!((layout.height() - expected).abs() < 0.01);
350 }
351
352 #[test]
353 fn gallery_chrome_matches_teams() {
354 let chrome = GalleryLayout {
355 tiles: 0,
356 overflow: 0,
357 divider: false,
358 self_tile: false,
359 }
360 .height();
361 assert_eq!(chrome, 78.);
362 assert_eq!(GALLERY_TILE_WIDTH, 186.);
363 }
364
365 #[test]
366 fn gallery_drops_tiles_to_fit_a_short_screen() {
367 let layout = gallery_layout(9, true, 500.);
368 assert!(layout.height() <= 500.);
369 assert_eq!(layout.tiles, 2);
370 assert_eq!(layout.overflow, 7);
371 assert_eq!(gallery_layout(9, true, 10.).tiles, 1);
372 }
373
374 #[test]
375 fn gallery_without_others_has_no_divider() {
376 let layout = gallery_layout(0, true, 2000.);
377 assert_eq!(
378 (layout.tiles, layout.divider, layout.self_tile),
379 (0, false, true)
380 );
381 let hidden_self = gallery_layout(3, false, 2000.);
382 assert_eq!((hidden_self.tiles, hidden_self.divider), (3, false));
383 }
384
385 #[test]
386 fn gallery_defaults_to_the_bottom_right_with_the_teams_margin() {
387 let layout = gallery_layout(2, true, 2000.);
388 let placed = gallery_rect(work(1.), layout, None);
389 assert_eq!(placed.width(), 192);
390 assert_eq!((placed.right, placed.bottom), (1920 - 30, 1040 - 30));
391 assert_eq!(placed.height(), layout.height().round() as i32);
392 }
393
394 #[test]
395 fn gallery_keeps_a_dragged_origin_inside_the_work_area() {
396 let layout = gallery_layout(4, true, 2000.);
397 assert_eq!(gallery_rect(work(1.), layout, Some((200, 100))).left, 200);
398 let pushed = gallery_rect(work(1.), layout, Some((5000, 900)));
399 assert_eq!((pushed.right, pushed.bottom), (1920, 1040));
400 }
401
402 #[test]
403 fn gallery_scales_with_the_monitor() {
404 let layout = gallery_layout(1, false, 2000.);
405 let placed = gallery_rect(work(2.), layout, None);
406 assert_eq!(placed.width(), 384);
407 assert_eq!(gallery_available_height(work(2.)), 520. - 60.);
408 }
409
410 fn present(mri: &str, name: &str) -> Tile {
411 Tile {
412 state: TileState::Present,
413 ..Tile::invited(mri, name)
414 }
415 }
416
417 #[test]
418 fn candidates_put_pinned_then_speakers_first() {
419 let mut model = CallModel::test();
420 model.tiles = vec![
421 present("8:a", "Ada"),
422 present("8:b", "Bo"),
423 present("8:c", "Cy"),
424 Tile::invited("8:d", "Dee"),
425 ];
426 model.speaking_mris = vec!["8:c".to_owned()];
427 model.toggle_pin("8:b");
428 let names: Vec<&str> = gallery_candidates(&model)
429 .iter()
430 .map(|tile| tile.name.as_str())
431 .collect();
432 assert_eq!(names, ["Bo", "Cy", "Ada"]);
433 }
434 }
@@ -0,0 +1,434 @@
1use calling::ShareKind;
2
3use super::model::{CallModel, Tile, TileState};
4use crate::notify::platform::{ScreenRect, WorkArea};
5
6pub const GALLERY_WIDTH: f32 = 192.;
7pub const GALLERY_INSET: f32 = 3.;
8pub const GALLERY_TILE_WIDTH: f32 = GALLERY_WIDTH - 2. * GALLERY_INSET;
9pub const GALLERY_TILE_HEIGHT: f32 = GALLERY_TILE_WIDTH * 9. / 16.;
10pub const GALLERY_TITLE_HEIGHT: f32 = 32.;
11pub const GALLERY_CONTROLS_HEIGHT: f32 = 40.;
12pub const GALLERY_DIVIDER_HEIGHT: f32 = 20.;
13pub const GALLERY_MAX_TILES: usize = 4;
14pub const GALLERY_MARGIN: f32 = 30.;
15pub const GALLERY_POSITION_KEY: &str = "call_gallery_position";
16pub const MINIMIZE_OVERLAP_PERCENT: i64 = 5;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum LocalShare {
20 None,
21 Screen,
22 Window,
23}
24
25impl LocalShare {
26 pub fn of(kind: Option<ShareKind>, sharing: bool) -> LocalShare {
27 match (sharing, kind) {
28 (false, _) => LocalShare::None,
29 (true, Some(ShareKind::Window)) => LocalShare::Window,
30 (true, _) => LocalShare::Screen,
31 }
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Monitor {
37 None,
38 Mini,
39 Gallery,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Surface {
44 Main,
45 ShareBar,
46 Border,
47 Mini,
48 Gallery,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct OverlayPlan {
53 pub monitor: Monitor,
54 pub share_bar: bool,
55 pub exclude_main: bool,
56}
57
58pub fn overlay_plan(
59 in_call: bool,
60 share: LocalShare,
61 main_minimized: bool,
62 speaker_only: bool,
63) -> OverlayPlan {
64 let monitor = match (in_call && main_minimized, share) {
65 (false, _) => Monitor::None,
66 (true, LocalShare::None) => Monitor::Mini,
67 (true, _) if speaker_only => Monitor::Mini,
68 (true, _) => Monitor::Gallery,
69 };
70 OverlayPlan {
71 monitor,
72 share_bar: in_call && share != LocalShare::None,
73 exclude_main: excluded_from_capture(Surface::Main, share),
74 }
75}
76
77pub fn excluded_from_capture(surface: Surface, share: LocalShare) -> bool {
78 match surface {
79 Surface::Main => share == LocalShare::Screen,
80 Surface::ShareBar | Surface::Border | Surface::Mini | Surface::Gallery => true,
81 }
82}
83
84fn overlap_area(first: ScreenRect, second: ScreenRect) -> i64 {
85 let width = (first.right.min(second.right) - first.left.max(second.left)).max(0);
86 let height = (first.bottom.min(second.bottom) - first.top.max(second.top)).max(0);
87 i64::from(width) * i64::from(height)
88}
89
90pub fn minimize_on_share_start(
91 share: LocalShare,
92 main: Option<ScreenRect>,
93 shared: Option<ScreenRect>,
94) -> bool {
95 if share != LocalShare::Screen {
96 return false;
97 }
98 let (Some(main), Some(shared)) = (main, shared) else {
99 return true;
100 };
101 let main_area = i64::from(main.width().max(0)) * i64::from(main.height().max(0));
102 if main_area == 0 {
103 return true;
104 }
105 overlap_area(main, shared) * 100 >= MINIMIZE_OVERLAP_PERCENT * main_area
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct GalleryLayout {
110 pub tiles: usize,
111 pub overflow: usize,
112 pub divider: bool,
113 pub self_tile: bool,
114}
115
116impl GalleryLayout {
117 pub fn height(&self) -> f32 {
118 let segments = self.tiles + usize::from(self.self_tile);
119 let gaps = (segments + usize::from(self.divider)).saturating_sub(1);
120 GALLERY_TITLE_HEIGHT
121 + GALLERY_INSET
122 + segments as f32 * GALLERY_TILE_HEIGHT
123 + if self.divider {
124 GALLERY_DIVIDER_HEIGHT
125 } else {
126 0.
127 }
128 + gaps as f32 * GALLERY_INSET
129 + GALLERY_INSET
130 + GALLERY_CONTROLS_HEIGHT
131 }
132}
133
134pub fn gallery_layout(others: usize, self_tile: bool, available_height: f32) -> GalleryLayout {
135 let build = |tiles: usize| GalleryLayout {
136 tiles,
137 overflow: others - tiles,
138 divider: others > 0 && self_tile,
139 self_tile,
140 };
141 let mut layout = build(others.min(GALLERY_MAX_TILES));
142 while layout.tiles > 1 && layout.height() > available_height {
143 layout = build(layout.tiles - 1);
144 }
145 layout
146}
147
148pub fn gallery_available_height(work: WorkArea) -> f32 {
149 (work.bottom - work.top) as f32 / work.scale - 2. * GALLERY_MARGIN
150}
151
152pub fn gallery_rect(
153 work: WorkArea,
154 layout: GalleryLayout,
155 origin: Option<(i32, i32)>,
156) -> ScreenRect {
157 let scaled = |logical: f32| (logical * work.scale).round() as i32;
158 let width = scaled(GALLERY_WIDTH);
159 let height = scaled(layout.height());
160 let margin = scaled(GALLERY_MARGIN);
161 let (left, top) =
162 origin.unwrap_or((work.right - width - margin, work.bottom - height - margin));
163 let left = left.clamp(work.left, (work.right - width).max(work.left));
164 let top = top.clamp(work.top, (work.bottom - height).max(work.top));
165 ScreenRect {
166 left,
167 top,
168 right: left + width,
169 bottom: top + height,
170 }
171}
172
173fn prioritized(model: &CallModel, tile: &Tile) -> bool {
174 model.is_pinned(&tile.mri) || tile.spotlight.is_some() || tile.hand.is_some()
175}
176
177pub fn gallery_candidates(model: &CallModel) -> Vec<&Tile> {
178 let mut tiles: Vec<&Tile> = model
179 .layout_tiles()
180 .into_iter()
181 .filter(|tile| tile.state == TileState::Present)
182 .collect();
183 tiles.sort_by_key(|tile| {
184 (
185 !prioritized(model, tile),
186 !(model.tile_speaking(tile) || model.is_recent_speaker(&tile.mri)),
187 )
188 });
189 tiles
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 fn work(scale: f32) -> WorkArea {
197 WorkArea {
198 left: 0,
199 top: 0,
200 right: 1920,
201 bottom: 1040,
202 scale,
203 }
204 }
205
206 fn rect(left: i32, top: i32, right: i32, bottom: i32) -> ScreenRect {
207 ScreenRect {
208 left,
209 top,
210 right,
211 bottom,
212 }
213 }
214
215 #[test]
216 fn decision_table() {
217 use LocalShare::*;
218 use Monitor as M;
219 let rows = [
220 (None, false, M::None, false, false),
221 (None, true, M::Mini, false, false),
222 (Screen, false, M::None, true, true),
223 (Screen, true, M::Gallery, true, true),
224 (Window, false, M::None, true, false),
225 (Window, true, M::Gallery, true, false),
226 ];
227 for (share, minimized, monitor, share_bar, exclude_main) in rows {
228 assert_eq!(
229 overlay_plan(true, share, minimized, false),
230 OverlayPlan {
231 monitor,
232 share_bar,
233 exclude_main
234 },
235 "{share:?} minimized={minimized}"
236 );
237 }
238 }
239
240 #[test]
241 fn speaker_only_swaps_the_gallery_for_the_mini_tile() {
242 let plan = overlay_plan(true, LocalShare::Screen, true, true);
243 assert_eq!(plan.monitor, Monitor::Mini);
244 assert!(plan.exclude_main);
245 assert_eq!(
246 overlay_plan(true, LocalShare::None, true, true).monitor,
247 Monitor::Mini
248 );
249 }
250
251 #[test]
252 fn nothing_shows_outside_a_call() {
253 let plan = overlay_plan(false, LocalShare::None, true, false);
254 assert_eq!(plan.monitor, Monitor::None);
255 assert!(!plan.share_bar);
256 }
257
258 #[test]
259 fn overlays_are_always_excluded_and_main_only_for_a_screen() {
260 for share in [LocalShare::None, LocalShare::Screen, LocalShare::Window] {
261 for surface in [
262 Surface::ShareBar,
263 Surface::Border,
264 Surface::Mini,
265 Surface::Gallery,
266 ] {
267 assert!(excluded_from_capture(surface, share));
268 }
269 }
270 assert!(excluded_from_capture(Surface::Main, LocalShare::Screen));
271 assert!(!excluded_from_capture(Surface::Main, LocalShare::Window));
272 assert!(!excluded_from_capture(Surface::Main, LocalShare::None));
273 }
274
275 #[test]
276 fn unknown_source_kind_counts_as_a_screen() {
277 assert_eq!(LocalShare::of(None, true), LocalShare::Screen);
278 assert_eq!(
279 LocalShare::of(Some(ShareKind::Window), true),
280 LocalShare::Window
281 );
282 assert_eq!(
283 LocalShare::of(Some(ShareKind::Screen), false),
284 LocalShare::None
285 );
286 }
287
288 #[test]
289 fn screen_share_minimizes_only_when_the_main_window_is_on_the_shared_monitor() {
290 let monitor = rect(0, 0, 1920, 1080);
291 let on_monitor = Some(rect(100, 100, 1100, 800));
292 let other_monitor = Some(rect(2000, 100, 3000, 800));
293 let edge = Some(rect(1880, 0, 2880, 1000));
294 assert!(minimize_on_share_start(
295 LocalShare::Screen,
296 on_monitor,
297 Some(monitor)
298 ));
299 assert!(!minimize_on_share_start(
300 LocalShare::Screen,
301 other_monitor,
302 Some(monitor)
303 ));
304 assert!(!minimize_on_share_start(
305 LocalShare::Screen,
306 edge,
307 Some(monitor)
308 ));
309 assert!(minimize_on_share_start(
310 LocalShare::Screen,
311 None,
312 Some(monitor)
313 ));
314 assert!(minimize_on_share_start(
315 LocalShare::Screen,
316 on_monitor,
317 None
318 ));
319 }
320
321 #[test]
322 fn window_share_and_no_share_never_minimize() {
323 let monitor = Some(rect(0, 0, 1920, 1080));
324 assert!(!minimize_on_share_start(
325 LocalShare::Window,
326 monitor,
327 monitor
328 ));
329 assert!(!minimize_on_share_start(LocalShare::None, monitor, monitor));
330 }
331
332 #[test]
333 fn gallery_stacks_four_tiles_a_divider_and_the_own_tile() {
334 let layout = gallery_layout(9, true, 2000.);
335 assert_eq!(
336 layout,
337 GalleryLayout {
338 tiles: 4,
339 overflow: 5,
340 divider: true,
341 self_tile: true
342 }
343 );
344 let expected = GALLERY_TITLE_HEIGHT
345 + 5. * GALLERY_TILE_HEIGHT
346 + GALLERY_DIVIDER_HEIGHT
347 + 7. * GALLERY_INSET
348 + GALLERY_CONTROLS_HEIGHT;
349 assert!((layout.height() - expected).abs() < 0.01);
350 }
351
352 #[test]
353 fn gallery_chrome_matches_teams() {
354 let chrome = GalleryLayout {
355 tiles: 0,
356 overflow: 0,
357 divider: false,
358 self_tile: false,
359 }
360 .height();
361 assert_eq!(chrome, 78.);
362 assert_eq!(GALLERY_TILE_WIDTH, 186.);
363 }
364
365 #[test]
366 fn gallery_drops_tiles_to_fit_a_short_screen() {
367 let layout = gallery_layout(9, true, 500.);
368 assert!(layout.height() <= 500.);
369 assert_eq!(layout.tiles, 2);
370 assert_eq!(layout.overflow, 7);
371 assert_eq!(gallery_layout(9, true, 10.).tiles, 1);
372 }
373
374 #[test]
375 fn gallery_without_others_has_no_divider() {
376 let layout = gallery_layout(0, true, 2000.);
377 assert_eq!(
378 (layout.tiles, layout.divider, layout.self_tile),
379 (0, false, true)
380 );
381 let hidden_self = gallery_layout(3, false, 2000.);
382 assert_eq!((hidden_self.tiles, hidden_self.divider), (3, false));
383 }
384
385 #[test]
386 fn gallery_defaults_to_the_bottom_right_with_the_teams_margin() {
387 let layout = gallery_layout(2, true, 2000.);
388 let placed = gallery_rect(work(1.), layout, None);
389 assert_eq!(placed.width(), 192);
390 assert_eq!((placed.right, placed.bottom), (1920 - 30, 1040 - 30));
391 assert_eq!(placed.height(), layout.height().round() as i32);
392 }
393
394 #[test]
395 fn gallery_keeps_a_dragged_origin_inside_the_work_area() {
396 let layout = gallery_layout(4, true, 2000.);
397 assert_eq!(gallery_rect(work(1.), layout, Some((200, 100))).left, 200);
398 let pushed = gallery_rect(work(1.), layout, Some((5000, 900)));
399 assert_eq!((pushed.right, pushed.bottom), (1920, 1040));
400 }
401
402 #[test]
403 fn gallery_scales_with_the_monitor() {
404 let layout = gallery_layout(1, false, 2000.);
405 let placed = gallery_rect(work(2.), layout, None);
406 assert_eq!(placed.width(), 384);
407 assert_eq!(gallery_available_height(work(2.)), 520. - 60.);
408 }
409
410 fn present(mri: &str, name: &str) -> Tile {
411 Tile {
412 state: TileState::Present,
413 ..Tile::invited(mri, name)
414 }
415 }
416
417 #[test]
418 fn candidates_put_pinned_then_speakers_first() {
419 let mut model = CallModel::test();
420 model.tiles = vec![
421 present("8:a", "Ada"),
422 present("8:b", "Bo"),
423 present("8:c", "Cy"),
424 Tile::invited("8:d", "Dee"),
425 ];
426 model.speaking_mris = vec!["8:c".to_owned()];
427 model.toggle_pin("8:b");
428 let names: Vec<&str> = gallery_candidates(&model)
429 .iter()
430 .map(|tile| tile.name.as_str())
431 .collect();
432 assert_eq!(names, ["Bo", "Cy", "Ada"]);
433 }
434}
crates/app-state/src/call_rows.rs +36 −0
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2 2
3 3 use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4 4 use store::MessageRecord;
5 use teams_core::roster_event::RosterEvent;
5 6 use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};
6 7
7 8 use crate::format;
@@ -12,6 +13,8 @@ const RECAP_DATE_FORMAT: &str = "%A, %-d %B %Y %H:%M";
12 13 const RECAP_TIME_FORMAT: &str = "%H:%M";
13 14 const AUTO_STOP_SECONDS: i64 = 5;
14 15 const WEEKDAY_STAMP_DAYS: i64 = 6;
16 const OWN_NAME: &str = "You";
17 const UNKNOWN_USER: &str = "Unknown User";
15 18
16 19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17 20 pub enum CallIcon {
@@ -21,6 +24,7 @@ pub enum CallIcon {
21 24 Record,
22 25 RecordStop,
23 26 Saved,
27 Roster,
24 28 }
25 29
26 30 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -95,6 +99,38 @@ impl CallNames<'_> {
95 99 .map(str::to_owned)
96 100 .or_else(|| self.names.get(user_id?).cloned())
97 101 }
102
103 fn roster_name(&self, user_id: Option<&str>, given: Option<&str>) -> String {
104 if user_id.is_some() && user_id == self.my_user_id {
105 return OWN_NAME.to_owned();
106 }
107 self.name(user_id, given)
108 .unwrap_or_else(|| UNKNOWN_USER.to_owned())
109 }
110 }
111
112 /// A member added, removed or leaving: one muted line with the people icon, like Teams.
113 pub fn roster_card(
114 event: &RosterEvent,
115 created_at: DateTime<Utc>,
116 names: &CallNames,
117 clock: &CallClock,
118 ) -> CallCard {
119 CallCard {
120 title: String::new(),
121 detail: String::new(),
122 icon: CallIcon::Roster,
123 missed: false,
124 started: false,
125 participants: Vec::new(),
126 extra_participants: 0,
127 notice: Some(CallNotice {
128 stamp: notice_stamp(created_at, clock),
129 text: event.text(|user_id, given| names.roster_name(user_id, given)),
130 emphasis: None,
131 }),
132 recap: None,
133 }
98 134 }
99 135
100 136 pub struct CallClock<'a> {
@@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet};
2
2
3use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
3use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4use store::MessageRecord;
4use store::MessageRecord;
5use teams_core::roster_event::RosterEvent;
5use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};
6use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};
6
7
7use crate::format;
8use crate::format;
@@ -12,6 +13,8 @@ const RECAP_DATE_FORMAT: &str = "%A, %-d %B %Y %H:%M";
12const RECAP_TIME_FORMAT: &str = "%H:%M";
13const RECAP_TIME_FORMAT: &str = "%H:%M";
13const AUTO_STOP_SECONDS: i64 = 5;
14const AUTO_STOP_SECONDS: i64 = 5;
14const WEEKDAY_STAMP_DAYS: i64 = 6;
15const WEEKDAY_STAMP_DAYS: i64 = 6;
16const OWN_NAME: &str = "You";
17const UNKNOWN_USER: &str = "Unknown User";
15
18
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum CallIcon {
20pub enum CallIcon {
@@ -21,6 +24,7 @@ pub enum CallIcon {
21 Record,
24 Record,
22 RecordStop,
25 RecordStop,
23 Saved,
26 Saved,
27 Roster,
24}
28}
25
29
26#[derive(Debug, Clone, PartialEq, Eq)]
30#[derive(Debug, Clone, PartialEq, Eq)]
@@ -95,6 +99,38 @@ impl CallNames<'_> {
95 .map(str::to_owned)
99 .map(str::to_owned)
96 .or_else(|| self.names.get(user_id?).cloned())
100 .or_else(|| self.names.get(user_id?).cloned())
97 }
101 }
102
103 fn roster_name(&self, user_id: Option<&str>, given: Option<&str>) -> String {
104 if user_id.is_some() && user_id == self.my_user_id {
105 return OWN_NAME.to_owned();
106 }
107 self.name(user_id, given)
108 .unwrap_or_else(|| UNKNOWN_USER.to_owned())
109 }
110}
111
112/// A member added, removed or leaving: one muted line with the people icon, like Teams.
113pub fn roster_card(
114 event: &RosterEvent,
115 created_at: DateTime<Utc>,
116 names: &CallNames,
117 clock: &CallClock,
118) -> CallCard {
119 CallCard {
120 title: String::new(),
121 detail: String::new(),
122 icon: CallIcon::Roster,
123 missed: false,
124 started: false,
125 participants: Vec::new(),
126 extra_participants: 0,
127 notice: Some(CallNotice {
128 stamp: notice_stamp(created_at, clock),
129 text: event.text(|user_id, given| names.roster_name(user_id, given)),
130 emphasis: None,
131 }),
132 recap: None,
133 }
98}
134}
99
135
100pub struct CallClock<'a> {
136pub struct CallClock<'a> {
crates/app-state/src/chat_actions.rs +84 −1
@@ -2,7 +2,9 @@ use std::future::Future;
2 2
3 3 use chrono::{DateTime, Duration, Local, Offset, Utc};
4 4 use gpui_kit::*;
5 use store::{ChannelNotifications, ChatRecord};
5 use chatsvc::HistoryShare;
6 use store::{ChannelNotifications, ChatRecord, MemberRecord};
7 use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
6 8
7 9 use crate::app_state::{AppState, Selection, chat_title};
8 10 use crate::notice::{NoticeAction, short_error, truncated};
@@ -238,6 +240,87 @@ impl AppState {
238 240 );
239 241 }
240 242
243 pub fn add_chat_members(
244 &mut self,
245 chat_id: &str,
246 people: Vec<MemberRecord>,
247 share: HistoryShare,
248 cx: &mut Context<Self>,
249 ) {
250 let Some(chat) = self.chat_record(chat_id) else {
251 return;
252 };
253 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
254 return;
255 };
256 let mut with_members = chat.clone();
257 merge_members(&mut with_members.members, &people);
258 let _ = self
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
261 self.reload_sidebar(cx);
262 let Some(engine) = engine_or_demo else {
263 self.add_demo_roster_line(chat_id, &people, share, cx);
264 return;
265 };
266 let owned_chat_id = chat_id.to_owned();
267 self.run_chat_action(
268 "Add people",
269 async move {
270 engine
271 .add_chat_members(&owned_chat_id, &people, share)
272 .await
273 },
274 move |state, cx| state.restore_chat_locally(&chat, cx),
275 |_, _| {},
276 cx,
277 );
278 }
279
280 fn add_demo_roster_line(
281 &mut self,
282 chat_id: &str,
283 people: &[MemberRecord],
284 share: HistoryShare,
285 cx: &mut Context<Self>,
286 ) {
287 let me = self.directory.me.as_ref();
288 let event = RosterEvent {
289 change: RosterChange::Added,
290 initiator_id: me.map(|person| person.user_id.clone()),
291 initiator_name: me.map(|person| person.display_name.clone()),
292 member_ids: people
293 .iter()
294 .filter_map(|person| person.user_id.clone())
295 .collect(),
296 member_names: people
297 .iter()
298 .map(|person| Some(person.display_name.clone()))
299 .collect(),
300 history: match share {
301 HistoryShare::None => SharedHistory::None,
302 HistoryShare::Days(days) => SharedHistory::Days(days),
303 HistoryShare::All => SharedHistory::All,
304 },
305 };
306 let now = Utc::now();
307 let record = crate::demo::roster_record(
308 chat_id,
309 &format!("demo-roster-{}", now.timestamp_millis()),
310 now,
311 &event,
312 );
313 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 cx.notify();
316 }
317
318 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 self.new_chat_people = people;
321 self.start_new_chat(cx);
322 }
323
241 324 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
242 325 self.sidebar
243 326 .chats
@@ -2,7 +2,9 @@ use std::future::Future;
2
2
3use chrono::{DateTime, Duration, Local, Offset, Utc};
3use chrono::{DateTime, Duration, Local, Offset, Utc};
4use gpui_kit::*;
4use gpui_kit::*;
5use store::{ChannelNotifications, ChatRecord};
5use chatsvc::HistoryShare;
6use store::{ChannelNotifications, ChatRecord, MemberRecord};
7use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
6
8
7use crate::app_state::{AppState, Selection, chat_title};
9use crate::app_state::{AppState, Selection, chat_title};
8use crate::notice::{NoticeAction, short_error, truncated};
10use crate::notice::{NoticeAction, short_error, truncated};
@@ -238,6 +240,87 @@ impl AppState {
238 );
240 );
239 }
241 }
240
242
243 pub fn add_chat_members(
244 &mut self,
245 chat_id: &str,
246 people: Vec<MemberRecord>,
247 share: HistoryShare,
248 cx: &mut Context<Self>,
249 ) {
250 let Some(chat) = self.chat_record(chat_id) else {
251 return;
252 };
253 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
254 return;
255 };
256 let mut with_members = chat.clone();
257 merge_members(&mut with_members.members, &people);
258 let _ = self
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
261 self.reload_sidebar(cx);
262 let Some(engine) = engine_or_demo else {
263 self.add_demo_roster_line(chat_id, &people, share, cx);
264 return;
265 };
266 let owned_chat_id = chat_id.to_owned();
267 self.run_chat_action(
268 "Add people",
269 async move {
270 engine
271 .add_chat_members(&owned_chat_id, &people, share)
272 .await
273 },
274 move |state, cx| state.restore_chat_locally(&chat, cx),
275 |_, _| {},
276 cx,
277 );
278 }
279
280 fn add_demo_roster_line(
281 &mut self,
282 chat_id: &str,
283 people: &[MemberRecord],
284 share: HistoryShare,
285 cx: &mut Context<Self>,
286 ) {
287 let me = self.directory.me.as_ref();
288 let event = RosterEvent {
289 change: RosterChange::Added,
290 initiator_id: me.map(|person| person.user_id.clone()),
291 initiator_name: me.map(|person| person.display_name.clone()),
292 member_ids: people
293 .iter()
294 .filter_map(|person| person.user_id.clone())
295 .collect(),
296 member_names: people
297 .iter()
298 .map(|person| Some(person.display_name.clone()))
299 .collect(),
300 history: match share {
301 HistoryShare::None => SharedHistory::None,
302 HistoryShare::Days(days) => SharedHistory::Days(days),
303 HistoryShare::All => SharedHistory::All,
304 },
305 };
306 let now = Utc::now();
307 let record = crate::demo::roster_record(
308 chat_id,
309 &format!("demo-roster-{}", now.timestamp_millis()),
310 now,
311 &event,
312 );
313 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 cx.notify();
316 }
317
318 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 self.new_chat_people = people;
321 self.start_new_chat(cx);
322 }
323
241 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
324 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
242 self.sidebar
325 self.sidebar
243 .chats
326 .chats
crates/app-state/src/data.rs +73 −19
@@ -9,6 +9,7 @@ use store::{ChatRecord, Store, is_bot_id};
9 9 use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10 10 use tokio::sync::oneshot;
11 11
12 use crate::avatar_image::AvatarPhoto;
12 13 use crate::backend::Engine;
13 14 use crate::runtime;
14 15
@@ -113,7 +114,8 @@ impl Presence {
113 114 pub enum AvatarState {
114 115 Pending,
115 116 Missing,
116 Ready(Arc<Image>),
117 Ready(Arc<AvatarPhoto>),
118 Icon(Arc<Image>),
117 119 }
118 120
119 121 #[derive(Debug, Clone)]
@@ -201,8 +203,7 @@ impl Directory {
201 203 }
202 204 }
203 205
204 pub fn set_avatar(&mut self, user_id: &str, image: Option<Arc<Image>>) {
205 let state = image.map_or(AvatarState::Missing, AvatarState::Ready);
206 pub fn set_avatar(&mut self, user_id: &str, state: AvatarState) {
206 207 self.avatars.insert(user_id.to_owned(), state);
207 208 }
208 209
@@ -330,16 +331,34 @@ impl Directory {
330 331 }
331 332
332 333 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
334 self.place(conversation_id, folder_id, None);
335 }
336
337 pub fn place(&mut self, conversation_id: &str, folder_id: Option<&str>, index: Option<usize>) {
333 338 for folder in &mut self.folders {
334 339 folder.conversation_ids.retain(|id| id != conversation_id);
335 340 }
336 341 if let Some(folder) =
337 342 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
338 343 {
339 folder.conversation_ids.push(conversation_id.to_owned());
344 let position = index.map_or(folder.conversation_ids.len(), |index| {
345 index.min(folder.conversation_ids.len())
346 });
347 folder
348 .conversation_ids
349 .insert(position, conversation_id.to_owned());
340 350 }
341 351 }
342 352
353 pub fn slot_of(&self, folder_id: &str, conversation_id: &str) -> Option<usize> {
354 self.folders
355 .iter()
356 .find(|folder| folder.id == folder_id)?
357 .conversation_ids
358 .iter()
359 .position(|id| id == conversation_id)
360 }
361
343 362 pub fn move_targets(&self) -> Vec<(String, String)> {
344 363 let favorites = self.favorites().map(|folder| {
345 364 let name = folder.name.trim();
@@ -539,21 +558,24 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
539 558 store.pinned_channel_ids().unwrap_or_default()
540 559 }
541 560
542 pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
561 pub fn cached_avatar(store: &Store, user_id: &str) -> Option<AvatarState> {
543 562 let record = store.avatar(user_id).ok().flatten()?;
544 Some(record.bytes.map(|bytes| {
545 if is_bot_id(user_id) {
546 Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
547 } else {
548 avatar_image_from(&record.content_type, bytes)
549 }
550 }))
563 Some(match record.bytes {
564 Some(bytes) => avatar_state_from(&record.content_type, bytes, is_bot_id(user_id)),
565 None => AvatarState::Missing,
566 })
551 567 }
552 568
553 pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
554 match crate::avatar_image::circular_png(&bytes) {
555 Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
556 None => Arc::new(Image::from_bytes(image_format(content_type), bytes)),
569 pub fn avatar_state_from(content_type: &str, bytes: Vec<u8>, is_bot: bool) -> AvatarState {
570 if image_format(content_type) == ImageFormat::Svg {
571 if is_bot {
572 return AvatarState::Icon(Arc::new(Image::from_bytes(ImageFormat::Svg, bytes)));
573 }
574 return AvatarState::Missing;
575 }
576 match AvatarPhoto::from_bytes(bytes) {
577 Some(photo) => AvatarState::Ready(Arc::new(photo)),
578 None => AvatarState::Missing,
557 579 }
558 580 }
559 581
@@ -643,13 +665,22 @@ pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
643 665 run(async move { engine.watch_presence(&user_ids).await })
644 666 }
645 667
646 pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
668 pub fn move_to_folder(
669 engine: &Arc<Engine>,
670 conversation_id: &str,
671 folder_id: &str,
672 index: Option<usize>,
673 ) -> Done {
647 674 let (engine, conversation_id, folder_id) = (
648 675 engine.clone(),
649 676 conversation_id.to_owned(),
650 677 folder_id.to_owned(),
651 678 );
652 run(async move { engine.move_to_folder(&conversation_id, &folder_id).await })
679 run(async move {
680 engine
681 .move_to_folder(&conversation_id, &folder_id, index)
682 .await
683 })
653 684 }
654 685
655 686 pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
@@ -715,6 +746,29 @@ mod tests {
715 746 }
716 747 }
717 748
749 #[test]
750 fn place_puts_a_chat_at_the_slot_inside_and_across_folders() {
751 let mut directory = Directory {
752 folders: vec![
753 folder("fav", FolderKind::Favorites, &["a", "b", "c"]),
754 folder("work", FolderKind::UserCreated, &["d"]),
755 ],
756 ..Default::default()
757 };
758 directory.place("a", Some("fav"), Some(2));
759 assert_eq!(directory.folders[0].conversation_ids, vec!["b", "c", "a"]);
760 directory.place("d", Some("fav"), Some(0));
761 assert_eq!(
762 directory.folders[0].conversation_ids,
763 vec!["d", "b", "c", "a"]
764 );
765 assert!(directory.folders[1].conversation_ids.is_empty());
766 directory.place("b", Some("work"), Some(9));
767 assert_eq!(directory.folders[1].conversation_ids, vec!["b"]);
768 assert_eq!(directory.slot_of("fav", "c"), Some(1));
769 assert_eq!(directory.slot_of("work", "c"), None);
770 }
771
718 772 #[test]
719 773 fn assign_moves_a_chat_between_folders() {
720 774 let mut directory = Directory {
@@ -821,7 +875,7 @@ mod tests {
821 875 #[test]
822 876 fn missing_avatars_skip_known_and_duplicates() {
823 877 let mut directory = Directory::default();
824 directory.set_avatar("known", None);
878 directory.set_avatar("known", AvatarState::Missing);
825 879 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
826 880 assert_eq!(wanted, vec!["x", "y"]);
827 881 directory.mark_avatars_pending(&wanted);
@@ -9,6 +9,7 @@ use store::{ChatRecord, Store, is_bot_id};
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10use tokio::sync::oneshot;
10use tokio::sync::oneshot;
11
11
12use crate::avatar_image::AvatarPhoto;
12use crate::backend::Engine;
13use crate::backend::Engine;
13use crate::runtime;
14use crate::runtime;
14
15
@@ -113,7 +114,8 @@ impl Presence {
113pub enum AvatarState {
114pub enum AvatarState {
114 Pending,
115 Pending,
115 Missing,
116 Missing,
116 Ready(Arc<Image>),
117 Ready(Arc<AvatarPhoto>),
118 Icon(Arc<Image>),
117}
119}
118
120
119#[derive(Debug, Clone)]
121#[derive(Debug, Clone)]
@@ -201,8 +203,7 @@ impl Directory {
201 }
203 }
202 }
204 }
203
205
204 pub fn set_avatar(&mut self, user_id: &str, image: Option<Arc<Image>>) {
206 pub fn set_avatar(&mut self, user_id: &str, state: AvatarState) {
205 let state = image.map_or(AvatarState::Missing, AvatarState::Ready);
206 self.avatars.insert(user_id.to_owned(), state);
207 self.avatars.insert(user_id.to_owned(), state);
207 }
208 }
208
209
@@ -330,16 +331,34 @@ impl Directory {
330 }
331 }
331
332
332 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
333 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
334 self.place(conversation_id, folder_id, None);
335 }
336
337 pub fn place(&mut self, conversation_id: &str, folder_id: Option<&str>, index: Option<usize>) {
333 for folder in &mut self.folders {
338 for folder in &mut self.folders {
334 folder.conversation_ids.retain(|id| id != conversation_id);
339 folder.conversation_ids.retain(|id| id != conversation_id);
335 }
340 }
336 if let Some(folder) =
341 if let Some(folder) =
337 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
342 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
338 {
343 {
339 folder.conversation_ids.push(conversation_id.to_owned());
344 let position = index.map_or(folder.conversation_ids.len(), |index| {
345 index.min(folder.conversation_ids.len())
346 });
347 folder
348 .conversation_ids
349 .insert(position, conversation_id.to_owned());
340 }
350 }
341 }
351 }
342
352
353 pub fn slot_of(&self, folder_id: &str, conversation_id: &str) -> Option<usize> {
354 self.folders
355 .iter()
356 .find(|folder| folder.id == folder_id)?
357 .conversation_ids
358 .iter()
359 .position(|id| id == conversation_id)
360 }
361
343 pub fn move_targets(&self) -> Vec<(String, String)> {
362 pub fn move_targets(&self) -> Vec<(String, String)> {
344 let favorites = self.favorites().map(|folder| {
363 let favorites = self.favorites().map(|folder| {
345 let name = folder.name.trim();
364 let name = folder.name.trim();
@@ -539,21 +558,24 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
539 store.pinned_channel_ids().unwrap_or_default()
558 store.pinned_channel_ids().unwrap_or_default()
540}
559}
541
560
542pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
561pub fn cached_avatar(store: &Store, user_id: &str) -> Option<AvatarState> {
543 let record = store.avatar(user_id).ok().flatten()?;
562 let record = store.avatar(user_id).ok().flatten()?;
544 Some(record.bytes.map(|bytes| {
563 Some(match record.bytes {
545 if is_bot_id(user_id) {
564 Some(bytes) => avatar_state_from(&record.content_type, bytes, is_bot_id(user_id)),
546 Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
565 None => AvatarState::Missing,
547 } else {
566 })
548 avatar_image_from(&record.content_type, bytes)
549 }
550 }))
551}
567}
552
568
553pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
569pub fn avatar_state_from(content_type: &str, bytes: Vec<u8>, is_bot: bool) -> AvatarState {
554 match crate::avatar_image::circular_png(&bytes) {
570 if image_format(content_type) == ImageFormat::Svg {
555 Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
571 if is_bot {
556 None => Arc::new(Image::from_bytes(image_format(content_type), bytes)),
572 return AvatarState::Icon(Arc::new(Image::from_bytes(ImageFormat::Svg, bytes)));
573 }
574 return AvatarState::Missing;
575 }
576 match AvatarPhoto::from_bytes(bytes) {
577 Some(photo) => AvatarState::Ready(Arc::new(photo)),
578 None => AvatarState::Missing,
557 }
579 }
558}
580}
559
581
@@ -643,13 +665,22 @@ pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
643 run(async move { engine.watch_presence(&user_ids).await })
665 run(async move { engine.watch_presence(&user_ids).await })
644}
666}
645
667
646pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
668pub fn move_to_folder(
669 engine: &Arc<Engine>,
670 conversation_id: &str,
671 folder_id: &str,
672 index: Option<usize>,
673) -> Done {
647 let (engine, conversation_id, folder_id) = (
674 let (engine, conversation_id, folder_id) = (
648 engine.clone(),
675 engine.clone(),
649 conversation_id.to_owned(),
676 conversation_id.to_owned(),
650 folder_id.to_owned(),
677 folder_id.to_owned(),
651 );
678 );
652 run(async move { engine.move_to_folder(&conversation_id, &folder_id).await })
679 run(async move {
680 engine
681 .move_to_folder(&conversation_id, &folder_id, index)
682 .await
683 })
653}
684}
654
685
655pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
686pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
@@ -715,6 +746,29 @@ mod tests {
715 }
746 }
716 }
747 }
717
748
749 #[test]
750 fn place_puts_a_chat_at_the_slot_inside_and_across_folders() {
751 let mut directory = Directory {
752 folders: vec![
753 folder("fav", FolderKind::Favorites, &["a", "b", "c"]),
754 folder("work", FolderKind::UserCreated, &["d"]),
755 ],
756 ..Default::default()
757 };
758 directory.place("a", Some("fav"), Some(2));
759 assert_eq!(directory.folders[0].conversation_ids, vec!["b", "c", "a"]);
760 directory.place("d", Some("fav"), Some(0));
761 assert_eq!(
762 directory.folders[0].conversation_ids,
763 vec!["d", "b", "c", "a"]
764 );
765 assert!(directory.folders[1].conversation_ids.is_empty());
766 directory.place("b", Some("work"), Some(9));
767 assert_eq!(directory.folders[1].conversation_ids, vec!["b"]);
768 assert_eq!(directory.slot_of("fav", "c"), Some(1));
769 assert_eq!(directory.slot_of("work", "c"), None);
770 }
771
718 #[test]
772 #[test]
719 fn assign_moves_a_chat_between_folders() {
773 fn assign_moves_a_chat_between_folders() {
720 let mut directory = Directory {
774 let mut directory = Directory {
@@ -821,7 +875,7 @@ mod tests {
821 #[test]
875 #[test]
822 fn missing_avatars_skip_known_and_duplicates() {
876 fn missing_avatars_skip_known_and_duplicates() {
823 let mut directory = Directory::default();
877 let mut directory = Directory::default();
824 directory.set_avatar("known", None);
878 directory.set_avatar("known", AvatarState::Missing);
825 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
879 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
826 assert_eq!(wanted, vec!["x", "y"]);
880 assert_eq!(wanted, vec!["x", "y"]);
827 directory.mark_avatars_pending(&wanted);
881 directory.mark_avatars_pending(&wanted);
crates/app-state/src/demo.rs +31 −10
@@ -1,10 +1,10 @@
1 1 use std::collections::HashMap;
2 2 use std::path::PathBuf;
3 use std::sync::{Arc, OnceLock};
3 use std::sync::OnceLock;
4 4 use std::time::Instant;
5 5
6 6 use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7 use gpui_kit::{App, Entity, Image};
7 use gpui_kit::{App, Entity};
8 8 use store::{
9 9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
@@ -20,7 +20,7 @@ use teams_core::{
20 20 use crate::activity::{Actor, Entry, Kind};
21 21 use crate::app_state::{AppState, Selection};
22 22 use crate::card_actions::{CardAnswer, CardTask};
23 use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
23 use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
24 24 use crate::demo_gifs;
25 25 use crate::message_actions::ForwardSource;
26 26
@@ -31,6 +31,7 @@ const DEMO_USER_NAME: &str = "Dana Demo";
31 31 const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
32 32 const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
33 33 const PHOTO_SIZE: usize = 48;
34 const DEMO_PHOTO_SIDE: usize = 240;
34 35 const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
35 36 const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
36 37 const STAGING_SIZE: (usize, usize) = (960, 540);
@@ -896,8 +897,8 @@ fn seed_agent_access(store: &Store) {
896 897 });
897 898 }
898 899
899 fn photo(palette: &Palette) -> Arc<Image> {
900 crate::data::avatar_image_from("image/png", encode_png(palette))
900 fn photo(palette: &Palette) -> AvatarState {
901 crate::data::avatar_state_from("image/png", encode_png(palette), false)
901 902 }
902 903
903 904 pub fn seed_directory(state: &mut AppState) {
@@ -962,9 +963,9 @@ pub fn seed_directory(state: &mut AppState) {
962 963 directory
963 964 .unread_counts
964 965 .insert("demo-chat-allhands".to_owned(), 120);
965 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
966 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
967 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
966 directory.set_avatar(MARA_ID, photo(&MARA));
967 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
968 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
968 969 for (user_id, kind) in [
969 970 (MARA_ID, PresenceKind::Available),
970 971 (JONAS_ID, PresenceKind::Busy),
@@ -1097,6 +1098,25 @@ fn message(
1097 1098 }
1098 1099 }
1099 1100
1101 pub fn roster_record(
1102 conversation: &str,
1103 id: &str,
1104 time: DateTime<Utc>,
1105 event: &teams_core::roster_event::RosterEvent,
1106 ) -> MessageRecord {
1107 MessageRecord {
1108 conversation_id: conversation.to_owned(),
1109 message_id: id.to_owned(),
1110 created_at: time,
1111 links_json: "[]".to_owned(),
1112 attachments_json: "[]".to_owned(),
1113 reactions_json: "[]".to_owned(),
1114 mentions_json: "[]".to_owned(),
1115 call_event_json: Some(event.to_json()),
1116 ..MessageRecord::default()
1117 }
1118 }
1119
1100 1120 fn call_record(
1101 1121 conversation: &str,
1102 1122 id: &str,
@@ -2192,8 +2212,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2192 2212 }
2193 2213
2194 2214 fn encode_png(palette: &Palette) -> Vec<u8> {
2195 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
2196 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
2215 let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2216 encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {
2217 let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);
2197 2218 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2198 2219 palette.skin
2199 2220 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
@@ -1,10 +1,10 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::path::PathBuf;
2use std::path::PathBuf;
3use std::sync::{Arc, OnceLock};
3use std::sync::OnceLock;
4use std::time::Instant;
4use std::time::Instant;
5
5
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7use gpui_kit::{App, Entity, Image};
7use gpui_kit::{App, Entity};
8use store::{
8use store::{
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
@@ -20,7 +20,7 @@ use teams_core::{
20use crate::activity::{Actor, Entry, Kind};
20use crate::activity::{Actor, Entry, Kind};
21use crate::app_state::{AppState, Selection};
21use crate::app_state::{AppState, Selection};
22use crate::card_actions::{CardAnswer, CardTask};
22use crate::card_actions::{CardAnswer, CardTask};
23use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
23use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
24use crate::demo_gifs;
24use crate::demo_gifs;
25use crate::message_actions::ForwardSource;
25use crate::message_actions::ForwardSource;
26
26
@@ -31,6 +31,7 @@ const DEMO_USER_NAME: &str = "Dana Demo";
31const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
31const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
32const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
32const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
33const PHOTO_SIZE: usize = 48;
33const PHOTO_SIZE: usize = 48;
34const DEMO_PHOTO_SIDE: usize = 240;
34const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
35const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
35const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
36const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
36const STAGING_SIZE: (usize, usize) = (960, 540);
37const STAGING_SIZE: (usize, usize) = (960, 540);
@@ -896,8 +897,8 @@ fn seed_agent_access(store: &Store) {
896 });
897 });
897}
898}
898
899
899fn photo(palette: &Palette) -> Arc<Image> {
900fn photo(palette: &Palette) -> AvatarState {
900 crate::data::avatar_image_from("image/png", encode_png(palette))
901 crate::data::avatar_state_from("image/png", encode_png(palette), false)
901}
902}
902
903
903pub fn seed_directory(state: &mut AppState) {
904pub fn seed_directory(state: &mut AppState) {
@@ -962,9 +963,9 @@ pub fn seed_directory(state: &mut AppState) {
962 directory
963 directory
963 .unread_counts
964 .unread_counts
964 .insert("demo-chat-allhands".to_owned(), 120);
965 .insert("demo-chat-allhands".to_owned(), 120);
965 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
966 directory.set_avatar(MARA_ID, photo(&MARA));
966 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
967 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
967 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
968 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
968 for (user_id, kind) in [
969 for (user_id, kind) in [
969 (MARA_ID, PresenceKind::Available),
970 (MARA_ID, PresenceKind::Available),
970 (JONAS_ID, PresenceKind::Busy),
971 (JONAS_ID, PresenceKind::Busy),
@@ -1097,6 +1098,25 @@ fn message(
1097 }
1098 }
1098}
1099}
1099
1100
1101pub fn roster_record(
1102 conversation: &str,
1103 id: &str,
1104 time: DateTime<Utc>,
1105 event: &teams_core::roster_event::RosterEvent,
1106) -> MessageRecord {
1107 MessageRecord {
1108 conversation_id: conversation.to_owned(),
1109 message_id: id.to_owned(),
1110 created_at: time,
1111 links_json: "[]".to_owned(),
1112 attachments_json: "[]".to_owned(),
1113 reactions_json: "[]".to_owned(),
1114 mentions_json: "[]".to_owned(),
1115 call_event_json: Some(event.to_json()),
1116 ..MessageRecord::default()
1117 }
1118}
1119
1100fn call_record(
1120fn call_record(
1101 conversation: &str,
1121 conversation: &str,
1102 id: &str,
1122 id: &str,
@@ -2192,8 +2212,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2192}
2212}
2193
2213
2194fn encode_png(palette: &Palette) -> Vec<u8> {
2214fn encode_png(palette: &Palette) -> Vec<u8> {
2195 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
2215 let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2196 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
2216 encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {
2217 let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);
2197 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2218 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2198 palette.skin
2219 palette.skin
2199 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
2220 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
crates/app-state/src/lib.rs +2 −1
@@ -31,6 +31,7 @@ pub mod people;
31 31 pub mod profile_model;
32 32 pub mod profile_state;
33 33 pub mod reaction_model;
34 pub mod restorable_deletes;
34 35 pub mod rows;
35 36 pub mod scheduled;
36 37 pub mod scheduled_rows;
@@ -48,5 +49,5 @@ pub use app_base::{
48 49 APP_NAME, appearance, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
49 50 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
50 51 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,
52 single_instance, stickers, theme, translation, updater, user_activity, zoom,
52 53 };
@@ -31,6 +31,7 @@ pub mod people;
31pub mod profile_model;
31pub mod profile_model;
32pub mod profile_state;
32pub mod profile_state;
33pub mod reaction_model;
33pub mod reaction_model;
34pub mod restorable_deletes;
34pub mod rows;
35pub mod rows;
35pub mod scheduled;
36pub mod scheduled;
36pub mod scheduled_rows;
37pub mod scheduled_rows;
@@ -48,5 +49,5 @@ pub use app_base::{
48 APP_NAME, appearance, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
49 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,
50 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,
51 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,
52 single_instance, stickers, theme, translation, updater, user_activity, zoom,
52};
53};
crates/app-state/src/restorable_deletes.rs added +53 −0
@@ -0,0 +1,53 @@
1 use std::collections::HashSet;
2
3 pub const DELETED_TOMBSTONE: &str = "This message has been deleted.";
4 pub const UNDO_DELETE_LABEL: &str = "Undo";
5 pub const RESTORE_FAILED_NOTICE: &str = "Message restore failed. Please try again";
6
7 #[derive(Debug, Default, Clone)]
8 pub struct RestorableDeletes {
9 messages: HashSet<(String, String)>,
10 }
11
12 impl RestorableDeletes {
13 pub fn remember(&mut self, conversation_id: &str, message_id: &str) {
14 self.messages
15 .insert((conversation_id.to_owned(), message_id.to_owned()));
16 }
17
18 pub fn forget(&mut self, conversation_id: &str, message_id: &str) -> bool {
19 self.messages
20 .remove(&(conversation_id.to_owned(), message_id.to_owned()))
21 }
22
23 pub fn can_undo(
24 &self,
25 conversation_id: &str,
26 message_id: &str,
27 own: bool,
28 deleted: bool,
29 ) -> bool {
30 own && deleted
31 && self
32 .messages
33 .contains(&(conversation_id.to_owned(), message_id.to_owned()))
34 }
35 }
36
37 #[cfg(test)]
38 mod tests {
39 use super::*;
40
41 #[test]
42 fn only_own_messages_deleted_in_this_session_can_be_undone() {
43 let mut deletes = RestorableDeletes::default();
44 deletes.remember("19:a", "m1");
45 assert!(deletes.can_undo("19:a", "m1", true, true));
46 assert!(!deletes.can_undo("19:a", "m1", false, true));
47 assert!(!deletes.can_undo("19:a", "m1", true, false));
48 assert!(!deletes.can_undo("19:b", "m1", true, true));
49 assert!(deletes.forget("19:a", "m1"));
50 assert!(!deletes.can_undo("19:a", "m1", true, true));
51 assert!(!deletes.forget("19:a", "m1"));
52 }
53 }
@@ -0,0 +1,53 @@
1use std::collections::HashSet;
2
3pub const DELETED_TOMBSTONE: &str = "This message has been deleted.";
4pub const UNDO_DELETE_LABEL: &str = "Undo";
5pub const RESTORE_FAILED_NOTICE: &str = "Message restore failed. Please try again";
6
7#[derive(Debug, Default, Clone)]
8pub struct RestorableDeletes {
9 messages: HashSet<(String, String)>,
10}
11
12impl RestorableDeletes {
13 pub fn remember(&mut self, conversation_id: &str, message_id: &str) {
14 self.messages
15 .insert((conversation_id.to_owned(), message_id.to_owned()));
16 }
17
18 pub fn forget(&mut self, conversation_id: &str, message_id: &str) -> bool {
19 self.messages
20 .remove(&(conversation_id.to_owned(), message_id.to_owned()))
21 }
22
23 pub fn can_undo(
24 &self,
25 conversation_id: &str,
26 message_id: &str,
27 own: bool,
28 deleted: bool,
29 ) -> bool {
30 own && deleted
31 && self
32 .messages
33 .contains(&(conversation_id.to_owned(), message_id.to_owned()))
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40
41 #[test]
42 fn only_own_messages_deleted_in_this_session_can_be_undone() {
43 let mut deletes = RestorableDeletes::default();
44 deletes.remember("19:a", "m1");
45 assert!(deletes.can_undo("19:a", "m1", true, true));
46 assert!(!deletes.can_undo("19:a", "m1", false, true));
47 assert!(!deletes.can_undo("19:a", "m1", true, false));
48 assert!(!deletes.can_undo("19:b", "m1", true, true));
49 assert!(deletes.forget("19:a", "m1"));
50 assert!(!deletes.can_undo("19:a", "m1", true, true));
51 assert!(!deletes.forget("19:a", "m1"));
52 }
53}
crates/app-state/src/rows.rs +90 −19
@@ -5,6 +5,7 @@ use std::sync::Arc;
5 5 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 6 use gpui_kit::Image;
7 7 use store::MessageRecord;
8 use teams_core::roster_event::{RosterEvent, roster_event};
8 9 use teams_core::{
9 10 JumboEmoji, jumbo_emoji,
10 11 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
@@ -18,7 +19,7 @@ pub use crate::call_rows::{
18 19 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
19 20 RecordingCard,
20 21 };
21 use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card};
22 use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card, roster_card};
22 23 use crate::card_state::CardOverride;
23 24 use crate::format;
24 25 use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
@@ -602,14 +603,95 @@ fn call_row(
602 603 .and_then(|user_id| context.names.get(user_id).cloned())
603 604 })
604 605 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
606 let card = call_card(
607 CallSource {
608 event,
609 message_id: &record.message_id,
610 created_at: record.created_at,
611 time: &time,
612 },
613 &names,
614 &CallClock {
615 offset: context.offset,
616 today: context.today,
617 meeting: &context.meeting,
618 },
619 timeline,
620 );
621 event_row(
622 record,
623 context,
624 EventAuthor {
625 sender_id: event.initiator_id.clone(),
626 name: author,
627 own: event.initiated_by(my_user_id),
628 },
629 card,
630 time,
631 )
632 }
633
634 fn roster_row(record: &MessageRecord, event: &RosterEvent, context: &RowContext) -> MessageRow {
635 let my_user_id = context.my_user_id.as_deref();
636 let names = CallNames {
637 my_user_id,
638 names: &context.names,
639 };
640 let card = roster_card(
641 event,
642 record.created_at,
643 &names,
644 &CallClock {
645 offset: context.offset,
646 today: context.today,
647 meeting: &context.meeting,
648 },
649 );
650 let author = event
651 .initiator_name
652 .clone()
653 .or_else(|| {
654 event
655 .initiator_id
656 .as_ref()
657 .and_then(|user_id| context.names.get(user_id).cloned())
658 })
659 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
660 let own = my_user_id.is_some() && event.initiator_id.as_deref() == my_user_id;
661 event_row(
662 record,
663 context,
664 EventAuthor {
665 sender_id: event.initiator_id.clone(),
666 name: author,
667 own,
668 },
669 card,
670 clock_label(record.created_at, context.offset),
671 )
672 }
673
674 struct EventAuthor {
675 sender_id: Option<String>,
676 name: String,
677 own: bool,
678 }
679
680 fn event_row(
681 record: &MessageRecord,
682 context: &RowContext,
683 author: EventAuthor,
684 card: CallCard,
685 time: String,
686 ) -> MessageRow {
605 687 MessageRow {
606 688 key: record.message_id.clone(),
607 689 conversation_id: record.conversation_id.clone(),
608 sender_id: event.initiator_id.clone(),
690 sender_id: author.sender_id,
609 691 application_id: None,
610 692 created_at: record.created_at,
611 693 series: Series::default(),
612 author,
694 author: author.name,
613 695 day_header: Some(format::day_label(
614 696 record
615 697 .created_at
@@ -633,24 +715,10 @@ fn call_row(
633 715 reply_root: None,
634 716 delivery: Delivery::Delivered,
635 717 receipt: Receipt::Hidden,
636 own: event.initiated_by(my_user_id),
718 own: author.own,
637 719 forwarded: false,
638 720 translation: None,
639 call: Some(call_card(
640 CallSource {
641 event,
642 message_id: &record.message_id,
643 created_at: record.created_at,
644 time: &time,
645 },
646 &names,
647 &CallClock {
648 offset: context.offset,
649 today: context.today,
650 meeting: &context.meeting,
651 },
652 timeline,
653 )),
721 call: Some(card),
654 722 time,
655 723 }
656 724 }
@@ -721,6 +789,9 @@ fn message_row_with(
721 789 let events = [Some(event.clone())];
722 790 return call_row(record, &event, context, &CallTimeline::new(&events));
723 791 }
792 if let Some(event) = roster_event(record) {
793 return roster_row(record, &event, context);
794 }
724 795 let local = record.created_at.with_timezone(&context.offset);
725 796 let images = images(record);
726 797 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
@@ -5,6 +5,7 @@ use std::sync::Arc;
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::MessageRecord;
7use store::MessageRecord;
8use teams_core::roster_event::{RosterEvent, roster_event};
8use teams_core::{
9use teams_core::{
9 JumboEmoji, jumbo_emoji,
10 JumboEmoji, jumbo_emoji,
10 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
11 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
@@ -18,7 +19,7 @@ pub use crate::call_rows::{
18 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
19 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
19 RecordingCard,
20 RecordingCard,
20};
21};
21use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card};
22use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card, roster_card};
22use crate::card_state::CardOverride;
23use crate::card_state::CardOverride;
23use crate::format;
24use crate::format;
24use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
25use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
@@ -602,14 +603,95 @@ fn call_row(
602 .and_then(|user_id| context.names.get(user_id).cloned())
603 .and_then(|user_id| context.names.get(user_id).cloned())
603 })
604 })
604 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
605 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
606 let card = call_card(
607 CallSource {
608 event,
609 message_id: &record.message_id,
610 created_at: record.created_at,
611 time: &time,
612 },
613 &names,
614 &CallClock {
615 offset: context.offset,
616 today: context.today,
617 meeting: &context.meeting,
618 },
619 timeline,
620 );
621 event_row(
622 record,
623 context,
624 EventAuthor {
625 sender_id: event.initiator_id.clone(),
626 name: author,
627 own: event.initiated_by(my_user_id),
628 },
629 card,
630 time,
631 )
632}
633
634fn roster_row(record: &MessageRecord, event: &RosterEvent, context: &RowContext) -> MessageRow {
635 let my_user_id = context.my_user_id.as_deref();
636 let names = CallNames {
637 my_user_id,
638 names: &context.names,
639 };
640 let card = roster_card(
641 event,
642 record.created_at,
643 &names,
644 &CallClock {
645 offset: context.offset,
646 today: context.today,
647 meeting: &context.meeting,
648 },
649 );
650 let author = event
651 .initiator_name
652 .clone()
653 .or_else(|| {
654 event
655 .initiator_id
656 .as_ref()
657 .and_then(|user_id| context.names.get(user_id).cloned())
658 })
659 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
660 let own = my_user_id.is_some() && event.initiator_id.as_deref() == my_user_id;
661 event_row(
662 record,
663 context,
664 EventAuthor {
665 sender_id: event.initiator_id.clone(),
666 name: author,
667 own,
668 },
669 card,
670 clock_label(record.created_at, context.offset),
671 )
672}
673
674struct EventAuthor {
675 sender_id: Option<String>,
676 name: String,
677 own: bool,
678}
679
680fn event_row(
681 record: &MessageRecord,
682 context: &RowContext,
683 author: EventAuthor,
684 card: CallCard,
685 time: String,
686) -> MessageRow {
605 MessageRow {
687 MessageRow {
606 key: record.message_id.clone(),
688 key: record.message_id.clone(),
607 conversation_id: record.conversation_id.clone(),
689 conversation_id: record.conversation_id.clone(),
608 sender_id: event.initiator_id.clone(),
690 sender_id: author.sender_id,
609 application_id: None,
691 application_id: None,
610 created_at: record.created_at,
692 created_at: record.created_at,
611 series: Series::default(),
693 series: Series::default(),
612 author,
694 author: author.name,
613 day_header: Some(format::day_label(
695 day_header: Some(format::day_label(
614 record
696 record
615 .created_at
697 .created_at
@@ -633,24 +715,10 @@ fn call_row(
633 reply_root: None,
715 reply_root: None,
634 delivery: Delivery::Delivered,
716 delivery: Delivery::Delivered,
635 receipt: Receipt::Hidden,
717 receipt: Receipt::Hidden,
636 own: event.initiated_by(my_user_id),
718 own: author.own,
637 forwarded: false,
719 forwarded: false,
638 translation: None,
720 translation: None,
639 call: Some(call_card(
721 call: Some(card),
640 CallSource {
641 event,
642 message_id: &record.message_id,
643 created_at: record.created_at,
644 time: &time,
645 },
646 &names,
647 &CallClock {
648 offset: context.offset,
649 today: context.today,
650 meeting: &context.meeting,
651 },
652 timeline,
653 )),
654 time,
722 time,
655 }
723 }
656}
724}
@@ -721,6 +789,9 @@ fn message_row_with(
721 let events = [Some(event.clone())];
789 let events = [Some(event.clone())];
722 return call_row(record, &event, context, &CallTimeline::new(&events));
790 return call_row(record, &event, context, &CallTimeline::new(&events));
723 }
791 }
792 if let Some(event) = roster_event(record) {
793 return roster_row(record, &event, context);
794 }
724 let local = record.created_at.with_timezone(&context.offset);
795 let local = record.created_at.with_timezone(&context.offset);
725 let images = images(record);
796 let images = images(record);
726 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
797 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
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/call/overlay.rs +173 −26
@@ -7,12 +7,18 @@ use gpui_kit::*;
7 7 use super::model::format_elapsed;
8 8 use super::overlay_layout::{
9 9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
10 border_visibility, format_position, mini_rect, mini_wanted, mini_work_area, parse_position,
10 border_visibility, format_position, mini_rect, mini_work_area, parse_position,
11 };
12 use super::share_overlay::{
13 GALLERY_POSITION_KEY, GalleryLayout, LocalShare, Monitor, Surface, excluded_from_capture,
14 gallery_available_height, gallery_candidates, gallery_layout, gallery_rect,
15 minimize_on_share_start, overlay_plan,
11 16 };
12 17 use crate::app_state::AppState;
13 18 use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14 19 use crate::views::call_mini_window::MiniWindowView;
15 20 use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
21 use crate::views::call_share_gallery::ShareGalleryView;
16 22 use crate::views::share_bar::{ShareBarView, ShareBorderView};
17 23
18 24 const TICK: Duration = Duration::from_millis(100);
@@ -24,6 +30,7 @@ const BORDER_SIDES: usize = 4;
24 30 enum Role {
25 31 Bar,
26 32 Mini,
33 Gallery,
27 34 Border(usize),
28 35 }
29 36
@@ -76,6 +83,7 @@ struct ShareSession {
76 83 started: Instant,
77 84 source: Option<ShareSource>,
78 85 geometry: Option<ShareGeometry>,
86 minimize_checked: bool,
79 87 }
80 88
81 89 pub struct CallWindows {
@@ -95,6 +103,12 @@ pub struct CallWindows {
95 103 shown_second: u64,
96 104 mini_saved: Option<(i32, i32)>,
97 105 mini_seen: Option<(i32, i32)>,
106 gallery_saved: Option<(i32, i32)>,
107 gallery_seen: Option<(i32, i32)>,
108 gallery_layout: GalleryLayout,
109 speaker_only: bool,
110 main_excluded: bool,
111 minimized_for_share: bool,
98 112 ticks: u32,
99 113 }
100 114
@@ -125,12 +139,12 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
125 139 focus: false,
126 140 show: true,
127 141 kind: WindowKind::PopUp,
128 is_movable: role == Role::Mini,
142 is_movable: matches!(role, Role::Mini | Role::Gallery),
129 143 is_resizable: false,
130 144 is_minimizable: false,
131 145 window_background: match role {
132 146 Role::Border(_) => WindowBackgroundAppearance::Opaque,
133 Role::Bar | Role::Mini => WindowBackgroundAppearance::Transparent,
147 Role::Bar | Role::Mini | Role::Gallery => WindowBackgroundAppearance::Transparent,
134 148 },
135 149 ..Default::default()
136 150 }
@@ -138,13 +152,16 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
138 152
139 153 impl CallWindows {
140 154 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
141 let mini_saved = app
142 .read(cx)
143 .store
144 .meta(MINI_POSITION_KEY)
145 .ok()
146 .flatten()
147 .and_then(|text| parse_position(&text));
155 let saved_position = |key: &str, cx: &App| {
156 app.read(cx)
157 .store
158 .meta(key)
159 .ok()
160 .flatten()
161 .and_then(|text| parse_position(&text))
162 };
163 let mini_saved = saved_position(MINI_POSITION_KEY, cx);
164 let gallery_saved = saved_position(GALLERY_POSITION_KEY, cx);
148 165 let windows = CallWindows {
149 166 app,
150 167 main_window: window.window_handle(),
@@ -162,6 +179,12 @@ impl CallWindows {
162 179 shown_second: 0,
163 180 mini_saved,
164 181 mini_seen: None,
182 gallery_saved,
183 gallery_seen: None,
184 gallery_layout: gallery_layout(0, true, f32::MAX),
185 speaker_only: false,
186 main_excluded: false,
187 minimized_for_share: false,
165 188 ticks: 0,
166 189 };
167 190 cx.spawn(async move |this, cx| {
@@ -190,6 +213,19 @@ impl CallWindows {
190 213 self.bar_collapsed
191 214 }
192 215
216 pub fn gallery_layout(&self) -> GalleryLayout {
217 self.gallery_layout
218 }
219
220 pub fn sharing(&self) -> bool {
221 self.share.is_some()
222 }
223
224 pub fn toggle_speaker_only(&mut self, cx: &mut Context<Self>) {
225 self.speaker_only = !self.speaker_only;
226 cx.notify();
227 }
228
193 229 pub fn share_text(&self) -> String {
194 230 let Some(session) = &self.share else {
195 231 return String::new();
@@ -233,6 +269,7 @@ impl CallWindows {
233 269 && self.share.is_none()
234 270 && self.windows.is_empty()
235 271 && self.opening.is_empty()
272 && !self.main_excluded
236 273 }
237 274
238 275 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
@@ -243,10 +280,12 @@ impl CallWindows {
243 280 let slow = self.ticks % SLOW_TICK_EVERY == 0;
244 281 self.refresh_main_window();
245 282 self.sync_share(slow, cx);
283 self.sync_capture_exclusion();
246 284 self.sync_pop_out(cx);
247 self.sync_mini(cx);
285 self.sync_monitor(cx);
248 286 if slow {
249 self.track_mini_position(cx);
287 self.track_position(Role::Mini, cx);
288 self.track_position(Role::Gallery, cx);
250 289 }
251 290 TICK
252 291 }
@@ -255,7 +294,11 @@ impl CallWindows {
255 294 let Some(native) = self.main_native else {
256 295 return;
257 296 };
258 self.minimized = platform::window_minimized(native);
297 let minimized = platform::window_minimized(native);
298 if self.minimized && !minimized {
299 self.minimized_for_share = false;
300 }
301 self.minimized = minimized;
259 302 if !self.minimized {
260 303 self.work_area = platform::work_area(native).or(self.work_area);
261 304 }
@@ -285,6 +328,7 @@ impl CallWindows {
285 328 started: Instant::now(),
286 329 source: None,
287 330 geometry: None,
331 minimize_checked: false,
288 332 });
289 333 refresh_geometry = true;
290 334 }
@@ -305,6 +349,10 @@ impl CallWindows {
305 349 }
306 350 let geometry = session.geometry;
307 351 let elapsed_seconds = session.started.elapsed().as_secs();
352 let check_minimize = !std::mem::replace(&mut session.minimize_checked, true);
353 if check_minimize {
354 self.minimize_for_share(geometry.map(|geometry| geometry.target), cx);
355 }
308 356 let Some(work) = geometry
309 357 .map(|geometry| geometry.work)
310 358 .or(self.work_area)
@@ -347,10 +395,55 @@ impl CallWindows {
347 395 }
348 396 }
349 397
398 fn local_share_mode(&self) -> LocalShare {
399 let kind = self
400 .share
401 .as_ref()
402 .and_then(|session| session.source.as_ref())
403 .map(|source| source.kind);
404 LocalShare::of(kind, self.share.is_some())
405 }
406
407 fn minimize_for_share(&mut self, shared: Option<ScreenRect>, cx: &mut Context<Self>) {
408 let Some(native) = self.main_native.filter(|_| !self.minimized) else {
409 return;
410 };
411 if !minimize_on_share_start(
412 self.local_share_mode(),
413 platform::window_rect(native),
414 shared,
415 ) {
416 return;
417 }
418 self.minimized_for_share = true;
419 self.main_window
420 .update(cx, |_, window, _| window.minimize_window())
421 .ok();
422 }
423
424 fn sync_capture_exclusion(&mut self) {
425 let Some(native) = self.main_native else {
426 return;
427 };
428 let wanted = excluded_from_capture(Surface::Main, self.local_share_mode());
429 if wanted == self.main_excluded {
430 return;
431 }
432 self.main_excluded = wanted;
433 if wanted {
434 platform::exclude_from_capture(native);
435 } else {
436 platform::include_in_capture(native);
437 }
438 }
439
350 440 fn end_share(&mut self, cx: &mut Context<Self>) {
351 441 if self.share.take().is_none() {
352 442 return;
353 443 }
444 if std::mem::take(&mut self.minimized_for_share) && self.minimized {
445 self.return_to_call(cx);
446 }
354 447 self.bar_collapsed = false;
355 448 self.close(Role::Bar, cx);
356 449 self.close_borders(cx);
@@ -419,40 +512,91 @@ impl CallWindows {
419 512 });
420 513 }
421 514
422 fn sync_mini(&mut self, cx: &mut Context<Self>) {
515 fn sync_monitor(&mut self, cx: &mut Context<Self>) {
423 516 let in_call = self.app.read(cx).call.is_some();
517 let plan = overlay_plan(
518 in_call,
519 self.local_share_mode(),
520 self.minimized,
521 self.speaker_only,
522 );
424 523 let work = self.work_area.or_else(|| display_work_area(cx));
425 match work.filter(|_| mini_wanted(in_call, self.minimized)) {
426 Some(main_work) => {
524 match (plan.monitor, work) {
525 (Monitor::Mini, Some(main_work)) => {
526 self.close(Role::Gallery, cx);
427 527 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
428 528 let rect = mini_rect(work, self.mini_saved);
429 529 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
430 530 }
431 None => self.close(Role::Mini, cx),
531 (Monitor::Gallery, Some(main_work)) => {
532 self.close(Role::Mini, cx);
533 self.place_gallery(main_work, cx);
534 }
535 _ => {
536 self.close(Role::Mini, cx);
537 self.close(Role::Gallery, cx);
538 }
432 539 }
433 540 }
434 541
435 fn track_mini_position(&mut self, cx: &mut Context<Self>) {
436 let Some(native) = self
542 fn place_gallery(&mut self, main_work: WorkArea, cx: &mut Context<Self>) {
543 let work = mini_work_area(main_work, self.gallery_saved, platform::work_area_at);
544 let (others, self_tile) = self.app.read(cx).call.as_ref().map_or((0, true), |call| {
545 (
546 gallery_candidates(&call.model).len(),
547 !call.model.view.hide_me,
548 )
549 });
550 let layout = gallery_layout(others, self_tile, gallery_available_height(work));
551 if layout != self.gallery_layout {
552 self.gallery_layout = layout;
553 cx.notify();
554 }
555 let origin = self
437 556 .windows
438 .get(&Role::Mini)
557 .get(&Role::Gallery)
439 558 .and_then(|placed| placed.native)
440 else {
559 .and_then(platform::window_rect)
560 .map(|rect| (rect.left, rect.top))
561 .or(self.gallery_saved);
562 let rect = gallery_rect(work, layout, origin);
563 match self.windows.get_mut(&Role::Gallery) {
564 Some(placed) => {
565 let size = |rect: ScreenRect| (rect.width(), rect.height());
566 if placed.rect.map(size) != Some(size(rect)) {
567 placed.place(rect, cx);
568 }
569 }
570 None => self.open(Role::Gallery, rect, work.scale, cx),
571 }
572 }
573
574 fn track_position(&mut self, role: Role, cx: &mut Context<Self>) {
575 let Some(native) = self.windows.get(&role).and_then(|placed| placed.native) else {
441 576 return;
442 577 };
443 578 let Some(rect) = platform::window_rect(native) else {
444 579 return;
445 580 };
581 let (key, saved, seen) = match role {
582 Role::Mini => (MINI_POSITION_KEY, &mut self.mini_saved, &mut self.mini_seen),
583 Role::Gallery => (
584 GALLERY_POSITION_KEY,
585 &mut self.gallery_saved,
586 &mut self.gallery_seen,
587 ),
588 Role::Bar | Role::Border(_) => return,
589 };
446 590 let position = (rect.left, rect.top);
447 let settled = self.mini_seen == Some(position);
448 self.mini_seen = Some(position);
449 if settled && self.mini_saved != Some(position) {
450 self.mini_saved = Some(position);
591 let settled = *seen == Some(position);
592 *seen = Some(position);
593 if settled && *saved != Some(position) {
594 *saved = Some(position);
451 595 let _ = self
452 596 .app
453 597 .read(cx)
454 598 .store
455 .set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
599 .set_meta(key, &format_position(position.0, position.1));
456 600 }
457 601 }
458 602
@@ -506,6 +650,9 @@ impl CallWindows {
506 650 let view: AnyView = match role {
507 651 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
508 652 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
653 Role::Gallery => cx
654 .new(|cx| ShareGalleryView::new(view_controller, cx))
655 .into(),
509 656 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
510 657 };
511 658 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
@@ -7,12 +7,18 @@ use gpui_kit::*;
7use super::model::format_elapsed;
7use super::model::format_elapsed;
8use super::overlay_layout::{
8use super::overlay_layout::{
9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
10 border_visibility, format_position, mini_rect, mini_wanted, mini_work_area, parse_position,
10 border_visibility, format_position, mini_rect, mini_work_area, parse_position,
11};
12use super::share_overlay::{
13 GALLERY_POSITION_KEY, GalleryLayout, LocalShare, Monitor, Surface, excluded_from_capture,
14 gallery_available_height, gallery_candidates, gallery_layout, gallery_rect,
15 minimize_on_share_start, overlay_plan,
11};
16};
12use crate::app_state::AppState;
17use crate::app_state::AppState;
13use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
18use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14use crate::views::call_mini_window::MiniWindowView;
19use crate::views::call_mini_window::MiniWindowView;
15use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
20use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
21use crate::views::call_share_gallery::ShareGalleryView;
16use crate::views::share_bar::{ShareBarView, ShareBorderView};
22use crate::views::share_bar::{ShareBarView, ShareBorderView};
17
23
18const TICK: Duration = Duration::from_millis(100);
24const TICK: Duration = Duration::from_millis(100);
@@ -24,6 +30,7 @@ const BORDER_SIDES: usize = 4;
24enum Role {
30enum Role {
25 Bar,
31 Bar,
26 Mini,
32 Mini,
33 Gallery,
27 Border(usize),
34 Border(usize),
28}
35}
29
36
@@ -76,6 +83,7 @@ struct ShareSession {
76 started: Instant,
83 started: Instant,
77 source: Option<ShareSource>,
84 source: Option<ShareSource>,
78 geometry: Option<ShareGeometry>,
85 geometry: Option<ShareGeometry>,
86 minimize_checked: bool,
79}
87}
80
88
81pub struct CallWindows {
89pub struct CallWindows {
@@ -95,6 +103,12 @@ pub struct CallWindows {
95 shown_second: u64,
103 shown_second: u64,
96 mini_saved: Option<(i32, i32)>,
104 mini_saved: Option<(i32, i32)>,
97 mini_seen: Option<(i32, i32)>,
105 mini_seen: Option<(i32, i32)>,
106 gallery_saved: Option<(i32, i32)>,
107 gallery_seen: Option<(i32, i32)>,
108 gallery_layout: GalleryLayout,
109 speaker_only: bool,
110 main_excluded: bool,
111 minimized_for_share: bool,
98 ticks: u32,
112 ticks: u32,
99}
113}
100
114
@@ -125,12 +139,12 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
125 focus: false,
139 focus: false,
126 show: true,
140 show: true,
127 kind: WindowKind::PopUp,
141 kind: WindowKind::PopUp,
128 is_movable: role == Role::Mini,
142 is_movable: matches!(role, Role::Mini | Role::Gallery),
129 is_resizable: false,
143 is_resizable: false,
130 is_minimizable: false,
144 is_minimizable: false,
131 window_background: match role {
145 window_background: match role {
132 Role::Border(_) => WindowBackgroundAppearance::Opaque,
146 Role::Border(_) => WindowBackgroundAppearance::Opaque,
133 Role::Bar | Role::Mini => WindowBackgroundAppearance::Transparent,
147 Role::Bar | Role::Mini | Role::Gallery => WindowBackgroundAppearance::Transparent,
134 },
148 },
135 ..Default::default()
149 ..Default::default()
136 }
150 }
@@ -138,13 +152,16 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
138
152
139impl CallWindows {
153impl CallWindows {
140 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
154 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
141 let mini_saved = app
155 let saved_position = |key: &str, cx: &App| {
142 .read(cx)
156 app.read(cx)
143 .store
157 .store
144 .meta(MINI_POSITION_KEY)
158 .meta(key)
145 .ok()
159 .ok()
146 .flatten()
160 .flatten()
147 .and_then(|text| parse_position(&text));
161 .and_then(|text| parse_position(&text))
162 };
163 let mini_saved = saved_position(MINI_POSITION_KEY, cx);
164 let gallery_saved = saved_position(GALLERY_POSITION_KEY, cx);
148 let windows = CallWindows {
165 let windows = CallWindows {
149 app,
166 app,
150 main_window: window.window_handle(),
167 main_window: window.window_handle(),
@@ -162,6 +179,12 @@ impl CallWindows {
162 shown_second: 0,
179 shown_second: 0,
163 mini_saved,
180 mini_saved,
164 mini_seen: None,
181 mini_seen: None,
182 gallery_saved,
183 gallery_seen: None,
184 gallery_layout: gallery_layout(0, true, f32::MAX),
185 speaker_only: false,
186 main_excluded: false,
187 minimized_for_share: false,
165 ticks: 0,
188 ticks: 0,
166 };
189 };
167 cx.spawn(async move |this, cx| {
190 cx.spawn(async move |this, cx| {
@@ -190,6 +213,19 @@ impl CallWindows {
190 self.bar_collapsed
213 self.bar_collapsed
191 }
214 }
192
215
216 pub fn gallery_layout(&self) -> GalleryLayout {
217 self.gallery_layout
218 }
219
220 pub fn sharing(&self) -> bool {
221 self.share.is_some()
222 }
223
224 pub fn toggle_speaker_only(&mut self, cx: &mut Context<Self>) {
225 self.speaker_only = !self.speaker_only;
226 cx.notify();
227 }
228
193 pub fn share_text(&self) -> String {
229 pub fn share_text(&self) -> String {
194 let Some(session) = &self.share else {
230 let Some(session) = &self.share else {
195 return String::new();
231 return String::new();
@@ -233,6 +269,7 @@ impl CallWindows {
233 && self.share.is_none()
269 && self.share.is_none()
234 && self.windows.is_empty()
270 && self.windows.is_empty()
235 && self.opening.is_empty()
271 && self.opening.is_empty()
272 && !self.main_excluded
236 }
273 }
237
274
238 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
275 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
@@ -243,10 +280,12 @@ impl CallWindows {
243 let slow = self.ticks % SLOW_TICK_EVERY == 0;
280 let slow = self.ticks % SLOW_TICK_EVERY == 0;
244 self.refresh_main_window();
281 self.refresh_main_window();
245 self.sync_share(slow, cx);
282 self.sync_share(slow, cx);
283 self.sync_capture_exclusion();
246 self.sync_pop_out(cx);
284 self.sync_pop_out(cx);
247 self.sync_mini(cx);
285 self.sync_monitor(cx);
248 if slow {
286 if slow {
249 self.track_mini_position(cx);
287 self.track_position(Role::Mini, cx);
288 self.track_position(Role::Gallery, cx);
250 }
289 }
251 TICK
290 TICK
252 }
291 }
@@ -255,7 +294,11 @@ impl CallWindows {
255 let Some(native) = self.main_native else {
294 let Some(native) = self.main_native else {
256 return;
295 return;
257 };
296 };
258 self.minimized = platform::window_minimized(native);
297 let minimized = platform::window_minimized(native);
298 if self.minimized && !minimized {
299 self.minimized_for_share = false;
300 }
301 self.minimized = minimized;
259 if !self.minimized {
302 if !self.minimized {
260 self.work_area = platform::work_area(native).or(self.work_area);
303 self.work_area = platform::work_area(native).or(self.work_area);
261 }
304 }
@@ -285,6 +328,7 @@ impl CallWindows {
285 started: Instant::now(),
328 started: Instant::now(),
286 source: None,
329 source: None,
287 geometry: None,
330 geometry: None,
331 minimize_checked: false,
288 });
332 });
289 refresh_geometry = true;
333 refresh_geometry = true;
290 }
334 }
@@ -305,6 +349,10 @@ impl CallWindows {
305 }
349 }
306 let geometry = session.geometry;
350 let geometry = session.geometry;
307 let elapsed_seconds = session.started.elapsed().as_secs();
351 let elapsed_seconds = session.started.elapsed().as_secs();
352 let check_minimize = !std::mem::replace(&mut session.minimize_checked, true);
353 if check_minimize {
354 self.minimize_for_share(geometry.map(|geometry| geometry.target), cx);
355 }
308 let Some(work) = geometry
356 let Some(work) = geometry
309 .map(|geometry| geometry.work)
357 .map(|geometry| geometry.work)
310 .or(self.work_area)
358 .or(self.work_area)
@@ -347,10 +395,55 @@ impl CallWindows {
347 }
395 }
348 }
396 }
349
397
398 fn local_share_mode(&self) -> LocalShare {
399 let kind = self
400 .share
401 .as_ref()
402 .and_then(|session| session.source.as_ref())
403 .map(|source| source.kind);
404 LocalShare::of(kind, self.share.is_some())
405 }
406
407 fn minimize_for_share(&mut self, shared: Option<ScreenRect>, cx: &mut Context<Self>) {
408 let Some(native) = self.main_native.filter(|_| !self.minimized) else {
409 return;
410 };
411 if !minimize_on_share_start(
412 self.local_share_mode(),
413 platform::window_rect(native),
414 shared,
415 ) {
416 return;
417 }
418 self.minimized_for_share = true;
419 self.main_window
420 .update(cx, |_, window, _| window.minimize_window())
421 .ok();
422 }
423
424 fn sync_capture_exclusion(&mut self) {
425 let Some(native) = self.main_native else {
426 return;
427 };
428 let wanted = excluded_from_capture(Surface::Main, self.local_share_mode());
429 if wanted == self.main_excluded {
430 return;
431 }
432 self.main_excluded = wanted;
433 if wanted {
434 platform::exclude_from_capture(native);
435 } else {
436 platform::include_in_capture(native);
437 }
438 }
439
350 fn end_share(&mut self, cx: &mut Context<Self>) {
440 fn end_share(&mut self, cx: &mut Context<Self>) {
351 if self.share.take().is_none() {
441 if self.share.take().is_none() {
352 return;
442 return;
353 }
443 }
444 if std::mem::take(&mut self.minimized_for_share) && self.minimized {
445 self.return_to_call(cx);
446 }
354 self.bar_collapsed = false;
447 self.bar_collapsed = false;
355 self.close(Role::Bar, cx);
448 self.close(Role::Bar, cx);
356 self.close_borders(cx);
449 self.close_borders(cx);
@@ -419,40 +512,91 @@ impl CallWindows {
419 });
512 });
420 }
513 }
421
514
422 fn sync_mini(&mut self, cx: &mut Context<Self>) {
515 fn sync_monitor(&mut self, cx: &mut Context<Self>) {
423 let in_call = self.app.read(cx).call.is_some();
516 let in_call = self.app.read(cx).call.is_some();
517 let plan = overlay_plan(
518 in_call,
519 self.local_share_mode(),
520 self.minimized,
521 self.speaker_only,
522 );
424 let work = self.work_area.or_else(|| display_work_area(cx));
523 let work = self.work_area.or_else(|| display_work_area(cx));
425 match work.filter(|_| mini_wanted(in_call, self.minimized)) {
524 match (plan.monitor, work) {
426 Some(main_work) => {
525 (Monitor::Mini, Some(main_work)) => {
526 self.close(Role::Gallery, cx);
427 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
527 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
428 let rect = mini_rect(work, self.mini_saved);
528 let rect = mini_rect(work, self.mini_saved);
429 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
529 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
430 }
530 }
431 None => self.close(Role::Mini, cx),
531 (Monitor::Gallery, Some(main_work)) => {
532 self.close(Role::Mini, cx);
533 self.place_gallery(main_work, cx);
534 }
535 _ => {
536 self.close(Role::Mini, cx);
537 self.close(Role::Gallery, cx);
538 }
432 }
539 }
433 }
540 }
434
541
435 fn track_mini_position(&mut self, cx: &mut Context<Self>) {
542 fn place_gallery(&mut self, main_work: WorkArea, cx: &mut Context<Self>) {
436 let Some(native) = self
543 let work = mini_work_area(main_work, self.gallery_saved, platform::work_area_at);
544 let (others, self_tile) = self.app.read(cx).call.as_ref().map_or((0, true), |call| {
545 (
546 gallery_candidates(&call.model).len(),
547 !call.model.view.hide_me,
548 )
549 });
550 let layout = gallery_layout(others, self_tile, gallery_available_height(work));
551 if layout != self.gallery_layout {
552 self.gallery_layout = layout;
553 cx.notify();
554 }
555 let origin = self
437 .windows
556 .windows
438 .get(&Role::Mini)
557 .get(&Role::Gallery)
439 .and_then(|placed| placed.native)
558 .and_then(|placed| placed.native)
440 else {
559 .and_then(platform::window_rect)
560 .map(|rect| (rect.left, rect.top))
561 .or(self.gallery_saved);
562 let rect = gallery_rect(work, layout, origin);
563 match self.windows.get_mut(&Role::Gallery) {
564 Some(placed) => {
565 let size = |rect: ScreenRect| (rect.width(), rect.height());
566 if placed.rect.map(size) != Some(size(rect)) {
567 placed.place(rect, cx);
568 }
569 }
570 None => self.open(Role::Gallery, rect, work.scale, cx),
571 }
572 }
573
574 fn track_position(&mut self, role: Role, cx: &mut Context<Self>) {
575 let Some(native) = self.windows.get(&role).and_then(|placed| placed.native) else {
441 return;
576 return;
442 };
577 };
443 let Some(rect) = platform::window_rect(native) else {
578 let Some(rect) = platform::window_rect(native) else {
444 return;
579 return;
445 };
580 };
581 let (key, saved, seen) = match role {
582 Role::Mini => (MINI_POSITION_KEY, &mut self.mini_saved, &mut self.mini_seen),
583 Role::Gallery => (
584 GALLERY_POSITION_KEY,
585 &mut self.gallery_saved,
586 &mut self.gallery_seen,
587 ),
588 Role::Bar | Role::Border(_) => return,
589 };
446 let position = (rect.left, rect.top);
590 let position = (rect.left, rect.top);
447 let settled = self.mini_seen == Some(position);
591 let settled = *seen == Some(position);
448 self.mini_seen = Some(position);
592 *seen = Some(position);
449 if settled && self.mini_saved != Some(position) {
593 if settled && *saved != Some(position) {
450 self.mini_saved = Some(position);
594 *saved = Some(position);
451 let _ = self
595 let _ = self
452 .app
596 .app
453 .read(cx)
597 .read(cx)
454 .store
598 .store
455 .set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
599 .set_meta(key, &format_position(position.0, position.1));
456 }
600 }
457 }
601 }
458
602
@@ -506,6 +650,9 @@ impl CallWindows {
506 let view: AnyView = match role {
650 let view: AnyView = match role {
507 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
651 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
508 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
652 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
653 Role::Gallery => cx
654 .new(|cx| ShareGalleryView::new(view_controller, cx))
655 .into(),
509 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
656 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
510 };
657 };
511 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
658 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
crates/app/src/layout_guard.rs +67 −3
@@ -194,6 +194,7 @@ mod frames {
194 194 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
195 195 };
196 196 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
197 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
197 198
198 199 const GUARDED: &[&str] = &[
199 200 "shell",
@@ -201,6 +202,7 @@ mod frames {
201 202 "shell/title-bar/search",
202 203 "shell/title-bar/own-status",
203 204 "shell/title-bar/own-status/avatar",
205 OWN_AVATAR_DISC,
204 206 "shell/islands",
205 207 "shell/islands/rail",
206 208 "shell/islands/sidebar",
@@ -317,6 +319,7 @@ mod frames {
317 319 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
318 320 const TOLERANCE: f32 = 0.5;
319 321 const KNOWN_VIOLATIONS: &[&str] = &[];
322 const ZOOM_STEP: f32 = 1.25;
320 323
321 324 type Tag = (&'static str, Bounds<Pixels>);
322 325
@@ -732,11 +735,31 @@ mod frames {
732 735
733 736 #[gpui_kit::test]
734 737 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
738 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
739 }
740
741 #[gpui_kit::test]
742 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
743 let (width, height) = SIZES[1];
744 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
745 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
746 }
747
748 fn check_layout(
749 cx: &mut TestAppContext,
750 sizes: &[(f32, f32)],
751 zoom: f32,
752 known_violations: &[&str],
753 ) {
735 754 let (handle, app) = mount(cx);
755 let platform_scale = cx
756 .update_window(handle, |_, window, _| window.scale_factor())
757 .expect("test window");
758 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
736 759 let mut visual = VisualTestContext::from_window(handle, cx);
737 760 let mut seen_known = HashSet::new();
738 761 let mut unexpected = Vec::new();
739 for (width, height) in SIZES {
762 for &(width, height) in sizes {
740 763 visual.simulate_resize(size(px(width), px(height)));
741 764 let window = Bounds {
742 765 origin: point(px(0.), px(0.)),
@@ -921,7 +944,7 @@ mod frames {
921 944 }
922 945 for (key, message) in found {
923 946 let full_key = format!("{screen_name}@{width}x{height}:{key}");
924 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
947 if known_violations.contains(&full_key.as_str()) {
925 948 seen_known.insert(full_key);
926 949 } else {
927 950 unexpected.push(format!("{full_key}: {message}"));
@@ -929,7 +952,7 @@ mod frames {
929 952 }
930 953 }
931 954 }
932 let stale: Vec<String> = KNOWN_VIOLATIONS
955 let stale: Vec<String> = known_violations
933 956 .iter()
934 957 .filter(|key| !seen_known.contains(**key))
935 958 .map(|key| format!("stale known violation, remove it: {key}"))
@@ -944,6 +967,40 @@ mod frames {
944 967 .join("\n")
945 968 );
946 969 }
970 #[gpui_kit::test]
971 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
972 let (handle, _) = mount(cx);
973 let mut visual = VisualTestContext::from_window(handle, cx);
974 visual.simulate_resize(size(px(1280.), px(800.)));
975 collect(&mut visual, Some(OWN_AVATAR_DISC));
976 let disc = visual
977 .debug_bounds(OWN_AVATAR_DISC)
978 .expect("own avatar rendered");
979 let bar = visual
980 .debug_bounds("shell/title-bar")
981 .expect("title bar rendered");
982 assert_eq!(
983 f32::from(disc.size.width),
984 TITLE_AVATAR_SIZE,
985 "{}",
986 describe(disc)
987 );
988 assert_eq!(
989 f32::from(disc.size.height),
990 TITLE_AVATAR_SIZE,
991 "{}",
992 describe(disc)
993 );
994 let top = f32::from(disc.top() - bar.top());
995 let bottom = f32::from(bar.bottom() - disc.bottom());
996 assert!(
997 (top - bottom).abs() <= 1.,
998 "own avatar {} is not centered in the title bar {}",
999 describe(disc),
1000 describe(bar)
1001 );
1002 }
1003
947 1004 const TITLE_SEARCH: &str = "shell/title-bar/search";
948 1005 const TITLE_NEIGHBOURS: &[&str] = &[
949 1006 "shell/title-bar/leading",
@@ -1197,6 +1254,13 @@ mod frames {
1197 1254 crate::theme::set_thread_scheme(None);
1198 1255 }
1199 1256
1257 #[gpui_kit::test]
1258 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1259 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1260 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1261 crate::theme::set_thread_shade(None);
1262 }
1263
1200 1264 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1201 1265 let (handle, state) = mount_with(cx, true);
1202 1266 let mut visual = VisualTestContext::from_window(handle, cx);
@@ -194,6 +194,7 @@ mod frames {
194 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
194 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
195 };
195 };
196 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
196 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
197 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
197
198
198 const GUARDED: &[&str] = &[
199 const GUARDED: &[&str] = &[
199 "shell",
200 "shell",
@@ -201,6 +202,7 @@ mod frames {
201 "shell/title-bar/search",
202 "shell/title-bar/search",
202 "shell/title-bar/own-status",
203 "shell/title-bar/own-status",
203 "shell/title-bar/own-status/avatar",
204 "shell/title-bar/own-status/avatar",
205 OWN_AVATAR_DISC,
204 "shell/islands",
206 "shell/islands",
205 "shell/islands/rail",
207 "shell/islands/rail",
206 "shell/islands/sidebar",
208 "shell/islands/sidebar",
@@ -317,6 +319,7 @@ mod frames {
317 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
319 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
318 const TOLERANCE: f32 = 0.5;
320 const TOLERANCE: f32 = 0.5;
319 const KNOWN_VIOLATIONS: &[&str] = &[];
321 const KNOWN_VIOLATIONS: &[&str] = &[];
322 const ZOOM_STEP: f32 = 1.25;
320
323
321 type Tag = (&'static str, Bounds<Pixels>);
324 type Tag = (&'static str, Bounds<Pixels>);
322
325
@@ -732,11 +735,31 @@ mod frames {
732
735
733 #[gpui_kit::test]
736 #[gpui_kit::test]
734 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
737 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
738 check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
739 }
740
741 #[gpui_kit::test]
742 fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
743 let (width, height) = SIZES[1];
744 let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
745 check_layout(cx, &zoomed, ZOOM_STEP, &[]);
746 }
747
748 fn check_layout(
749 cx: &mut TestAppContext,
750 sizes: &[(f32, f32)],
751 zoom: f32,
752 known_violations: &[&str],
753 ) {
735 let (handle, app) = mount(cx);
754 let (handle, app) = mount(cx);
755 let platform_scale = cx
756 .update_window(handle, |_, window, _| window.scale_factor())
757 .expect("test window");
758 cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
736 let mut visual = VisualTestContext::from_window(handle, cx);
759 let mut visual = VisualTestContext::from_window(handle, cx);
737 let mut seen_known = HashSet::new();
760 let mut seen_known = HashSet::new();
738 let mut unexpected = Vec::new();
761 let mut unexpected = Vec::new();
739 for (width, height) in SIZES {
762 for &(width, height) in sizes {
740 visual.simulate_resize(size(px(width), px(height)));
763 visual.simulate_resize(size(px(width), px(height)));
741 let window = Bounds {
764 let window = Bounds {
742 origin: point(px(0.), px(0.)),
765 origin: point(px(0.), px(0.)),
@@ -921,7 +944,7 @@ mod frames {
921 }
944 }
922 for (key, message) in found {
945 for (key, message) in found {
923 let full_key = format!("{screen_name}@{width}x{height}:{key}");
946 let full_key = format!("{screen_name}@{width}x{height}:{key}");
924 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
947 if known_violations.contains(&full_key.as_str()) {
925 seen_known.insert(full_key);
948 seen_known.insert(full_key);
926 } else {
949 } else {
927 unexpected.push(format!("{full_key}: {message}"));
950 unexpected.push(format!("{full_key}: {message}"));
@@ -929,7 +952,7 @@ mod frames {
929 }
952 }
930 }
953 }
931 }
954 }
932 let stale: Vec<String> = KNOWN_VIOLATIONS
955 let stale: Vec<String> = known_violations
933 .iter()
956 .iter()
934 .filter(|key| !seen_known.contains(**key))
957 .filter(|key| !seen_known.contains(**key))
935 .map(|key| format!("stale known violation, remove it: {key}"))
958 .map(|key| format!("stale known violation, remove it: {key}"))
@@ -944,6 +967,40 @@ mod frames {
944 .join("\n")
967 .join("\n")
945 );
968 );
946 }
969 }
970 #[gpui_kit::test]
971 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
972 let (handle, _) = mount(cx);
973 let mut visual = VisualTestContext::from_window(handle, cx);
974 visual.simulate_resize(size(px(1280.), px(800.)));
975 collect(&mut visual, Some(OWN_AVATAR_DISC));
976 let disc = visual
977 .debug_bounds(OWN_AVATAR_DISC)
978 .expect("own avatar rendered");
979 let bar = visual
980 .debug_bounds("shell/title-bar")
981 .expect("title bar rendered");
982 assert_eq!(
983 f32::from(disc.size.width),
984 TITLE_AVATAR_SIZE,
985 "{}",
986 describe(disc)
987 );
988 assert_eq!(
989 f32::from(disc.size.height),
990 TITLE_AVATAR_SIZE,
991 "{}",
992 describe(disc)
993 );
994 let top = f32::from(disc.top() - bar.top());
995 let bottom = f32::from(bar.bottom() - disc.bottom());
996 assert!(
997 (top - bottom).abs() <= 1.,
998 "own avatar {} is not centered in the title bar {}",
999 describe(disc),
1000 describe(bar)
1001 );
1002 }
1003
947 const TITLE_SEARCH: &str = "shell/title-bar/search";
1004 const TITLE_SEARCH: &str = "shell/title-bar/search";
948 const TITLE_NEIGHBOURS: &[&str] = &[
1005 const TITLE_NEIGHBOURS: &[&str] = &[
949 "shell/title-bar/leading",
1006 "shell/title-bar/leading",
@@ -1197,6 +1254,13 @@ mod frames {
1197 crate::theme::set_thread_scheme(None);
1254 crate::theme::set_thread_scheme(None);
1198 }
1255 }
1199
1256
1257 #[gpui_kit::test]
1258 fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1259 crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1260 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1261 crate::theme::set_thread_shade(None);
1262 }
1263
1200 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1264 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1201 let (handle, state) = mount_with(cx, true);
1265 let (handle, state) = mount_with(cx, true);
1202 let mut visual = VisualTestContext::from_window(handle, cx);
1266 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/add_people_dialog.rs added +320 −0
@@ -0,0 +1,320 @@
1 use chatsvc::{HistoryShare, MAX_HISTORY_DAYS};
2 use gpui_kit::component::button::{Button, ButtonVariants as _};
3 use gpui_kit::component::dialog::{Dialog, DialogFooter};
4 use gpui_kit::component::input::{Input, InputEvent, InputState};
5 use gpui_kit::component::radio::Radio;
6 use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
7 use gpui_kit::prelude::FluentBuilder as _;
8 use gpui_kit::*;
9 use store::MemberRecord;
10
11 use super::new_chat::{NewChatDraft, Pick};
12 use crate::app_state::AppState;
13 use crate::theme;
14
15 const DIALOG_WIDTH: f32 = 480.;
16 const TITLE: &str = "Add people";
17 const FIELD_RADIUS: f32 = 6.;
18 const DAYS_FIELD_WIDTH: f32 = 64.;
19 const DEFAULT_DAYS: &str = "1";
20 const SECTION_GAP: f32 = 12.;
21 const OPTION_GAP: f32 = 8.;
22
23 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24 pub enum HistoryChoice {
25 None,
26 Days,
27 All,
28 }
29
30 /// Teams accepts 1 to 999 days and disables Add for anything else.
31 pub fn history_share(choice: HistoryChoice, days_text: &str) -> Option<HistoryShare> {
32 match choice {
33 HistoryChoice::None => Some(HistoryShare::None),
34 HistoryChoice::All => Some(HistoryShare::All),
35 HistoryChoice::Days => {
36 let digits: String = days_text.chars().filter(char::is_ascii_digit).collect();
37 let days: u32 = digits.parse().ok()?;
38 (1..=MAX_HISTORY_DAYS)
39 .contains(&days)
40 .then_some(HistoryShare::Days(days))
41 }
42 }
43 }
44
45 /// Everyone of the new group chat after adding to a 1:1: the other member first, then the picks.
46 pub fn group_chat_people(
47 members: &[MemberRecord],
48 my_user_id: Option<&str>,
49 picks: &[Pick],
50 ) -> Vec<MemberRecord> {
51 members
52 .iter()
53 .filter(|member| member.user_id.is_some() && member.user_id.as_deref() != my_user_id)
54 .cloned()
55 .chain(picks.iter().map(member_of))
56 .collect()
57 }
58
59 fn member_of(pick: &Pick) -> MemberRecord {
60 MemberRecord {
61 user_id: Some(pick.user_id.clone()),
62 display_name: pick.name.clone(),
63 }
64 }
65
66 struct AddPeopleForm {
67 app: Entity<AppState>,
68 chat_id: String,
69 one_on_one: bool,
70 people: Entity<NewChatDraft>,
71 days: Entity<InputState>,
72 choice: HistoryChoice,
73 _subscriptions: Vec<Subscription>,
74 }
75
76 impl AddPeopleForm {
77 fn new(
78 app: Entity<AppState>,
79 chat_id: String,
80 one_on_one: bool,
81 window: &mut Window,
82 cx: &mut Context<Self>,
83 ) -> Self {
84 let members: Vec<String> = app
85 .read(cx)
86 .sidebar
87 .chats
88 .iter()
89 .find(|chat| chat.id == chat_id)
90 .map(|chat| {
91 chat.members
92 .iter()
93 .filter_map(|member| member.user_id.clone())
94 .collect()
95 })
96 .unwrap_or_default();
97 let people_app = app.clone();
98 let people = cx.new(|cx| {
99 NewChatDraft::new(people_app, window, cx)
100 .compact()
101 .excluding(members)
102 });
103 let days = cx.new(|cx| {
104 let mut input = InputState::new(window, cx);
105 input.set_value(DEFAULT_DAYS, window, cx);
106 input
107 });
108 let subscriptions = vec![
109 cx.observe(&people, |_, _, cx| cx.notify()),
110 cx.subscribe_in(&days, window, |form, _, event: &InputEvent, _, cx| {
111 if matches!(event, InputEvent::Focus) {
112 form.choice = HistoryChoice::Days;
113 }
114 cx.notify();
115 }),
116 ];
117 AddPeopleForm {
118 app,
119 chat_id,
120 one_on_one,
121 people,
122 days,
123 choice: HistoryChoice::None,
124 _subscriptions: subscriptions,
125 }
126 }
127
128 fn share(&self, cx: &App) -> Option<HistoryShare> {
129 history_share(self.choice, &self.days.read(cx).value())
130 }
131
132 fn can_add(&self, cx: &App) -> bool {
133 !self.people.read(cx).chips().is_empty() && (self.one_on_one || self.share(cx).is_some())
134 }
135
136 fn choose(&mut self, choice: HistoryChoice, cx: &mut Context<Self>) {
137 self.choice = choice;
138 cx.notify();
139 }
140
141 fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
142 if !self.can_add(cx) {
143 return;
144 }
145 let picks = self.people.read(cx).chips().to_vec();
146 let chat_id = self.chat_id.clone();
147 if self.one_on_one {
148 self.app.update(cx, |state, cx| {
149 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
150 let members = state
151 .sidebar
152 .chats
153 .iter()
154 .find(|chat| chat.id == chat_id)
155 .map(|chat| chat.members.clone())
156 .unwrap_or_default();
157 let people = group_chat_people(&members, my_user_id.as_deref(), &picks);
158 state.start_group_chat_with(people, cx);
159 });
160 } else {
161 let share = self.share(cx).unwrap_or_default();
162 let people = picks.iter().map(member_of).collect();
163 self.app.update(cx, |state, cx| {
164 state.add_chat_members(&chat_id, people, share, cx)
165 });
166 }
167 window.close_dialog(cx);
168 }
169
170 fn history_options(&self, cx: &mut Context<Self>) -> Div {
171 let form = cx.entity();
172 let option = |id: &'static str, label: &'static str, choice: HistoryChoice| {
173 let form = form.clone();
174 Radio::new(id)
175 .label(label)
176 .checked(self.choice == choice)
177 .on_click(move |_, _, cx| form.update(cx, |form, cx| form.choose(choice, cx)))
178 };
179 v_flex()
180 .debug_selector(|| "add-people/history".into())
181 .gap(px(OPTION_GAP))
182 .child(option(
183 "add-people-no-history",
184 "Don't include chat history",
185 HistoryChoice::None,
186 ))
187 .child(
188 h_flex()
189 .gap(px(OPTION_GAP))
190 .items_center()
191 .child(option(
192 "add-people-some-history",
193 "Include history from the past number of days:",
194 HistoryChoice::Days,
195 ))
196 .child(
197 div()
198 .w(px(DAYS_FIELD_WIDTH))
199 .flex_none()
200 .child(Input::new(&self.days)),
201 ),
202 )
203 .child(option(
204 "add-people-all-history",
205 "Include all chat history",
206 HistoryChoice::All,
207 ))
208 }
209 }
210
211 impl Render for AddPeopleForm {
212 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
213 v_flex()
214 .debug_selector(|| "add-people".into())
215 .gap(px(SECTION_GAP))
216 .child(
217 div()
218 .debug_selector(|| "add-people/people".into())
219 .rounded(px(FIELD_RADIUS))
220 .bg(theme::surface_raised())
221 .child(self.people.clone()),
222 )
223 .when(!self.one_on_one, |column| {
224 column.child(self.history_options(cx))
225 })
226 }
227 }
228
229 pub fn open_add_people(
230 app: &Entity<AppState>,
231 chat_id: &str,
232 one_on_one: bool,
233 window: &mut Window,
234 cx: &mut App,
235 ) {
236 let (app, chat_id) = (app.clone(), chat_id.to_owned());
237 let form = cx.new(|cx| AddPeopleForm::new(app, chat_id, one_on_one, window, cx));
238 let people = form.read(cx).people.clone();
239 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
240 let submit_form = form.clone();
241 let can_add = form.read(cx).can_add(cx);
242 let footer = DialogFooter::new()
243 .child(
244 Button::new("add-people-cancel")
245 .label("Cancel")
246 .on_click(|_, window, cx| window.close_dialog(cx)),
247 )
248 .child(
249 Button::new("add-people-confirm")
250 .primary()
251 .label("Add")
252 .disabled(!can_add)
253 .on_click(move |_, window, cx| {
254 submit_form.update(cx, |form, cx| form.submit(window, cx));
255 }),
256 );
257 dialog
258 .title(TITLE)
259 .w(px(DIALOG_WIDTH))
260 .child(form.clone())
261 .footer(footer)
262 });
263 window.defer(cx, move |window, cx| {
264 people.update(cx, |draft, cx| draft.focus_query(window, cx));
265 });
266 }
267
268 #[cfg(test)]
269 mod tests {
270 use chatsvc::HistoryShare;
271 use store::MemberRecord;
272
273 use super::{HistoryChoice, Pick, group_chat_people, history_share};
274
275 fn member(user_id: &str, name: &str) -> MemberRecord {
276 MemberRecord {
277 user_id: Some(user_id.to_owned()),
278 display_name: name.to_owned(),
279 }
280 }
281
282 #[test]
283 fn history_choice_maps_to_the_share_teams_sends() {
284 assert_eq!(
285 history_share(HistoryChoice::None, "abc"),
286 Some(HistoryShare::None)
287 );
288 assert_eq!(
289 history_share(HistoryChoice::All, ""),
290 Some(HistoryShare::All)
291 );
292 assert_eq!(
293 history_share(HistoryChoice::Days, "14"),
294 Some(HistoryShare::Days(14))
295 );
296 }
297
298 #[test]
299 fn day_counts_outside_one_to_999_disable_adding() {
300 assert_eq!(history_share(HistoryChoice::Days, ""), None);
301 assert_eq!(history_share(HistoryChoice::Days, "0"), None);
302 assert_eq!(history_share(HistoryChoice::Days, "1000"), None);
303 assert_eq!(
304 history_share(HistoryChoice::Days, "999"),
305 Some(HistoryShare::Days(999))
306 );
307 }
308
309 #[test]
310 fn one_on_one_becomes_a_group_with_the_other_member_and_the_picks() {
311 let members = [member("me", "Daniel"), member("ann", "Ann")];
312 let picks = [Pick {
313 user_id: "bob".to_owned(),
314 name: "Bob".to_owned(),
315 mail: None,
316 }];
317 let people = group_chat_people(&members, Some("me"), &picks);
318 assert_eq!(people, [member("ann", "Ann"), member("bob", "Bob")]);
319 }
320 }
@@ -0,0 +1,320 @@
1use chatsvc::{HistoryShare, MAX_HISTORY_DAYS};
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::dialog::{Dialog, DialogFooter};
4use gpui_kit::component::input::{Input, InputEvent, InputState};
5use gpui_kit::component::radio::Radio;
6use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use store::MemberRecord;
10
11use super::new_chat::{NewChatDraft, Pick};
12use crate::app_state::AppState;
13use crate::theme;
14
15const DIALOG_WIDTH: f32 = 480.;
16const TITLE: &str = "Add people";
17const FIELD_RADIUS: f32 = 6.;
18const DAYS_FIELD_WIDTH: f32 = 64.;
19const DEFAULT_DAYS: &str = "1";
20const SECTION_GAP: f32 = 12.;
21const OPTION_GAP: f32 = 8.;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum HistoryChoice {
25 None,
26 Days,
27 All,
28}
29
30/// Teams accepts 1 to 999 days and disables Add for anything else.
31pub fn history_share(choice: HistoryChoice, days_text: &str) -> Option<HistoryShare> {
32 match choice {
33 HistoryChoice::None => Some(HistoryShare::None),
34 HistoryChoice::All => Some(HistoryShare::All),
35 HistoryChoice::Days => {
36 let digits: String = days_text.chars().filter(char::is_ascii_digit).collect();
37 let days: u32 = digits.parse().ok()?;
38 (1..=MAX_HISTORY_DAYS)
39 .contains(&days)
40 .then_some(HistoryShare::Days(days))
41 }
42 }
43}
44
45/// Everyone of the new group chat after adding to a 1:1: the other member first, then the picks.
46pub fn group_chat_people(
47 members: &[MemberRecord],
48 my_user_id: Option<&str>,
49 picks: &[Pick],
50) -> Vec<MemberRecord> {
51 members
52 .iter()
53 .filter(|member| member.user_id.is_some() && member.user_id.as_deref() != my_user_id)
54 .cloned()
55 .chain(picks.iter().map(member_of))
56 .collect()
57}
58
59fn member_of(pick: &Pick) -> MemberRecord {
60 MemberRecord {
61 user_id: Some(pick.user_id.clone()),
62 display_name: pick.name.clone(),
63 }
64}
65
66struct AddPeopleForm {
67 app: Entity<AppState>,
68 chat_id: String,
69 one_on_one: bool,
70 people: Entity<NewChatDraft>,
71 days: Entity<InputState>,
72 choice: HistoryChoice,
73 _subscriptions: Vec<Subscription>,
74}
75
76impl AddPeopleForm {
77 fn new(
78 app: Entity<AppState>,
79 chat_id: String,
80 one_on_one: bool,
81 window: &mut Window,
82 cx: &mut Context<Self>,
83 ) -> Self {
84 let members: Vec<String> = app
85 .read(cx)
86 .sidebar
87 .chats
88 .iter()
89 .find(|chat| chat.id == chat_id)
90 .map(|chat| {
91 chat.members
92 .iter()
93 .filter_map(|member| member.user_id.clone())
94 .collect()
95 })
96 .unwrap_or_default();
97 let people_app = app.clone();
98 let people = cx.new(|cx| {
99 NewChatDraft::new(people_app, window, cx)
100 .compact()
101 .excluding(members)
102 });
103 let days = cx.new(|cx| {
104 let mut input = InputState::new(window, cx);
105 input.set_value(DEFAULT_DAYS, window, cx);
106 input
107 });
108 let subscriptions = vec![
109 cx.observe(&people, |_, _, cx| cx.notify()),
110 cx.subscribe_in(&days, window, |form, _, event: &InputEvent, _, cx| {
111 if matches!(event, InputEvent::Focus) {
112 form.choice = HistoryChoice::Days;
113 }
114 cx.notify();
115 }),
116 ];
117 AddPeopleForm {
118 app,
119 chat_id,
120 one_on_one,
121 people,
122 days,
123 choice: HistoryChoice::None,
124 _subscriptions: subscriptions,
125 }
126 }
127
128 fn share(&self, cx: &App) -> Option<HistoryShare> {
129 history_share(self.choice, &self.days.read(cx).value())
130 }
131
132 fn can_add(&self, cx: &App) -> bool {
133 !self.people.read(cx).chips().is_empty() && (self.one_on_one || self.share(cx).is_some())
134 }
135
136 fn choose(&mut self, choice: HistoryChoice, cx: &mut Context<Self>) {
137 self.choice = choice;
138 cx.notify();
139 }
140
141 fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
142 if !self.can_add(cx) {
143 return;
144 }
145 let picks = self.people.read(cx).chips().to_vec();
146 let chat_id = self.chat_id.clone();
147 if self.one_on_one {
148 self.app.update(cx, |state, cx| {
149 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
150 let members = state
151 .sidebar
152 .chats
153 .iter()
154 .find(|chat| chat.id == chat_id)
155 .map(|chat| chat.members.clone())
156 .unwrap_or_default();
157 let people = group_chat_people(&members, my_user_id.as_deref(), &picks);
158 state.start_group_chat_with(people, cx);
159 });
160 } else {
161 let share = self.share(cx).unwrap_or_default();
162 let people = picks.iter().map(member_of).collect();
163 self.app.update(cx, |state, cx| {
164 state.add_chat_members(&chat_id, people, share, cx)
165 });
166 }
167 window.close_dialog(cx);
168 }
169
170 fn history_options(&self, cx: &mut Context<Self>) -> Div {
171 let form = cx.entity();
172 let option = |id: &'static str, label: &'static str, choice: HistoryChoice| {
173 let form = form.clone();
174 Radio::new(id)
175 .label(label)
176 .checked(self.choice == choice)
177 .on_click(move |_, _, cx| form.update(cx, |form, cx| form.choose(choice, cx)))
178 };
179 v_flex()
180 .debug_selector(|| "add-people/history".into())
181 .gap(px(OPTION_GAP))
182 .child(option(
183 "add-people-no-history",
184 "Don't include chat history",
185 HistoryChoice::None,
186 ))
187 .child(
188 h_flex()
189 .gap(px(OPTION_GAP))
190 .items_center()
191 .child(option(
192 "add-people-some-history",
193 "Include history from the past number of days:",
194 HistoryChoice::Days,
195 ))
196 .child(
197 div()
198 .w(px(DAYS_FIELD_WIDTH))
199 .flex_none()
200 .child(Input::new(&self.days)),
201 ),
202 )
203 .child(option(
204 "add-people-all-history",
205 "Include all chat history",
206 HistoryChoice::All,
207 ))
208 }
209}
210
211impl Render for AddPeopleForm {
212 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
213 v_flex()
214 .debug_selector(|| "add-people".into())
215 .gap(px(SECTION_GAP))
216 .child(
217 div()
218 .debug_selector(|| "add-people/people".into())
219 .rounded(px(FIELD_RADIUS))
220 .bg(theme::surface_raised())
221 .child(self.people.clone()),
222 )
223 .when(!self.one_on_one, |column| {
224 column.child(self.history_options(cx))
225 })
226 }
227}
228
229pub fn open_add_people(
230 app: &Entity<AppState>,
231 chat_id: &str,
232 one_on_one: bool,
233 window: &mut Window,
234 cx: &mut App,
235) {
236 let (app, chat_id) = (app.clone(), chat_id.to_owned());
237 let form = cx.new(|cx| AddPeopleForm::new(app, chat_id, one_on_one, window, cx));
238 let people = form.read(cx).people.clone();
239 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
240 let submit_form = form.clone();
241 let can_add = form.read(cx).can_add(cx);
242 let footer = DialogFooter::new()
243 .child(
244 Button::new("add-people-cancel")
245 .label("Cancel")
246 .on_click(|_, window, cx| window.close_dialog(cx)),
247 )
248 .child(
249 Button::new("add-people-confirm")
250 .primary()
251 .label("Add")
252 .disabled(!can_add)
253 .on_click(move |_, window, cx| {
254 submit_form.update(cx, |form, cx| form.submit(window, cx));
255 }),
256 );
257 dialog
258 .title(TITLE)
259 .w(px(DIALOG_WIDTH))
260 .child(form.clone())
261 .footer(footer)
262 });
263 window.defer(cx, move |window, cx| {
264 people.update(cx, |draft, cx| draft.focus_query(window, cx));
265 });
266}
267
268#[cfg(test)]
269mod tests {
270 use chatsvc::HistoryShare;
271 use store::MemberRecord;
272
273 use super::{HistoryChoice, Pick, group_chat_people, history_share};
274
275 fn member(user_id: &str, name: &str) -> MemberRecord {
276 MemberRecord {
277 user_id: Some(user_id.to_owned()),
278 display_name: name.to_owned(),
279 }
280 }
281
282 #[test]
283 fn history_choice_maps_to_the_share_teams_sends() {
284 assert_eq!(
285 history_share(HistoryChoice::None, "abc"),
286 Some(HistoryShare::None)
287 );
288 assert_eq!(
289 history_share(HistoryChoice::All, ""),
290 Some(HistoryShare::All)
291 );
292 assert_eq!(
293 history_share(HistoryChoice::Days, "14"),
294 Some(HistoryShare::Days(14))
295 );
296 }
297
298 #[test]
299 fn day_counts_outside_one_to_999_disable_adding() {
300 assert_eq!(history_share(HistoryChoice::Days, ""), None);
301 assert_eq!(history_share(HistoryChoice::Days, "0"), None);
302 assert_eq!(history_share(HistoryChoice::Days, "1000"), None);
303 assert_eq!(
304 history_share(HistoryChoice::Days, "999"),
305 Some(HistoryShare::Days(999))
306 );
307 }
308
309 #[test]
310 fn one_on_one_becomes_a_group_with_the_other_member_and_the_picks() {
311 let members = [member("me", "Daniel"), member("ann", "Ann")];
312 let picks = [Pick {
313 user_id: "bob".to_owned(),
314 name: "Bob".to_owned(),
315 mail: None,
316 }];
317 let people = group_chat_people(&members, Some("me"), &picks);
318 assert_eq!(people, [member("ann", "Ann"), member("bob", "Bob")]);
319 }
320}
crates/app/src/views/avatar.rs +74 −27
@@ -1,10 +1,12 @@
1 1 use gpui_kit::prelude::FluentBuilder as _;
2 2 use gpui_kit::*;
3 3
4 use std::sync::Arc;
4 5 use std::time::Duration;
5 6
6 7 use gpui_kit::assets::IconName;
7 8
9 use crate::avatar_image::{AvatarPhoto, device_span};
8 10 use crate::card_state::BotIdentity;
9 11 use crate::data::{AvatarState, Directory, Presence, PresenceKind};
10 12 use crate::format;
@@ -55,22 +57,13 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
55 57 .as_deref()
56 58 .and_then(|user_id| directory.avatar(user_id));
57 59 match state {
58 Some(AvatarState::Ready(image)) => {
59 let texture_size = size / crate::avatar_image::visible_fraction();
60 let offset = (size - texture_size) / 2.;
61 div()
62 .relative()
63 .size(px(size))
64 .flex_none()
65 .child(
66 img(ImageSource::Image(image.clone()))
67 .absolute()
68 .left(px(offset))
69 .top(px(offset))
70 .size(px(texture_size)),
71 )
72 .into_any_element()
73 }
60 Some(AvatarState::Ready(photo)) => photo_disc(photo, size, size / 2.),
61 Some(AvatarState::Icon(image)) => img(ImageSource::Image(image.clone()))
62 .size(px(size))
63 .flex_none()
64 .rounded_full()
65 .object_fit(ObjectFit::Cover)
66 .into_any_element(),
74 67 Some(AvatarState::Pending) => {
75 68 initials_circle(&face.name, key, size, true, text_ratio).into_any_element()
76 69 }
@@ -78,6 +71,38 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
78 71 }
79 72 }
80 73
74 fn photo_disc(photo: &Arc<AvatarPhoto>, size: f32, radius: f32) -> AnyElement {
75 let photo = photo.clone();
76 canvas(
77 |_, _, _| {},
78 move |bounds, _, window, cx| {
79 let scale_factor = window.scale_factor();
80 let side = device_span(
81 f32::from(bounds.left()),
82 f32::from(bounds.right()),
83 scale_factor,
84 );
85 let Some(texture) = photo.texture(side) else {
86 return;
87 };
88 if let Some(evicted) = texture.evicted {
89 cx.drop_image(evicted, Some(window));
90 }
91 let _ = window.paint_image(
92 bounds,
93 bounds,
94 Corners::all(px(radius)),
95 texture.image,
96 0,
97 false,
98 );
99 },
100 )
101 .size(px(size))
102 .flex_none()
103 .into_any_element()
104 }
105
81 106 pub fn person_avatar(
82 107 directory: &Directory,
83 108 user_id: Option<&str>,
@@ -105,6 +130,7 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
105 130 .child(
106 131 img(url.clone())
107 132 .size_full()
133 .rounded_full()
108 134 .object_fit(ObjectFit::Cover)
109 135 .with_loading(initials.clone())
110 136 .with_fallback(initials),
@@ -122,7 +148,10 @@ pub fn bot_tile(directory: &Directory, face: &Face, size: f32) -> AnyElement {
122 148 .and_then(|user_id| directory.avatar(user_id));
123 149 let tile = div().size(px(size)).flex_none().rounded(px(radius));
124 150 match image {
125 Some(AvatarState::Ready(image)) => tile
151 Some(AvatarState::Ready(photo)) => tile
152 .child(photo_disc(photo, size, radius))
153 .into_any_element(),
154 Some(AvatarState::Icon(image)) => tile
126 155 .child(
127 156 img(ImageSource::Image(image.clone()))
128 157 .size_full()
@@ -143,8 +172,7 @@ pub fn presence_size(avatar_size: f32) -> f32 {
143 172 .clamp(PRESENCE_MIN, PRESENCE_MAX)
144 173 }
145 174
146 pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<Div> {
147 let outer = presence_size(avatar_size);
175 fn presence_badge(kind: PresenceKind, ring: Hsla, outer: f32) -> Option<Div> {
148 176 let inner = outer - 2. * PRESENCE_RING;
149 177 let fill = match kind {
150 178 PresenceKind::Available => theme::green(),
@@ -166,7 +194,9 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
166 194 center.child(div().w(px(inner - 4.)).h(px(2.)).rounded(px(1.)).bg(ring))
167 195 }
168 196 PresenceKind::Offline => center.border(px(1.5)).border_color(theme::text_muted()),
169 PresenceKind::OutOfOffice => center.child(icon(IconName::ArrowLeft, inner - 2., theme::white())),
197 PresenceKind::OutOfOffice => {
198 center.child(icon(IconName::ArrowLeft, inner - 2., theme::white()))
199 }
170 200 _ => center,
171 201 };
172 202 Some(
@@ -181,8 +211,7 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
181 211 )
182 212 }
183 213
184 fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
185 let outer = presence_size(avatar_size);
214 fn presence_spinner(ring: Hsla, outer: f32) -> Div {
186 215 let spinner = icon(IconName::Loader, outer - PRESENCE_RING, theme::text_muted())
187 216 .with_animation(
188 217 "presence-spinner",
@@ -200,12 +229,22 @@ fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
200 229 }
201 230
202 231 pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {
232 with_presence_badge(avatar, presence, size, presence_size(size), ring)
233 }
234
235 pub fn with_presence_badge(
236 avatar: AnyElement,
237 presence: Presence,
238 size: f32,
239 badge: f32,
240 ring: Hsla,
241 ) -> Div {
203 242 let wrapper = div().relative().size(px(size)).flex_none().child(avatar);
204 243 match presence {
205 Presence::Loading => wrapper.child(presence_spinner(ring, size)),
206 Presence::Live(kind) => wrapper.children(presence_dot(kind, ring, size)),
244 Presence::Loading => wrapper.child(presence_spinner(ring, badge)),
245 Presence::Live(kind) => wrapper.children(presence_badge(kind, ring, badge)),
207 246 Presence::Cached(kind) => wrapper.children(
208 presence_dot(kind, ring, size).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
247 presence_badge(kind, ring, badge).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
209 248 ),
210 249 }
211 250 }
@@ -222,7 +261,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
222 261 .flex()
223 262 .items_center()
224 263 .justify_center()
225 .child(icon(IconName::Calendar, (size * MEETING_ICON_RATIO).round(), theme::white()))
264 .child(icon(
265 IconName::Calendar,
266 (size * MEETING_ICON_RATIO).round(),
267 theme::white(),
268 ))
226 269 .into_any_element(),
227 270 AvatarSpec::Muted => div()
228 271 .size(px(size))
@@ -232,7 +275,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
232 275 .flex()
233 276 .items_center()
234 277 .justify_center()
235 .child(icon(IconName::BellOff, (size * MEETING_ICON_RATIO).round(), theme::text_muted()))
278 .child(icon(
279 IconName::BellOff,
280 (size * MEETING_ICON_RATIO).round(),
281 theme::text_muted(),
282 ))
236 283 .into_any_element(),
237 284 AvatarSpec::Pair(first, second) => {
238 285 let small = (size * PAIR_RATIO).round();
@@ -1,10 +1,12 @@
1use gpui_kit::prelude::FluentBuilder as _;
1use gpui_kit::prelude::FluentBuilder as _;
2use gpui_kit::*;
2use gpui_kit::*;
3
3
4use std::sync::Arc;
4use std::time::Duration;
5use std::time::Duration;
5
6
6use gpui_kit::assets::IconName;
7use gpui_kit::assets::IconName;
7
8
9use crate::avatar_image::{AvatarPhoto, device_span};
8use crate::card_state::BotIdentity;
10use crate::card_state::BotIdentity;
9use crate::data::{AvatarState, Directory, Presence, PresenceKind};
11use crate::data::{AvatarState, Directory, Presence, PresenceKind};
10use crate::format;
12use crate::format;
@@ -55,22 +57,13 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
55 .as_deref()
57 .as_deref()
56 .and_then(|user_id| directory.avatar(user_id));
58 .and_then(|user_id| directory.avatar(user_id));
57 match state {
59 match state {
58 Some(AvatarState::Ready(image)) => {
60 Some(AvatarState::Ready(photo)) => photo_disc(photo, size, size / 2.),
59 let texture_size = size / crate::avatar_image::visible_fraction();
61 Some(AvatarState::Icon(image)) => img(ImageSource::Image(image.clone()))
60 let offset = (size - texture_size) / 2.;
62 .size(px(size))
61 div()
63 .flex_none()
62 .relative()
64 .rounded_full()
63 .size(px(size))
65 .object_fit(ObjectFit::Cover)
64 .flex_none()
66 .into_any_element(),
65 .child(
66 img(ImageSource::Image(image.clone()))
67 .absolute()
68 .left(px(offset))
69 .top(px(offset))
70 .size(px(texture_size)),
71 )
72 .into_any_element()
73 }
74 Some(AvatarState::Pending) => {
67 Some(AvatarState::Pending) => {
75 initials_circle(&face.name, key, size, true, text_ratio).into_any_element()
68 initials_circle(&face.name, key, size, true, text_ratio).into_any_element()
76 }
69 }
@@ -78,6 +71,38 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
78 }
71 }
79}
72}
80
73
74fn photo_disc(photo: &Arc<AvatarPhoto>, size: f32, radius: f32) -> AnyElement {
75 let photo = photo.clone();
76 canvas(
77 |_, _, _| {},
78 move |bounds, _, window, cx| {
79 let scale_factor = window.scale_factor();
80 let side = device_span(
81 f32::from(bounds.left()),
82 f32::from(bounds.right()),
83 scale_factor,
84 );
85 let Some(texture) = photo.texture(side) else {
86 return;
87 };
88 if let Some(evicted) = texture.evicted {
89 cx.drop_image(evicted, Some(window));
90 }
91 let _ = window.paint_image(
92 bounds,
93 bounds,
94 Corners::all(px(radius)),
95 texture.image,
96 0,
97 false,
98 );
99 },
100 )
101 .size(px(size))
102 .flex_none()
103 .into_any_element()
104}
105
81pub fn person_avatar(
106pub fn person_avatar(
82 directory: &Directory,
107 directory: &Directory,
83 user_id: Option<&str>,
108 user_id: Option<&str>,
@@ -105,6 +130,7 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
105 .child(
130 .child(
106 img(url.clone())
131 img(url.clone())
107 .size_full()
132 .size_full()
133 .rounded_full()
108 .object_fit(ObjectFit::Cover)
134 .object_fit(ObjectFit::Cover)
109 .with_loading(initials.clone())
135 .with_loading(initials.clone())
110 .with_fallback(initials),
136 .with_fallback(initials),
@@ -122,7 +148,10 @@ pub fn bot_tile(directory: &Directory, face: &Face, size: f32) -> AnyElement {
122 .and_then(|user_id| directory.avatar(user_id));
148 .and_then(|user_id| directory.avatar(user_id));
123 let tile = div().size(px(size)).flex_none().rounded(px(radius));
149 let tile = div().size(px(size)).flex_none().rounded(px(radius));
124 match image {
150 match image {
125 Some(AvatarState::Ready(image)) => tile
151 Some(AvatarState::Ready(photo)) => tile
152 .child(photo_disc(photo, size, radius))
153 .into_any_element(),
154 Some(AvatarState::Icon(image)) => tile
126 .child(
155 .child(
127 img(ImageSource::Image(image.clone()))
156 img(ImageSource::Image(image.clone()))
128 .size_full()
157 .size_full()
@@ -143,8 +172,7 @@ pub fn presence_size(avatar_size: f32) -> f32 {
143 .clamp(PRESENCE_MIN, PRESENCE_MAX)
172 .clamp(PRESENCE_MIN, PRESENCE_MAX)
144}
173}
145
174
146pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<Div> {
175fn presence_badge(kind: PresenceKind, ring: Hsla, outer: f32) -> Option<Div> {
147 let outer = presence_size(avatar_size);
148 let inner = outer - 2. * PRESENCE_RING;
176 let inner = outer - 2. * PRESENCE_RING;
149 let fill = match kind {
177 let fill = match kind {
150 PresenceKind::Available => theme::green(),
178 PresenceKind::Available => theme::green(),
@@ -166,7 +194,9 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
166 center.child(div().w(px(inner - 4.)).h(px(2.)).rounded(px(1.)).bg(ring))
194 center.child(div().w(px(inner - 4.)).h(px(2.)).rounded(px(1.)).bg(ring))
167 }
195 }
168 PresenceKind::Offline => center.border(px(1.5)).border_color(theme::text_muted()),
196 PresenceKind::Offline => center.border(px(1.5)).border_color(theme::text_muted()),
169 PresenceKind::OutOfOffice => center.child(icon(IconName::ArrowLeft, inner - 2., theme::white())),
197 PresenceKind::OutOfOffice => {
198 center.child(icon(IconName::ArrowLeft, inner - 2., theme::white()))
199 }
170 _ => center,
200 _ => center,
171 };
201 };
172 Some(
202 Some(
@@ -181,8 +211,7 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
181 )
211 )
182}
212}
183
213
184fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
214fn presence_spinner(ring: Hsla, outer: f32) -> Div {
185 let outer = presence_size(avatar_size);
186 let spinner = icon(IconName::Loader, outer - PRESENCE_RING, theme::text_muted())
215 let spinner = icon(IconName::Loader, outer - PRESENCE_RING, theme::text_muted())
187 .with_animation(
216 .with_animation(
188 "presence-spinner",
217 "presence-spinner",
@@ -200,12 +229,22 @@ fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
200}
229}
201
230
202pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {
231pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {
232 with_presence_badge(avatar, presence, size, presence_size(size), ring)
233}
234
235pub fn with_presence_badge(
236 avatar: AnyElement,
237 presence: Presence,
238 size: f32,
239 badge: f32,
240 ring: Hsla,
241) -> Div {
203 let wrapper = div().relative().size(px(size)).flex_none().child(avatar);
242 let wrapper = div().relative().size(px(size)).flex_none().child(avatar);
204 match presence {
243 match presence {
205 Presence::Loading => wrapper.child(presence_spinner(ring, size)),
244 Presence::Loading => wrapper.child(presence_spinner(ring, badge)),
206 Presence::Live(kind) => wrapper.children(presence_dot(kind, ring, size)),
245 Presence::Live(kind) => wrapper.children(presence_badge(kind, ring, badge)),
207 Presence::Cached(kind) => wrapper.children(
246 Presence::Cached(kind) => wrapper.children(
208 presence_dot(kind, ring, size).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
247 presence_badge(kind, ring, badge).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
209 ),
248 ),
210 }
249 }
211}
250}
@@ -222,7 +261,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
222 .flex()
261 .flex()
223 .items_center()
262 .items_center()
224 .justify_center()
263 .justify_center()
225 .child(icon(IconName::Calendar, (size * MEETING_ICON_RATIO).round(), theme::white()))
264 .child(icon(
265 IconName::Calendar,
266 (size * MEETING_ICON_RATIO).round(),
267 theme::white(),
268 ))
226 .into_any_element(),
269 .into_any_element(),
227 AvatarSpec::Muted => div()
270 AvatarSpec::Muted => div()
228 .size(px(size))
271 .size(px(size))
@@ -232,7 +275,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
232 .flex()
275 .flex()
233 .items_center()
276 .items_center()
234 .justify_center()
277 .justify_center()
235 .child(icon(IconName::BellOff, (size * MEETING_ICON_RATIO).round(), theme::text_muted()))
278 .child(icon(
279 IconName::BellOff,
280 (size * MEETING_ICON_RATIO).round(),
281 theme::text_muted(),
282 ))
236 .into_any_element(),
283 .into_any_element(),
237 AvatarSpec::Pair(first, second) => {
284 AvatarSpec::Pair(first, second) => {
238 let small = (size * PAIR_RATIO).round();
285 let small = (size * PAIR_RATIO).round();
crates/app/src/views/call_card.rs +1 −0
@@ -54,6 +54,7 @@ fn icon_circle(call: &CallCard, own: bool) -> Div {
54 54 theme::accent_text(),
55 55 ),
56 56 CallIcon::RecordStop => (circle_fill(own), "fluent_record_stop", theme::text()),
57 CallIcon::Roster => (circle_fill(own), "group", theme::text()),
57 58 };
58 59 h_flex()
59 60 .size(px(ICON_CIRCLE))
@@ -54,6 +54,7 @@ fn icon_circle(call: &CallCard, own: bool) -> Div {
54 theme::accent_text(),
54 theme::accent_text(),
55 ),
55 ),
56 CallIcon::RecordStop => (circle_fill(own), "fluent_record_stop", theme::text()),
56 CallIcon::RecordStop => (circle_fill(own), "fluent_record_stop", theme::text()),
57 CallIcon::Roster => (circle_fill(own), "group", theme::text()),
57 };
58 };
58 h_flex()
59 h_flex()
59 .size(px(ICON_CIRCLE))
60 .size(px(ICON_CIRCLE))
crates/app/src/views/call_mini_window.rs +27 −11
@@ -3,9 +3,11 @@ use std::time::Instant;
3 3 use calling::VideoKey;
4 4 use gpui_kit::assets::IconName;
5 5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
6 7 use gpui_kit::*;
7 8
8 9 use super::avatar::person_avatar;
10 use super::call_share_gallery::{SHOW_MORE_PEOPLE, view_switch_button};
9 11 use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};
10 12 use super::widgets::icon;
11 13 use crate::app_state::AppState;
@@ -234,6 +236,7 @@ impl Render for MiniWindowView {
234 236 let now = Instant::now();
235 237 let (status, _) = status_line(model, now);
236 238 let windows = self.windows.clone();
239 let sharing = self.windows.read(cx).sharing();
237 240 let speaking = speaker_speaking(model);
238 241 let speaker_name = speaker_name_chip(state, model, now);
239 242 div()
@@ -274,17 +277,30 @@ impl Render for MiniWindowView {
274 277 }))
275 278 .children(self_view(state, model, now)),
276 279 )
277 .child(controls_row(
278 &self.app,
279 model,
280 ControlIds {
281 mute: "call-mini-window-mute",
282 back: "call-mini-window-back",
283 leave: "call-mini-window-leave",
284 },
285 "call-mini-window",
286 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
287 ))
280 .child(
281 controls_row(
282 &self.app,
283 model,
284 ControlIds {
285 mute: "call-mini-window-mute",
286 back: "call-mini-window-back",
287 leave: "call-mini-window-leave",
288 },
289 "call-mini-window",
290 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
291 )
292 .when(sharing, |row| {
293 row.child(
294 view_switch_button(
295 &self.windows,
296 "call-mini-window-more-people",
297 IconName::Users,
298 SHOW_MORE_PEOPLE,
299 )
300 .size(px(CONTROL_SIZE)),
301 )
302 }),
303 )
288 304 .into_any_element()
289 305 }
290 306 }
@@ -3,9 +3,11 @@ use std::time::Instant;
3use calling::VideoKey;
3use calling::VideoKey;
4use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use gpui_kit::*;
7
8
8use super::avatar::person_avatar;
9use super::avatar::person_avatar;
10use super::call_share_gallery::{SHOW_MORE_PEOPLE, view_switch_button};
9use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};
11use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};
10use super::widgets::icon;
12use super::widgets::icon;
11use crate::app_state::AppState;
13use crate::app_state::AppState;
@@ -234,6 +236,7 @@ impl Render for MiniWindowView {
234 let now = Instant::now();
236 let now = Instant::now();
235 let (status, _) = status_line(model, now);
237 let (status, _) = status_line(model, now);
236 let windows = self.windows.clone();
238 let windows = self.windows.clone();
239 let sharing = self.windows.read(cx).sharing();
237 let speaking = speaker_speaking(model);
240 let speaking = speaker_speaking(model);
238 let speaker_name = speaker_name_chip(state, model, now);
241 let speaker_name = speaker_name_chip(state, model, now);
239 div()
242 div()
@@ -274,17 +277,30 @@ impl Render for MiniWindowView {
274 }))
277 }))
275 .children(self_view(state, model, now)),
278 .children(self_view(state, model, now)),
276 )
279 )
277 .child(controls_row(
280 .child(
278 &self.app,
281 controls_row(
279 model,
282 &self.app,
280 ControlIds {
283 model,
281 mute: "call-mini-window-mute",
284 ControlIds {
282 back: "call-mini-window-back",
285 mute: "call-mini-window-mute",
283 leave: "call-mini-window-leave",
286 back: "call-mini-window-back",
284 },
287 leave: "call-mini-window-leave",
285 "call-mini-window",
288 },
286 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
289 "call-mini-window",
287 ))
290 move |cx| windows.update(cx, |windows, cx| windows.return_to_call(cx)),
291 )
292 .when(sharing, |row| {
293 row.child(
294 view_switch_button(
295 &self.windows,
296 "call-mini-window-more-people",
297 IconName::Users,
298 SHOW_MORE_PEOPLE,
299 )
300 .size(px(CONTROL_SIZE)),
301 )
302 }),
303 )
288 .into_any_element()
304 .into_any_element()
289 }
305 }
290}
306}
crates/app/src/views/call_notice.rs +1 −0
@@ -50,6 +50,7 @@ fn notice_icon(icon: CallIcon) -> (&'static str, Hsla) {
50 50 CallIcon::Record => ("fluent_record", theme::accent_text()),
51 51 CallIcon::RecordStop => ("fluent_record_stop", theme::text_muted()),
52 52 CallIcon::Saved => ("fluent_cloud_arrow_up", theme::text_muted()),
53 CallIcon::Roster => ("group", theme::text_muted()),
53 54 CallIcon::Video | CallIcon::Call | CallIcon::Missed => {
54 55 ("fluent_video", theme::text_muted())
55 56 }
@@ -50,6 +50,7 @@ fn notice_icon(icon: CallIcon) -> (&'static str, Hsla) {
50 CallIcon::Record => ("fluent_record", theme::accent_text()),
50 CallIcon::Record => ("fluent_record", theme::accent_text()),
51 CallIcon::RecordStop => ("fluent_record_stop", theme::text_muted()),
51 CallIcon::RecordStop => ("fluent_record_stop", theme::text_muted()),
52 CallIcon::Saved => ("fluent_cloud_arrow_up", theme::text_muted()),
52 CallIcon::Saved => ("fluent_cloud_arrow_up", theme::text_muted()),
53 CallIcon::Roster => ("group", theme::text_muted()),
53 CallIcon::Video | CallIcon::Call | CallIcon::Missed => {
54 CallIcon::Video | CallIcon::Call | CallIcon::Missed => {
54 ("fluent_video", theme::text_muted())
55 ("fluent_video", theme::text_muted())
55 }
56 }
crates/app/src/views/call_view.rs +28 −8
@@ -963,6 +963,17 @@ pub(super) fn person_tile(
963 963 remote: &Tile,
964 964 size: TileSize,
965 965 now: Instant,
966 ) -> AnyElement {
967 let element = plain_person_tile(state, model, remote, size, now);
968 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
969 }
970
971 pub(super) fn plain_person_tile(
972 state: &AppState,
973 model: &CallModel,
974 remote: &Tile,
975 size: TileSize,
976 now: Instant,
966 977 ) -> AnyElement {
967 978 let extras = TileExtras {
968 979 hand: remote.hand.map(|rank| model.hand_position(rank)),
@@ -973,8 +984,7 @@ pub(super) fn person_tile(
973 984 spotlight: remote.spotlight.is_some(),
974 985 pinned: model.is_pinned(&remote.mri),
975 986 };
976 let element = person_tile_body(state, model, remote, size, now, &extras);
977 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
987 person_tile_body(state, model, remote, size, now, &extras)
978 988 }
979 989
980 990 fn person_tile_body(
@@ -1042,18 +1052,28 @@ pub(super) fn own_tile(
1042 1052 now: Instant,
1043 1053 ) -> AnyElement {
1044 1054 let own_mri = model.own_mri.clone().unwrap_or_default();
1055 let element = plain_own_tile(state, model, size, now);
1056 if own_mri.is_empty() {
1057 return element;
1058 }
1059 with_tile_menu(app, model, &own_mri, "You", true, element)
1060 }
1061
1062 pub(super) fn plain_own_tile(
1063 state: &AppState,
1064 model: &CallModel,
1065 size: TileSize,
1066 now: Instant,
1067 ) -> AnyElement {
1068 let own_mri = model.own_mri.as_deref().unwrap_or_default();
1045 1069 let extras = TileExtras {
1046 1070 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1047 1071 own: true,
1048 1072 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1049 1073 spotlight: model.own_spotlight.is_some(),
1050 pinned: model.is_pinned(&own_mri),
1074 pinned: model.is_pinned(own_mri),
1051 1075 };
1052 let element = own_tile_body(state, model, size, now, &extras);
1053 if own_mri.is_empty() {
1054 return element;
1055 }
1056 with_tile_menu(app, model, &own_mri, "You", true, element)
1076 own_tile_body(state, model, size, now, &extras)
1057 1077 }
1058 1078
1059 1079 fn own_tile_body(
@@ -963,6 +963,17 @@ pub(super) fn person_tile(
963 remote: &Tile,
963 remote: &Tile,
964 size: TileSize,
964 size: TileSize,
965 now: Instant,
965 now: Instant,
966) -> AnyElement {
967 let element = plain_person_tile(state, model, remote, size, now);
968 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
969}
970
971pub(super) fn plain_person_tile(
972 state: &AppState,
973 model: &CallModel,
974 remote: &Tile,
975 size: TileSize,
976 now: Instant,
966) -> AnyElement {
977) -> AnyElement {
967 let extras = TileExtras {
978 let extras = TileExtras {
968 hand: remote.hand.map(|rank| model.hand_position(rank)),
979 hand: remote.hand.map(|rank| model.hand_position(rank)),
@@ -973,8 +984,7 @@ pub(super) fn person_tile(
973 spotlight: remote.spotlight.is_some(),
984 spotlight: remote.spotlight.is_some(),
974 pinned: model.is_pinned(&remote.mri),
985 pinned: model.is_pinned(&remote.mri),
975 };
986 };
976 let element = person_tile_body(state, model, remote, size, now, &extras);
987 person_tile_body(state, model, remote, size, now, &extras)
977 with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
978}
988}
979
989
980fn person_tile_body(
990fn person_tile_body(
@@ -1042,18 +1052,28 @@ pub(super) fn own_tile(
1042 now: Instant,
1052 now: Instant,
1043) -> AnyElement {
1053) -> AnyElement {
1044 let own_mri = model.own_mri.clone().unwrap_or_default();
1054 let own_mri = model.own_mri.clone().unwrap_or_default();
1055 let element = plain_own_tile(state, model, size, now);
1056 if own_mri.is_empty() {
1057 return element;
1058 }
1059 with_tile_menu(app, model, &own_mri, "You", true, element)
1060}
1061
1062pub(super) fn plain_own_tile(
1063 state: &AppState,
1064 model: &CallModel,
1065 size: TileSize,
1066 now: Instant,
1067) -> AnyElement {
1068 let own_mri = model.own_mri.as_deref().unwrap_or_default();
1045 let extras = TileExtras {
1069 let extras = TileExtras {
1046 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1070 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1047 own: true,
1071 own: true,
1048 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1072 reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1049 spotlight: model.own_spotlight.is_some(),
1073 spotlight: model.own_spotlight.is_some(),
1050 pinned: model.is_pinned(&own_mri),
1074 pinned: model.is_pinned(own_mri),
1051 };
1075 };
1052 let element = own_tile_body(state, model, size, now, &extras);
1076 own_tile_body(state, model, size, now, &extras)
1053 if own_mri.is_empty() {
1054 return element;
1055 }
1056 with_tile_menu(app, model, &own_mri, "You", true, element)
1057}
1077}
1058
1078
1059fn own_tile_body(
1079fn own_tile_body(
crates/app/src/views/chat_members.rs +11 −4
@@ -6,6 +6,7 @@ use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};
6 6 use gpui_kit::prelude::FluentBuilder as _;
7 7 use gpui_kit::*;
8 8
9 use super::add_people_dialog::open_add_people;
9 10 use super::avatar::{person_avatar, with_presence};
10 11 use super::profile_card::opens_profile;
11 12 use super::sidebar::confirm_leave;
@@ -104,11 +105,17 @@ fn members_panel(
104 105 .child(
105 106 v_flex()
106 107 .py(px(4.))
107 .child(
108 .child({
109 let (app, popover, chat_id) =
110 (app.clone(), popover.clone(), chat_id.to_owned());
108 111 action_row("chat-members-add", IconName::UserPlus, "Add people")
109 .opacity(0.5)
110 .cursor_default(),
111 )
112 .cursor_pointer()
113 .hover(|row| row.bg(theme::popup_hover()))
114 .on_click(move |_, window, cx| {
115 popover.update(cx, |state, cx| state.dismiss(window, cx));
116 open_add_people(&app, &chat_id, false, window, cx);
117 })
118 })
112 119 .when(leave_allowed, |actions| {
113 120 let (app, popover, chat_id) =
114 121 (app.clone(), popover.clone(), chat_id.to_owned());
@@ -6,6 +6,7 @@ use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
7use gpui_kit::*;
8
8
9use super::add_people_dialog::open_add_people;
9use super::avatar::{person_avatar, with_presence};
10use super::avatar::{person_avatar, with_presence};
10use super::profile_card::opens_profile;
11use super::profile_card::opens_profile;
11use super::sidebar::confirm_leave;
12use super::sidebar::confirm_leave;
@@ -104,11 +105,17 @@ fn members_panel(
104 .child(
105 .child(
105 v_flex()
106 v_flex()
106 .py(px(4.))
107 .py(px(4.))
107 .child(
108 .child({
109 let (app, popover, chat_id) =
110 (app.clone(), popover.clone(), chat_id.to_owned());
108 action_row("chat-members-add", IconName::UserPlus, "Add people")
111 action_row("chat-members-add", IconName::UserPlus, "Add people")
109 .opacity(0.5)
112 .cursor_pointer()
110 .cursor_default(),
113 .hover(|row| row.bg(theme::popup_hover()))
111 )
114 .on_click(move |_, window, cx| {
115 popover.update(cx, |state, cx| state.dismiss(window, cx));
116 open_add_people(&app, &chat_id, false, window, cx);
117 })
118 })
112 .when(leave_allowed, |actions| {
119 .when(leave_allowed, |actions| {
113 let (app, popover, chat_id) =
120 let (app, popover, chat_id) =
114 (app.clone(), popover.clone(), chat_id.to_owned());
121 (app.clone(), popover.clone(), chat_id.to_owned());
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/conversation.rs +44 −46
@@ -23,8 +23,10 @@ use teams_core::{
23 23
24 24 mod channel_details;
25 25 pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
26 mod deletes;
26 27 mod detached;
27 28 mod feed;
29 mod jump;
28 30 mod pins;
29 31 mod proposal;
30 32 mod recap;
@@ -39,11 +41,12 @@ use super::avatar::{
39 41 };
40 42 use super::call_controls::header_call_controls;
41 43 use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
44 use super::add_people_dialog::open_add_people;
42 45 use super::chat_members::members_popover;
43 46 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
44 47 use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
45 48 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
46 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder};
49 use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
47 50 use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
48 51 use super::post_card::render_post;
49 52 use super::profile_card::opens_profile;
@@ -936,6 +939,23 @@ impl ConversationView {
936 939 self.on_draft_changed(window, cx);
937 940 self.rebuild(true, cx);
938 941 }
942 let people = self
943 .app
944 .update(cx, |state, _| std::mem::take(&mut state.new_chat_people));
945 if !people.is_empty() {
946 let chips = people
947 .into_iter()
948 .filter_map(|person| {
949 Some(Pick {
950 user_id: person.user_id?,
951 name: person.display_name,
952 mail: None,
953 })
954 })
955 .collect();
956 self.draft
957 .update(cx, |draft, cx| draft.set_chips(chips, cx));
958 }
939 959 self.draft
940 960 .update(cx, |draft, cx| draft.focus_query(window, cx));
941 961 cx.notify();
@@ -2797,31 +2817,6 @@ impl ConversationView {
2797 2817 .detach();
2798 2818 }
2799 2819
2800 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2801 let Some(mut record) = self.own_record(message_id, cx) else {
2802 return;
2803 };
2804 let state = self.app.read(cx);
2805 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2806 if mode.demo {
2807 record.deleted = true;
2808 let _ = store.upsert_messages(std::slice::from_ref(&record));
2809 self.rebuild(false, cx);
2810 return;
2811 }
2812 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2813 self.show_notice("Read-only mode: message not deleted", cx);
2814 return;
2815 };
2816 let conversation_id = record.conversation_id.clone();
2817 let receiver = runtime::spawn(async move {
2818 engine
2819 .soft_delete_message(&conversation_id, &record.message_id)
2820 .await
2821 });
2822 self.report_failure(receiver, "Delete failed", cx);
2823 }
2824
2825 2820 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2826 2821 let Some(conversation_id) = self.conversation_id() else {
2827 2822 return;
@@ -2869,26 +2864,6 @@ impl ConversationView {
2869 2864 });
2870 2865 }
2871 2866
2872 fn report_failure(
2873 &mut self,
2874 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2875 label: &'static str,
2876 cx: &mut Context<Self>,
2877 ) {
2878 cx.spawn(async move |this, cx| {
2879 let error = match receiver.await {
2880 Ok(Ok(())) => return,
2881 Ok(Err(error)) => short_error(&error),
2882 Err(_) => "cancelled".to_owned(),
2883 };
2884 this.update(cx, |this, cx| {
2885 this.show_notice(&format!("{label}: {error}"), cx)
2886 })
2887 .ok();
2888 })
2889 .detach();
2890 }
2891
2892 2867 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2893 2868 let (Some(conversation_id), Some(runs)) =
2894 2869 (self.conversation_id(), crate::agents::runs_handle(cx))
@@ -3310,6 +3285,9 @@ impl ConversationView {
3310 3285 }
3311 3286 _ => String::new(),
3312 3287 };
3288 if is_one_on_one(chat) {
3289 stack = Some(add_people_button(&self.app, chat_id));
3290 }
3313 3291 } else {
3314 3292 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3315 3293 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
@@ -3577,6 +3555,15 @@ impl Render for ConversationView {
3577 3555 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3578 3556 .jump_button(!in_feed)
3579 3557 .force_jump_button(detached)
3558 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3559 .with_jump_button_renderer(|button| {
3560 button
3561 .label(jump::JUMP_TO_NEWEST_LABEL)
3562 .tooltip(jump::jump_to_newest_tooltip())
3563 .border_0()
3564 .bg(theme::accent())
3565 .text_color(theme::on_accent())
3566 })
3580 3567 .when(detached, |scroller| {
3581 3568 let view = cx.weak_entity();
3582 3569 scroller.on_jump(move |_, cx| {
@@ -3780,6 +3767,17 @@ fn progress_bar() -> impl IntoElement {
3780 3767 )
3781 3768 }
3782 3769
3770 fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
3771 let (app, chat_id) = (app.clone(), chat_id.to_owned());
3772 Button::new("chat-add-people")
3773 .ghost()
3774 .compact()
3775 .icon(IconName::UserPlus)
3776 .tooltip("Add people")
3777 .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
3778 .into_any_element()
3779 }
3780
3783 3781 #[cfg(test)]
3784 3782 mod tests {
3785 3783 use std::sync::Arc;
@@ -23,8 +23,10 @@ use teams_core::{
23
23
24mod channel_details;
24mod channel_details;
25pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
25pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
26mod deletes;
26mod detached;
27mod detached;
27mod feed;
28mod feed;
29mod jump;
28mod pins;
30mod pins;
29mod proposal;
31mod proposal;
30mod recap;
32mod recap;
@@ -39,11 +41,12 @@ use super::avatar::{
39};
41};
40use super::call_controls::header_call_controls;
42use super::call_controls::header_call_controls;
41use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
43use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
44use super::add_people_dialog::open_add_people;
42use super::chat_members::members_popover;
45use super::chat_members::members_popover;
43use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
46use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
44use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
47use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
45use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
48use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
46use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder};
49use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
47use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
50use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
48use super::post_card::render_post;
51use super::post_card::render_post;
49use super::profile_card::opens_profile;
52use super::profile_card::opens_profile;
@@ -936,6 +939,23 @@ impl ConversationView {
936 self.on_draft_changed(window, cx);
939 self.on_draft_changed(window, cx);
937 self.rebuild(true, cx);
940 self.rebuild(true, cx);
938 }
941 }
942 let people = self
943 .app
944 .update(cx, |state, _| std::mem::take(&mut state.new_chat_people));
945 if !people.is_empty() {
946 let chips = people
947 .into_iter()
948 .filter_map(|person| {
949 Some(Pick {
950 user_id: person.user_id?,
951 name: person.display_name,
952 mail: None,
953 })
954 })
955 .collect();
956 self.draft
957 .update(cx, |draft, cx| draft.set_chips(chips, cx));
958 }
939 self.draft
959 self.draft
940 .update(cx, |draft, cx| draft.focus_query(window, cx));
960 .update(cx, |draft, cx| draft.focus_query(window, cx));
941 cx.notify();
961 cx.notify();
@@ -2797,31 +2817,6 @@ impl ConversationView {
2797 .detach();
2817 .detach();
2798 }
2818 }
2799
2819
2800 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2801 let Some(mut record) = self.own_record(message_id, cx) else {
2802 return;
2803 };
2804 let state = self.app.read(cx);
2805 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2806 if mode.demo {
2807 record.deleted = true;
2808 let _ = store.upsert_messages(std::slice::from_ref(&record));
2809 self.rebuild(false, cx);
2810 return;
2811 }
2812 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2813 self.show_notice("Read-only mode: message not deleted", cx);
2814 return;
2815 };
2816 let conversation_id = record.conversation_id.clone();
2817 let receiver = runtime::spawn(async move {
2818 engine
2819 .soft_delete_message(&conversation_id, &record.message_id)
2820 .await
2821 });
2822 self.report_failure(receiver, "Delete failed", cx);
2823 }
2824
2825 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2820 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2826 let Some(conversation_id) = self.conversation_id() else {
2821 let Some(conversation_id) = self.conversation_id() else {
2827 return;
2822 return;
@@ -2869,26 +2864,6 @@ impl ConversationView {
2869 });
2864 });
2870 }
2865 }
2871
2866
2872 fn report_failure(
2873 &mut self,
2874 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2875 label: &'static str,
2876 cx: &mut Context<Self>,
2877 ) {
2878 cx.spawn(async move |this, cx| {
2879 let error = match receiver.await {
2880 Ok(Ok(())) => return,
2881 Ok(Err(error)) => short_error(&error),
2882 Err(_) => "cancelled".to_owned(),
2883 };
2884 this.update(cx, |this, cx| {
2885 this.show_notice(&format!("{label}: {error}"), cx)
2886 })
2887 .ok();
2888 })
2889 .detach();
2890 }
2891
2892 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2867 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2893 let (Some(conversation_id), Some(runs)) =
2868 let (Some(conversation_id), Some(runs)) =
2894 (self.conversation_id(), crate::agents::runs_handle(cx))
2869 (self.conversation_id(), crate::agents::runs_handle(cx))
@@ -3310,6 +3285,9 @@ impl ConversationView {
3310 }
3285 }
3311 _ => String::new(),
3286 _ => String::new(),
3312 };
3287 };
3288 if is_one_on_one(chat) {
3289 stack = Some(add_people_button(&self.app, chat_id));
3290 }
3313 } else {
3291 } else {
3314 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3292 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3315 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3293 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
@@ -3577,6 +3555,15 @@ impl Render for ConversationView {
3577 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3555 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3578 .jump_button(!in_feed)
3556 .jump_button(!in_feed)
3579 .force_jump_button(detached)
3557 .force_jump_button(detached)
3558 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3559 .with_jump_button_renderer(|button| {
3560 button
3561 .label(jump::JUMP_TO_NEWEST_LABEL)
3562 .tooltip(jump::jump_to_newest_tooltip())
3563 .border_0()
3564 .bg(theme::accent())
3565 .text_color(theme::on_accent())
3566 })
3580 .when(detached, |scroller| {
3567 .when(detached, |scroller| {
3581 let view = cx.weak_entity();
3568 let view = cx.weak_entity();
3582 scroller.on_jump(move |_, cx| {
3569 scroller.on_jump(move |_, cx| {
@@ -3780,6 +3767,17 @@ fn progress_bar() -> impl IntoElement {
3780 )
3767 )
3781}
3768}
3782
3769
3770fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
3771 let (app, chat_id) = (app.clone(), chat_id.to_owned());
3772 Button::new("chat-add-people")
3773 .ghost()
3774 .compact()
3775 .icon(IconName::UserPlus)
3776 .tooltip("Add people")
3777 .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
3778 .into_any_element()
3779}
3780
3783#[cfg(test)]
3781#[cfg(test)]
3784mod tests {
3782mod tests {
3785 use std::sync::Arc;
3783 use std::sync::Arc;
crates/app/src/views/conversation/deletes.rs added +124 −0
@@ -0,0 +1,124 @@
1 use gpui_kit::*;
2 use store::MessageRecord;
3
4 use super::ConversationView;
5 use crate::notice::short_error;
6 use crate::restorable_deletes::RESTORE_FAILED_NOTICE;
7 use crate::runtime;
8
9 impl ConversationView {
10 pub(super) fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
11 let Some(record) = self.own_record(message_id, cx) else {
12 return;
13 };
14 let state = self.app.read(cx);
15 let (mode, engine) = (state.mode, state.engine.clone());
16 if mode.demo {
17 self.remember_delete(&record, cx);
18 self.store_deleted(record, true, cx);
19 return;
20 }
21 let Some(engine) = engine.filter(|_| !mode.read_only) else {
22 self.show_notice("Read-only mode: message not deleted", cx);
23 return;
24 };
25 self.remember_delete(&record, cx);
26 let (conversation_id, message_id) = (record.conversation_id, record.message_id);
27 let (failed_conversation, failed_message) = (conversation_id.clone(), message_id.clone());
28 let receiver = runtime::spawn(async move {
29 engine
30 .soft_delete_message(&conversation_id, &message_id)
31 .await
32 });
33 cx.spawn(async move |this, cx| {
34 let error = match receiver.await {
35 Ok(Ok(())) => return,
36 Ok(Err(error)) => short_error(&error),
37 Err(_) => "cancelled".to_owned(),
38 };
39 this.update(cx, |this, cx| {
40 this.app.update(cx, |state, _| {
41 state
42 .restorable_deletes
43 .forget(&failed_conversation, &failed_message)
44 });
45 this.show_notice(&format!("Delete failed: {error}"), cx);
46 })
47 .ok();
48 })
49 .detach();
50 }
51
52 pub(super) fn undo_delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
53 let Some(record) = self.deleted_own_record(message_id, cx) else {
54 return;
55 };
56 let state = self.app.read(cx);
57 let (mode, engine) = (state.mode, state.engine.clone());
58 if mode.read_only && !mode.demo {
59 return;
60 }
61 let forgotten = self.app.update(cx, |state, _| {
62 state
63 .restorable_deletes
64 .forget(&record.conversation_id, &record.message_id)
65 });
66 if !forgotten {
67 return;
68 }
69 let engine = engine.filter(|_| !mode.demo);
70 self.store_deleted(record.clone(), false, cx);
71 let Some(engine) = engine else {
72 return;
73 };
74 let (conversation_id, message_id) =
75 (record.conversation_id.clone(), record.message_id.clone());
76 let receiver = runtime::spawn(async move {
77 engine
78 .undo_soft_delete_message(&conversation_id, &message_id)
79 .await
80 });
81 cx.spawn(async move |this, cx| {
82 if matches!(receiver.await, Ok(Ok(()))) {
83 return;
84 }
85 this.update(cx, |this, cx| {
86 this.remember_delete(&record, cx);
87 this.store_deleted(record, true, cx);
88 this.show_notice(RESTORE_FAILED_NOTICE, cx);
89 })
90 .ok();
91 })
92 .detach();
93 }
94
95 fn remember_delete(&mut self, record: &MessageRecord, cx: &mut Context<Self>) {
96 self.app.update(cx, |state, _| {
97 state
98 .restorable_deletes
99 .remember(&record.conversation_id, &record.message_id)
100 });
101 }
102
103 fn store_deleted(&mut self, mut record: MessageRecord, deleted: bool, cx: &mut Context<Self>) {
104 record.deleted = deleted;
105 let _ = self
106 .app
107 .read(cx)
108 .store
109 .upsert_messages(std::slice::from_ref(&record));
110 self.rebuild(false, cx);
111 }
112
113 fn deleted_own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
114 let conversation_id = self.conversation_id()?;
115 let my_user_id = self.row_context(cx).my_user_id?;
116 self.app
117 .read(cx)
118 .store
119 .messages_by_id(&conversation_id, &[message_id.to_owned()])
120 .ok()?
121 .remove(message_id)
122 .filter(|record| record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
123 }
124 }
@@ -0,0 +1,124 @@
1use gpui_kit::*;
2use store::MessageRecord;
3
4use super::ConversationView;
5use crate::notice::short_error;
6use crate::restorable_deletes::RESTORE_FAILED_NOTICE;
7use crate::runtime;
8
9impl ConversationView {
10 pub(super) fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
11 let Some(record) = self.own_record(message_id, cx) else {
12 return;
13 };
14 let state = self.app.read(cx);
15 let (mode, engine) = (state.mode, state.engine.clone());
16 if mode.demo {
17 self.remember_delete(&record, cx);
18 self.store_deleted(record, true, cx);
19 return;
20 }
21 let Some(engine) = engine.filter(|_| !mode.read_only) else {
22 self.show_notice("Read-only mode: message not deleted", cx);
23 return;
24 };
25 self.remember_delete(&record, cx);
26 let (conversation_id, message_id) = (record.conversation_id, record.message_id);
27 let (failed_conversation, failed_message) = (conversation_id.clone(), message_id.clone());
28 let receiver = runtime::spawn(async move {
29 engine
30 .soft_delete_message(&conversation_id, &message_id)
31 .await
32 });
33 cx.spawn(async move |this, cx| {
34 let error = match receiver.await {
35 Ok(Ok(())) => return,
36 Ok(Err(error)) => short_error(&error),
37 Err(_) => "cancelled".to_owned(),
38 };
39 this.update(cx, |this, cx| {
40 this.app.update(cx, |state, _| {
41 state
42 .restorable_deletes
43 .forget(&failed_conversation, &failed_message)
44 });
45 this.show_notice(&format!("Delete failed: {error}"), cx);
46 })
47 .ok();
48 })
49 .detach();
50 }
51
52 pub(super) fn undo_delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
53 let Some(record) = self.deleted_own_record(message_id, cx) else {
54 return;
55 };
56 let state = self.app.read(cx);
57 let (mode, engine) = (state.mode, state.engine.clone());
58 if mode.read_only && !mode.demo {
59 return;
60 }
61 let forgotten = self.app.update(cx, |state, _| {
62 state
63 .restorable_deletes
64 .forget(&record.conversation_id, &record.message_id)
65 });
66 if !forgotten {
67 return;
68 }
69 let engine = engine.filter(|_| !mode.demo);
70 self.store_deleted(record.clone(), false, cx);
71 let Some(engine) = engine else {
72 return;
73 };
74 let (conversation_id, message_id) =
75 (record.conversation_id.clone(), record.message_id.clone());
76 let receiver = runtime::spawn(async move {
77 engine
78 .undo_soft_delete_message(&conversation_id, &message_id)
79 .await
80 });
81 cx.spawn(async move |this, cx| {
82 if matches!(receiver.await, Ok(Ok(()))) {
83 return;
84 }
85 this.update(cx, |this, cx| {
86 this.remember_delete(&record, cx);
87 this.store_deleted(record, true, cx);
88 this.show_notice(RESTORE_FAILED_NOTICE, cx);
89 })
90 .ok();
91 })
92 .detach();
93 }
94
95 fn remember_delete(&mut self, record: &MessageRecord, cx: &mut Context<Self>) {
96 self.app.update(cx, |state, _| {
97 state
98 .restorable_deletes
99 .remember(&record.conversation_id, &record.message_id)
100 });
101 }
102
103 fn store_deleted(&mut self, mut record: MessageRecord, deleted: bool, cx: &mut Context<Self>) {
104 record.deleted = deleted;
105 let _ = self
106 .app
107 .read(cx)
108 .store
109 .upsert_messages(std::slice::from_ref(&record));
110 self.rebuild(false, cx);
111 }
112
113 fn deleted_own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
114 let conversation_id = self.conversation_id()?;
115 let my_user_id = self.row_context(cx).my_user_id?;
116 self.app
117 .read(cx)
118 .store
119 .messages_by_id(&conversation_id, &[message_id.to_owned()])
120 .ok()?
121 .remove(message_id)
122 .filter(|record| record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
123 }
124}
crates/app/src/views/conversation/jump.rs added +46 −0
@@ -0,0 +1,46 @@
1 use gpui_kit::*;
2
3 use super::ConversationView;
4 use crate::read_state::{JumpTarget, jump_target};
5 use crate::rows::Row;
6 use crate::views::shortcuts::keys_for_label;
7
8 pub(super) const JUMP_TO_NEWEST_LABEL: &str = "Jump to newest";
9 const JUMP_SHORTCUT_LABEL: &str = "Jump to last read or newest message";
10
11 pub(super) fn jump_to_newest_tooltip() -> SharedString {
12 match keys_for_label(JUMP_SHORTCUT_LABEL) {
13 Some(keys) => format!("{JUMP_TO_NEWEST_LABEL} ({keys})").into(),
14 None => JUMP_TO_NEWEST_LABEL.into(),
15 }
16 }
17
18 impl ConversationView {
19 pub fn jump_to_last_read_or_newest(&mut self, cx: &mut Context<Self>) {
20 if self.current.is_none() || self.in_feed() {
21 return;
22 }
23 if self.is_detached() {
24 self.leave_detached(cx);
25 return;
26 }
27 let last_read_index = self
28 .rows
29 .borrow()
30 .iter()
31 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
32 let (top_item, scrolled_up) = {
33 let scroller = self.scroller.read(cx);
34 (scroller.top_item(), scroller.is_scrolled_up())
35 };
36 let Some(target) = jump_target(last_read_index, top_item, scrolled_up) else {
37 return;
38 };
39 self.scroller.update(cx, |scroller, cx| match target {
40 JumpTarget::Newest => scroller.scroll_to_end(cx),
41 JumpTarget::LastRead(index) => {
42 scroller.scroll_to_item(index, cx);
43 }
44 });
45 }
46 }
@@ -0,0 +1,46 @@
1use gpui_kit::*;
2
3use super::ConversationView;
4use crate::read_state::{JumpTarget, jump_target};
5use crate::rows::Row;
6use crate::views::shortcuts::keys_for_label;
7
8pub(super) const JUMP_TO_NEWEST_LABEL: &str = "Jump to newest";
9const JUMP_SHORTCUT_LABEL: &str = "Jump to last read or newest message";
10
11pub(super) fn jump_to_newest_tooltip() -> SharedString {
12 match keys_for_label(JUMP_SHORTCUT_LABEL) {
13 Some(keys) => format!("{JUMP_TO_NEWEST_LABEL} ({keys})").into(),
14 None => JUMP_TO_NEWEST_LABEL.into(),
15 }
16}
17
18impl ConversationView {
19 pub fn jump_to_last_read_or_newest(&mut self, cx: &mut Context<Self>) {
20 if self.current.is_none() || self.in_feed() {
21 return;
22 }
23 if self.is_detached() {
24 self.leave_detached(cx);
25 return;
26 }
27 let last_read_index = self
28 .rows
29 .borrow()
30 .iter()
31 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
32 let (top_item, scrolled_up) = {
33 let scroller = self.scroller.read(cx);
34 (scroller.top_item(), scroller.is_scrolled_up())
35 };
36 let Some(target) = jump_target(last_read_index, top_item, scrolled_up) else {
37 return;
38 };
39 self.scroller.update(cx, |scroller, cx| match target {
40 JumpTarget::Newest => scroller.scroll_to_end(cx),
41 JumpTarget::LastRead(index) => {
42 scroller.scroll_to_item(index, cx);
43 }
44 });
45 }
46}
crates/app/src/views/conversation/render_env.rs +24 −1
@@ -22,7 +22,7 @@ use crate::views::attachments::ImageActions;
22 22 use crate::views::call_card::CallActions;
23 23 use crate::views::call_notice::RecapActions;
24 24 use crate::views::composer::Composer;
25 use crate::views::message_row::{DeliveryActions, RowActions};
25 use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
26 26 use crate::views::post_card::{PostAction, PostActions};
27 27 use crate::views::reaction_proposal_pill::ReactionPill;
28 28 use crate::views::toolbar_placement::TimelineBounds;
@@ -313,9 +313,32 @@ impl RenderEnv {
313 313 agent_run: actionable_run,
314 314 call: self.call_actions(message, cx),
315 315 reaction_proposal,
316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
316 317 }
317 318 }
318 319
320 fn undo_delete_action(
321 &self,
322 message: &MessageRow,
323 is_real: bool,
324 view: &WeakEntity<ConversationView>,
325 cx: &App,
326 ) -> SharedRowAction {
327 let restorable = is_real
328 && self.app.read(cx).restorable_deletes.can_undo(
329 &message.conversation_id,
330 &message.key,
331 message.own,
332 message.deleted,
333 );
334 restorable.then(|| {
335 let (view, key) = (view.clone(), message.key.clone());
336 Rc::new(move |cx: &mut App| {
337 view.update(cx, |this, cx| this.undo_delete(&key, cx)).ok();
338 }) as Rc<dyn Fn(&mut App)>
339 })
340 }
341
319 342 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
320 343 let Some(call) = &message.call else {
321 344 return CallActions::none();
@@ -22,7 +22,7 @@ use crate::views::attachments::ImageActions;
22use crate::views::call_card::CallActions;
22use crate::views::call_card::CallActions;
23use crate::views::call_notice::RecapActions;
23use crate::views::call_notice::RecapActions;
24use crate::views::composer::Composer;
24use crate::views::composer::Composer;
25use crate::views::message_row::{DeliveryActions, RowActions};
25use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
26use crate::views::post_card::{PostAction, PostActions};
26use crate::views::post_card::{PostAction, PostActions};
27use crate::views::reaction_proposal_pill::ReactionPill;
27use crate::views::reaction_proposal_pill::ReactionPill;
28use crate::views::toolbar_placement::TimelineBounds;
28use crate::views::toolbar_placement::TimelineBounds;
@@ -313,9 +313,32 @@ impl RenderEnv {
313 agent_run: actionable_run,
313 agent_run: actionable_run,
314 call: self.call_actions(message, cx),
314 call: self.call_actions(message, cx),
315 reaction_proposal,
315 reaction_proposal,
316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
316 }
317 }
317 }
318 }
318
319
320 fn undo_delete_action(
321 &self,
322 message: &MessageRow,
323 is_real: bool,
324 view: &WeakEntity<ConversationView>,
325 cx: &App,
326 ) -> SharedRowAction {
327 let restorable = is_real
328 && self.app.read(cx).restorable_deletes.can_undo(
329 &message.conversation_id,
330 &message.key,
331 message.own,
332 message.deleted,
333 );
334 restorable.then(|| {
335 let (view, key) = (view.clone(), message.key.clone());
336 Rc::new(move |cx: &mut App| {
337 view.update(cx, |this, cx| this.undo_delete(&key, cx)).ok();
338 }) as Rc<dyn Fn(&mut App)>
339 })
340 }
341
319 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
342 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
320 let Some(call) = &message.call else {
343 let Some(call) = &message.call else {
321 return CallActions::none();
344 return CallActions::none();
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/message_row.rs +35 −4
@@ -23,12 +23,14 @@ use crate::agents::{AgentRun, run_chip};
23 23 use crate::card_state::BotIdentity;
24 24 use crate::data::Directory;
25 25 use crate::render::Block;
26 use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
26 27 use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
27 28 use crate::sidebar_model::DELETED_PREVIEW;
28 29 use crate::theme;
29 30 use app_ui_kit::layout::ROW_PADDING;
30 31
31 32 pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
33 pub type SharedRowAction = Option<std::rc::Rc<dyn Fn(&mut App)>>;
32 34
33 35 pub const BUBBLE_TAGS: [&str; 12] = [
34 36 "message-bubble/0",
@@ -86,6 +88,7 @@ pub struct RowActions {
86 88 pub agent_run: Option<AgentRun>,
87 89 pub call: CallActions,
88 90 pub reaction_proposal: Option<ReactionPill>,
91 pub undo_delete: SharedRowAction,
89 92 }
90 93
91 94 const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -122,6 +125,34 @@ pub(super) fn new_marker() -> Div {
122 125 )
123 126 }
124 127
128 pub(super) fn deleted_tombstone(index: usize, undo_delete: SharedRowAction) -> Div {
129 let line =
130 h_flex()
131 .gap(px(8.))
132 .items_baseline()
133 .text_size(px(13.))
134 .child(div().italic().text_color(theme::text_muted()).child(
135 if undo_delete.is_some() {
136 DELETED_TOMBSTONE
137 } else {
138 DELETED_PREVIEW
139 },
140 ));
141 match undo_delete {
142 Some(undo) => line.child(
143 div()
144 .id(ElementId::Name(format!("undo-delete-{index}").into()))
145 .cursor_pointer()
146 .font_weight(FontWeight::SEMIBOLD)
147 .text_color(theme::accent_text())
148 .hover(|link| link.underline())
149 .child(UNDO_DELETE_LABEL)
150 .on_click(move |_, _, cx| undo(cx)),
151 ),
152 None => line,
153 }
154 }
155
125 156 fn bubble_max_width(timeline: &TimelineBounds, reserved: f32) -> Length {
126 157 let Some(bounds) = timeline.get() else {
127 158 return relative(MAX_WIDTH_RATIO).into();
@@ -168,10 +199,7 @@ fn bubble(
168 199 .border_1()
169 200 .border_color(theme::border_strong())
170 201 .py(px(6.))
171 .text_size(px(13.))
172 .italic()
173 .text_color(theme::text_muted())
174 .child(DELETED_PREVIEW);
202 .child(deleted_tombstone(index, extras.undo_delete));
175 203 }
176 204 let failed = matches!(row.delivery, Delivery::Failed(_));
177 205 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
@@ -319,6 +347,7 @@ struct BubbleExtras {
319 347 timeline: TimelineBounds,
320 348 agent_run: Option<AgentRun>,
321 349 reaction_proposal: Option<ReactionPill>,
350 undo_delete: SharedRowAction,
322 351 }
323 352
324 353 fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -655,6 +684,7 @@ pub fn render_message_row(
655 684 call: _,
656 685 pinned: _,
657 686 reaction_proposal,
687 undo_delete,
658 688 } = actions;
659 689 let extras = BubbleExtras {
660 690 hover: hovered,
@@ -669,6 +699,7 @@ pub fn render_message_row(
669 699 timeline,
670 700 agent_run,
671 701 reaction_proposal,
702 undo_delete,
672 703 };
673 704 let own = row.own;
674 705 let spacing = if row.series.has_prev {
@@ -23,12 +23,14 @@ use crate::agents::{AgentRun, run_chip};
23use crate::card_state::BotIdentity;
23use crate::card_state::BotIdentity;
24use crate::data::Directory;
24use crate::data::Directory;
25use crate::render::Block;
25use crate::render::Block;
26use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
26use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
27use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
27use crate::sidebar_model::DELETED_PREVIEW;
28use crate::sidebar_model::DELETED_PREVIEW;
28use crate::theme;
29use crate::theme;
29use app_ui_kit::layout::ROW_PADDING;
30use app_ui_kit::layout::ROW_PADDING;
30
31
31pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
32pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
33pub type SharedRowAction = Option<std::rc::Rc<dyn Fn(&mut App)>>;
32
34
33pub const BUBBLE_TAGS: [&str; 12] = [
35pub const BUBBLE_TAGS: [&str; 12] = [
34 "message-bubble/0",
36 "message-bubble/0",
@@ -86,6 +88,7 @@ pub struct RowActions {
86 pub agent_run: Option<AgentRun>,
88 pub agent_run: Option<AgentRun>,
87 pub call: CallActions,
89 pub call: CallActions,
88 pub reaction_proposal: Option<ReactionPill>,
90 pub reaction_proposal: Option<ReactionPill>,
91 pub undo_delete: SharedRowAction,
89}
92}
90
93
91const TOOLBAR_RIGHT_INSET: f32 = 0.;
94const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -122,6 +125,34 @@ pub(super) fn new_marker() -> Div {
122 )
125 )
123}
126}
124
127
128pub(super) fn deleted_tombstone(index: usize, undo_delete: SharedRowAction) -> Div {
129 let line =
130 h_flex()
131 .gap(px(8.))
132 .items_baseline()
133 .text_size(px(13.))
134 .child(div().italic().text_color(theme::text_muted()).child(
135 if undo_delete.is_some() {
136 DELETED_TOMBSTONE
137 } else {
138 DELETED_PREVIEW
139 },
140 ));
141 match undo_delete {
142 Some(undo) => line.child(
143 div()
144 .id(ElementId::Name(format!("undo-delete-{index}").into()))
145 .cursor_pointer()
146 .font_weight(FontWeight::SEMIBOLD)
147 .text_color(theme::accent_text())
148 .hover(|link| link.underline())
149 .child(UNDO_DELETE_LABEL)
150 .on_click(move |_, _, cx| undo(cx)),
151 ),
152 None => line,
153 }
154}
155
125fn bubble_max_width(timeline: &TimelineBounds, reserved: f32) -> Length {
156fn bubble_max_width(timeline: &TimelineBounds, reserved: f32) -> Length {
126 let Some(bounds) = timeline.get() else {
157 let Some(bounds) = timeline.get() else {
127 return relative(MAX_WIDTH_RATIO).into();
158 return relative(MAX_WIDTH_RATIO).into();
@@ -168,10 +199,7 @@ fn bubble(
168 .border_1()
199 .border_1()
169 .border_color(theme::border_strong())
200 .border_color(theme::border_strong())
170 .py(px(6.))
201 .py(px(6.))
171 .text_size(px(13.))
202 .child(deleted_tombstone(index, extras.undo_delete));
172 .italic()
173 .text_color(theme::text_muted())
174 .child(DELETED_PREVIEW);
175 }
203 }
176 let failed = matches!(row.delivery, Delivery::Failed(_));
204 let failed = matches!(row.delivery, Delivery::Failed(_));
177 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
205 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
@@ -319,6 +347,7 @@ struct BubbleExtras {
319 timeline: TimelineBounds,
347 timeline: TimelineBounds,
320 agent_run: Option<AgentRun>,
348 agent_run: Option<AgentRun>,
321 reaction_proposal: Option<ReactionPill>,
349 reaction_proposal: Option<ReactionPill>,
350 undo_delete: SharedRowAction,
322}
351}
323
352
324fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
353fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -655,6 +684,7 @@ pub fn render_message_row(
655 call: _,
684 call: _,
656 pinned: _,
685 pinned: _,
657 reaction_proposal,
686 reaction_proposal,
687 undo_delete,
658 } = actions;
688 } = actions;
659 let extras = BubbleExtras {
689 let extras = BubbleExtras {
660 hover: hovered,
690 hover: hovered,
@@ -669,6 +699,7 @@ pub fn render_message_row(
669 timeline,
699 timeline,
670 agent_run,
700 agent_run,
671 reaction_proposal,
701 reaction_proposal,
702 undo_delete,
672 };
703 };
673 let own = row.own;
704 let own = row.own;
674 let spacing = if row.series.has_prev {
705 let spacing = if row.series.has_prev {
crates/app/src/views/mod.rs +3 −0
@@ -1,6 +1,7 @@
1 1 pub mod actions;
2 2 pub mod activity_panel;
3 3 pub mod adaptive_card;
4 pub mod add_people_dialog;
4 5 pub mod attachment_tray;
5 6 pub mod attachments;
6 7 pub mod avatar;
@@ -17,6 +18,7 @@ pub mod call_mini_window;
17 18 pub mod call_organizer;
18 19 pub mod call_people;
19 20 pub mod call_pop_out;
21 pub mod call_share_gallery;
20 22 pub mod call_record;
21 23 pub mod call_stage;
22 24 pub mod call_transcript;
@@ -77,6 +79,7 @@ pub mod title_bar;
77 79 pub mod toolbar_placement;
78 80 pub mod transfer_picker;
79 81 pub mod translation_line;
82 pub mod window_zoom;
80 83
81 84 pub use app_ui_kit::{
82 85 card_chart, channel_tabs, draft_style, reaction_proposal_pill, scroll_edge, widgets,
@@ -1,6 +1,7 @@
1pub mod actions;
1pub mod actions;
2pub mod activity_panel;
2pub mod activity_panel;
3pub mod adaptive_card;
3pub mod adaptive_card;
4pub mod add_people_dialog;
4pub mod attachment_tray;
5pub mod attachment_tray;
5pub mod attachments;
6pub mod attachments;
6pub mod avatar;
7pub mod avatar;
@@ -17,6 +18,7 @@ pub mod call_mini_window;
17pub mod call_organizer;
18pub mod call_organizer;
18pub mod call_people;
19pub mod call_people;
19pub mod call_pop_out;
20pub mod call_pop_out;
21pub mod call_share_gallery;
20pub mod call_record;
22pub mod call_record;
21pub mod call_stage;
23pub mod call_stage;
22pub mod call_transcript;
24pub mod call_transcript;
@@ -77,6 +79,7 @@ pub mod title_bar;
77pub mod toolbar_placement;
79pub mod toolbar_placement;
78pub mod transfer_picker;
80pub mod transfer_picker;
79pub mod translation_line;
81pub mod translation_line;
82pub mod window_zoom;
80
83
81pub use app_ui_kit::{
84pub use app_ui_kit::{
82 card_chart, channel_tabs, draft_style, reaction_proposal_pill, scroll_edge, widgets,
85 card_chart, channel_tabs, draft_style, reaction_proposal_pill, scroll_edge, widgets,
crates/app/src/views/new_chat.rs +39 −3
@@ -84,6 +84,13 @@ fn not_chosen(pick: &Pick, me: Option<&Person>, chosen: &[Pick]) -> bool {
84 84 && chosen.iter().all(|chip| chip.user_id != pick.user_id)
85 85 }
86 86
87 fn without_excluded(picks: Vec<Pick>, excluded: &[String]) -> Vec<Pick> {
88 picks
89 .into_iter()
90 .filter(|pick| !excluded.contains(&pick.user_id))
91 .collect()
92 }
93
87 94 pub fn suggested_people(
88 95 chats: &[ChatRecord],
89 96 me: Option<&Person>,
@@ -158,6 +165,7 @@ pub struct NewChatDraft {
158 165 query: Entity<InputState>,
159 166 name: Entity<InputState>,
160 167 chips: Vec<Pick>,
168 excluded: Vec<String>,
161 169 form_field: bool,
162 170 remote: Vec<Pick>,
163 171 highlighted: usize,
@@ -184,6 +192,7 @@ impl NewChatDraft {
184 192 query,
185 193 name,
186 194 chips: Vec::new(),
195 excluded: Vec::new(),
187 196 form_field: false,
188 197 remote: Vec::new(),
189 198 highlighted: 0,
@@ -202,10 +211,22 @@ impl NewChatDraft {
202 211 self
203 212 }
204 213
214 pub fn excluding(mut self, user_ids: Vec<String>) -> Self {
215 self.excluded = user_ids;
216 self
217 }
218
205 219 pub fn chips(&self) -> &[Pick] {
206 220 &self.chips
207 221 }
208 222
223 pub fn set_chips(&mut self, chips: Vec<Pick>, cx: &mut Context<Self>) {
224 self.chips = chips;
225 self.highlighted = 0;
226 cx.emit(NewChatEvent::Changed);
227 cx.notify();
228 }
229
209 230 pub fn group_name(&self, cx: &App) -> String {
210 231 self.name.read(cx).value().trim().to_owned()
211 232 }
@@ -246,11 +267,19 @@ impl NewChatDraft {
246 267 let me = state.directory.me.as_ref();
247 268 let query = self.query_text(cx);
248 269 if query.is_empty() {
249 return suggested_people(&state.sidebar.chats, me, &self.chips, SUGGESTED_LIMIT);
270 let suggested = suggested_people(
271 &state.sidebar.chats,
272 me,
273 &self.chips,
274 SUGGESTED_LIMIT + self.excluded.len(),
275 );
276 let mut suggested = without_excluded(suggested, &self.excluded);
277 suggested.truncate(SUGGESTED_LIMIT);
278 return suggested;
250 279 }
251 280 search_results(
252 people_in(&state.sidebar.chats, me, false),
253 self.remote.clone(),
281 without_excluded(people_in(&state.sidebar.chats, me, false), &self.excluded),
282 without_excluded(self.remote.clone(), &self.excluded),
254 283 &query,
255 284 me,
256 285 &self.chips,
@@ -881,6 +910,13 @@ mod tests {
881 910 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
882 911 }
883 912
913 #[test]
914 fn excluded_people_are_filtered_out() {
915 let picks = vec![pick("ann", "Ann", None), pick("bob", "Bob", None)];
916 let kept = super::without_excluded(picks, &["ann".to_owned()]);
917 assert_eq!(kept, [pick("bob", "Bob", None)]);
918 }
919
884 920 #[test]
885 921 fn enter_adds_the_highlight_or_moves_on() {
886 922 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
@@ -84,6 +84,13 @@ fn not_chosen(pick: &Pick, me: Option<&Person>, chosen: &[Pick]) -> bool {
84 && chosen.iter().all(|chip| chip.user_id != pick.user_id)
84 && chosen.iter().all(|chip| chip.user_id != pick.user_id)
85}
85}
86
86
87fn without_excluded(picks: Vec<Pick>, excluded: &[String]) -> Vec<Pick> {
88 picks
89 .into_iter()
90 .filter(|pick| !excluded.contains(&pick.user_id))
91 .collect()
92}
93
87pub fn suggested_people(
94pub fn suggested_people(
88 chats: &[ChatRecord],
95 chats: &[ChatRecord],
89 me: Option<&Person>,
96 me: Option<&Person>,
@@ -158,6 +165,7 @@ pub struct NewChatDraft {
158 query: Entity<InputState>,
165 query: Entity<InputState>,
159 name: Entity<InputState>,
166 name: Entity<InputState>,
160 chips: Vec<Pick>,
167 chips: Vec<Pick>,
168 excluded: Vec<String>,
161 form_field: bool,
169 form_field: bool,
162 remote: Vec<Pick>,
170 remote: Vec<Pick>,
163 highlighted: usize,
171 highlighted: usize,
@@ -184,6 +192,7 @@ impl NewChatDraft {
184 query,
192 query,
185 name,
193 name,
186 chips: Vec::new(),
194 chips: Vec::new(),
195 excluded: Vec::new(),
187 form_field: false,
196 form_field: false,
188 remote: Vec::new(),
197 remote: Vec::new(),
189 highlighted: 0,
198 highlighted: 0,
@@ -202,10 +211,22 @@ impl NewChatDraft {
202 self
211 self
203 }
212 }
204
213
214 pub fn excluding(mut self, user_ids: Vec<String>) -> Self {
215 self.excluded = user_ids;
216 self
217 }
218
205 pub fn chips(&self) -> &[Pick] {
219 pub fn chips(&self) -> &[Pick] {
206 &self.chips
220 &self.chips
207 }
221 }
208
222
223 pub fn set_chips(&mut self, chips: Vec<Pick>, cx: &mut Context<Self>) {
224 self.chips = chips;
225 self.highlighted = 0;
226 cx.emit(NewChatEvent::Changed);
227 cx.notify();
228 }
229
209 pub fn group_name(&self, cx: &App) -> String {
230 pub fn group_name(&self, cx: &App) -> String {
210 self.name.read(cx).value().trim().to_owned()
231 self.name.read(cx).value().trim().to_owned()
211 }
232 }
@@ -246,11 +267,19 @@ impl NewChatDraft {
246 let me = state.directory.me.as_ref();
267 let me = state.directory.me.as_ref();
247 let query = self.query_text(cx);
268 let query = self.query_text(cx);
248 if query.is_empty() {
269 if query.is_empty() {
249 return suggested_people(&state.sidebar.chats, me, &self.chips, SUGGESTED_LIMIT);
270 let suggested = suggested_people(
271 &state.sidebar.chats,
272 me,
273 &self.chips,
274 SUGGESTED_LIMIT + self.excluded.len(),
275 );
276 let mut suggested = without_excluded(suggested, &self.excluded);
277 suggested.truncate(SUGGESTED_LIMIT);
278 return suggested;
250 }
279 }
251 search_results(
280 search_results(
252 people_in(&state.sidebar.chats, me, false),
281 without_excluded(people_in(&state.sidebar.chats, me, false), &self.excluded),
253 self.remote.clone(),
282 without_excluded(self.remote.clone(), &self.excluded),
254 &query,
283 &query,
255 me,
284 me,
256 &self.chips,
285 &self.chips,
@@ -881,6 +910,13 @@ mod tests {
881 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
910 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
882 }
911 }
883
912
913 #[test]
914 fn excluded_people_are_filtered_out() {
915 let picks = vec![pick("ann", "Ann", None), pick("bob", "Bob", None)];
916 let kept = super::without_excluded(picks, &["ann".to_owned()]);
917 assert_eq!(kept, [pick("bob", "Bob", None)]);
918 }
919
884 #[test]
920 #[test]
885 fn enter_adds_the_highlight_or_moves_on() {
921 fn enter_adds_the_highlight_or_moves_on() {
886 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
922 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
crates/app/src/views/post_card.rs +4 −9
@@ -10,7 +10,9 @@ use super::call_card::{CallActions, post_call_card};
10 10 use super::call_notice::notice_line;
11 11 use super::link_preview::{link_preview_card, meeting_join_chip};
12 12 use super::message_actions::message_toolbar;
13 use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
13 use super::message_row::{
14 BODY_SIZE, RowActions, deleted_tombstone, delivery_note, forwarded_header, has_text,
15 };
14 16 use super::profile_card::opens_profile;
15 17 use super::reaction_pills::reaction_pills;
16 18 use super::reaction_proposal_pill::reaction_pill;
@@ -21,7 +23,6 @@ use super::widgets::{icon, symbol};
21 23 use crate::agents::run_chip;
22 24 use crate::data::Directory;
23 25 use crate::rows::{Delivery, MessageRow, PostRow};
24 use crate::sidebar_model::DELETED_PREVIEW;
25 26 use crate::theme;
26 27
27 28 const ROOT_AVATAR: f32 = 32.;
@@ -82,13 +83,7 @@ fn message_content(
82 83 ) -> Div {
83 84 let mut content = v_flex().gap(px(6.));
84 85 if row.deleted {
85 return content.child(
86 div()
87 .text_size(px(13.))
88 .italic()
89 .text_color(theme::text_muted())
90 .child(DELETED_PREVIEW),
91 );
86 return content.child(deleted_tombstone(index, actions.undo_delete.clone()));
92 87 }
93 88 if row.forwarded {
94 89 content = content.child(forwarded_header());
@@ -10,7 +10,9 @@ use super::call_card::{CallActions, post_call_card};
10use super::call_notice::notice_line;
10use super::call_notice::notice_line;
11use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::link_preview::{link_preview_card, meeting_join_chip};
12use super::message_actions::message_toolbar;
12use super::message_actions::message_toolbar;
13use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
13use super::message_row::{
14 BODY_SIZE, RowActions, deleted_tombstone, delivery_note, forwarded_header, has_text,
15};
14use super::profile_card::opens_profile;
16use super::profile_card::opens_profile;
15use super::reaction_pills::reaction_pills;
17use super::reaction_pills::reaction_pills;
16use super::reaction_proposal_pill::reaction_pill;
18use super::reaction_proposal_pill::reaction_pill;
@@ -21,7 +23,6 @@ use super::widgets::{icon, symbol};
21use crate::agents::run_chip;
23use crate::agents::run_chip;
22use crate::data::Directory;
24use crate::data::Directory;
23use crate::rows::{Delivery, MessageRow, PostRow};
25use crate::rows::{Delivery, MessageRow, PostRow};
24use crate::sidebar_model::DELETED_PREVIEW;
25use crate::theme;
26use crate::theme;
26
27
27const ROOT_AVATAR: f32 = 32.;
28const ROOT_AVATAR: f32 = 32.;
@@ -82,13 +83,7 @@ fn message_content(
82) -> Div {
83) -> Div {
83 let mut content = v_flex().gap(px(6.));
84 let mut content = v_flex().gap(px(6.));
84 if row.deleted {
85 if row.deleted {
85 return content.child(
86 return content.child(deleted_tombstone(index, actions.undo_delete.clone()));
86 div()
87 .text_size(px(13.))
88 .italic()
89 .text_color(theme::text_muted())
90 .child(DELETED_PREVIEW),
91 );
92 }
87 }
93 if row.forwarded {
88 if row.forwarded {
94 content = content.child(forwarded_header());
89 content = content.child(forwarded_header());
crates/app/src/views/shell.rs +20 −2
@@ -19,11 +19,13 @@ use gpui_kit::prelude::FluentBuilder as _;
19 19 use super::rail::RailView;
20 20 use super::saved_panel::{SavedPanel, SavedPanelEvent};
21 21 use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, 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,9 +1034,20 @@ 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))
1043 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1044 if this.image_viewer.is_some() || this.state.read(cx).viewing_call() {
1045 cx.propagate();
1046 return;
1047 }
1048 this.conversation
1049 .update(cx, |conversation, cx| conversation.jump_to_last_read_or_newest(cx));
1050 }))
1033 1051 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1034 1052 this.close_image_viewer(window, cx);
1035 1053 this.conversation.update(cx, |conversation, cx| {
@@ -19,11 +19,13 @@ use gpui_kit::prelude::FluentBuilder as _;
19use super::rail::RailView;
19use super::rail::RailView;
20use super::saved_panel::{SavedPanel, SavedPanelEvent};
20use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::shortcuts::{
21use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, 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,9 +1034,20 @@ 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))
1043 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1044 if this.image_viewer.is_some() || this.state.read(cx).viewing_call() {
1045 cx.propagate();
1046 return;
1047 }
1048 this.conversation
1049 .update(cx, |conversation, cx| conversation.jump_to_last_read_or_newest(cx));
1050 }))
1033 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1051 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1034 this.close_image_viewer(window, cx);
1052 this.close_image_viewer(window, cx);
1035 this.conversation.update(cx, |conversation, cx| {
1053 this.conversation.update(cx, |conversation, cx| {
crates/app/src/views/shortcuts.rs +56 −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,
@@ -24,6 +31,7 @@ actions!(
24 31 OpenAgents,
25 32 PreviousConversation,
26 33 NextConversation,
34 JumpToLastReadOrNewest,
27 35 AcceptCall,
28 36 DeclineCall,
29 37 JoinMeetingFromToast,
@@ -40,7 +48,10 @@ actions!(
40 48 ZoomShareOut,
41 49 ZoomShareReset,
42 50 ShowShortcuts,
43 OpenSettings
51 OpenSettings,
52 ZoomIn,
53 ZoomOut,
54 ZoomReset
44 55 ]
45 56 );
46 57
@@ -107,6 +118,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
107 118 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
108 119 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
109 120 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
121 shortcut!(General, OutsideComposer, "Zoom in", "ctrl-=", Some("cmd-="), ZoomIn),
122 shortcut!(General, GlobalOverTextFields, "Zoom out", "ctrl--", Some("cmd--"), ZoomOut),
123 shortcut!(General, GlobalOverTextFields, "Reset zoom level", "ctrl-0", Some("cmd-0"), ZoomReset),
110 124 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
111 125 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
112 126 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
@@ -116,6 +130,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
116 130 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
117 131 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
118 132 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
119 134 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
120 135 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
121 136 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
@@ -171,7 +186,7 @@ impl Shortcut {
171 186 keys.extend(
172 187 ALTERNATE_KEYS
173 188 .iter()
174 .filter(|(primary, _)| *primary == self.keys)
189 .filter(|(label, _)| *label == self.label)
175 190 .map(|(_, alternate)| *alternate),
176 191 );
177 192 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
@@ -356,6 +371,43 @@ mod tests {
356 371 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
357 372 }
358 373
374 #[gpui_kit::test]
375 fn zoom_keys_match_teams_and_leave_the_composer_subscript_alone(cx: &mut TestAppContext) {
376 registered(cx);
377 let action_of = |label: &str| {
378 action_name(
379 SHORTCUTS
380 .iter()
381 .find(|shortcut| shortcut.label == label)
382 .unwrap(),
383 )
384 };
385 for (keys, label) in [
386 ("ctrl-=", "Zoom in"),
387 ("ctrl-+", "Zoom in"),
388 ("ctrl-shift-=", "Zoom in"),
389 ("ctrl--", "Zoom out"),
390 ("ctrl-_", "Zoom out"),
391 ("ctrl-0", "Reset zoom level"),
392 ] {
393 assert_eq!(
394 bound_action(cx, keys, &["AppShell"]),
395 Some(action_of(label)),
396 "{keys}"
397 );
398 }
399 let typing = ["AppShell", "Composer", "Input"];
400 assert_eq!(
401 bound_action(cx, "ctrl-=", &typing),
402 Some(action_of("Subscript"))
403 );
404 assert_eq!(
405 bound_action(cx, "ctrl--", &typing),
406 Some(action_of("Zoom out"))
407 );
408 assert_eq!(display_keys("ctrl-="), "Ctrl+Plus");
409 }
410
359 411 #[gpui_kit::test]
360 412 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
361 413 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,
@@ -24,6 +31,7 @@ actions!(
24 OpenAgents,
31 OpenAgents,
25 PreviousConversation,
32 PreviousConversation,
26 NextConversation,
33 NextConversation,
34 JumpToLastReadOrNewest,
27 AcceptCall,
35 AcceptCall,
28 DeclineCall,
36 DeclineCall,
29 JoinMeetingFromToast,
37 JoinMeetingFromToast,
@@ -40,7 +48,10 @@ actions!(
40 ZoomShareOut,
48 ZoomShareOut,
41 ZoomShareReset,
49 ZoomShareReset,
42 ShowShortcuts,
50 ShowShortcuts,
43 OpenSettings
51 OpenSettings,
52 ZoomIn,
53 ZoomOut,
54 ZoomReset
44 ]
55 ]
45);
56);
46
57
@@ -107,6 +118,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
107 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
118 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
108 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
119 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
109 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
120 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
121 shortcut!(General, OutsideComposer, "Zoom in", "ctrl-=", Some("cmd-="), ZoomIn),
122 shortcut!(General, GlobalOverTextFields, "Zoom out", "ctrl--", Some("cmd--"), ZoomOut),
123 shortcut!(General, GlobalOverTextFields, "Reset zoom level", "ctrl-0", Some("cmd-0"), ZoomReset),
110 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
124 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
111 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
125 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
112 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
126 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
@@ -116,6 +130,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
116 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
130 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
117 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
131 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
118 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
132 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
119 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
134 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
120 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
135 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
121 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
136 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
@@ -171,7 +186,7 @@ impl Shortcut {
171 keys.extend(
186 keys.extend(
172 ALTERNATE_KEYS
187 ALTERNATE_KEYS
173 .iter()
188 .iter()
174 .filter(|(primary, _)| *primary == self.keys)
189 .filter(|(label, _)| *label == self.label)
175 .map(|(_, alternate)| *alternate),
190 .map(|(_, alternate)| *alternate),
176 );
191 );
177 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
192 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
@@ -356,6 +371,43 @@ mod tests {
356 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
371 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
357 }
372 }
358
373
374 #[gpui_kit::test]
375 fn zoom_keys_match_teams_and_leave_the_composer_subscript_alone(cx: &mut TestAppContext) {
376 registered(cx);
377 let action_of = |label: &str| {
378 action_name(
379 SHORTCUTS
380 .iter()
381 .find(|shortcut| shortcut.label == label)
382 .unwrap(),
383 )
384 };
385 for (keys, label) in [
386 ("ctrl-=", "Zoom in"),
387 ("ctrl-+", "Zoom in"),
388 ("ctrl-shift-=", "Zoom in"),
389 ("ctrl--", "Zoom out"),
390 ("ctrl-_", "Zoom out"),
391 ("ctrl-0", "Reset zoom level"),
392 ] {
393 assert_eq!(
394 bound_action(cx, keys, &["AppShell"]),
395 Some(action_of(label)),
396 "{keys}"
397 );
398 }
399 let typing = ["AppShell", "Composer", "Input"];
400 assert_eq!(
401 bound_action(cx, "ctrl-=", &typing),
402 Some(action_of("Subscript"))
403 );
404 assert_eq!(
405 bound_action(cx, "ctrl--", &typing),
406 Some(action_of("Zoom out"))
407 );
408 assert_eq!(display_keys("ctrl-="), "Ctrl+Plus");
409 }
410
359 #[gpui_kit::test]
411 #[gpui_kit::test]
360 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
412 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
361 registered(cx);
413 registered(cx);
crates/app/src/views/sidebar.rs +13 −0
@@ -1029,6 +1029,10 @@ impl SidebarView {
1029 1029 title: item.title.clone(),
1030 1030 };
1031 1031 let menu_context = menu.clone();
1032 let reorder_folder = item
1033 .folder_id
1034 .clone()
1035 .filter(|folder_id| !is_pending_folder(folder_id));
1032 1036 let target = ChatMenuTarget {
1033 1037 id: item.id.clone(),
1034 1038 title: item.title.clone(),
@@ -1054,6 +1058,15 @@ impl SidebarView {
1054 1058 let title = dragged.title.clone();
1055 1059 cx.new(|_| DragGhost { title })
1056 1060 })
1061 .when_some(reorder_folder, |row, folder_id| {
1062 let (drop_state, target_id) = (self.state.clone(), item.id.clone());
1063 row.drag_over::<DraggedChat>(|style, _, _, _| style.bg(theme::drop_background()))
1064 .on_drop(move |dragged: &DraggedChat, _, cx| {
1065 drop_state.update(cx, |state, cx| {
1066 state.drop_chat_on(&dragged.id, &target_id, &folder_id, cx)
1067 });
1068 })
1069 })
1057 1070 .child(avatar)
1058 1071 .child(lines)
1059 1072 .on_click(move |_, _, cx| {
@@ -1029,6 +1029,10 @@ impl SidebarView {
1029 title: item.title.clone(),
1029 title: item.title.clone(),
1030 };
1030 };
1031 let menu_context = menu.clone();
1031 let menu_context = menu.clone();
1032 let reorder_folder = item
1033 .folder_id
1034 .clone()
1035 .filter(|folder_id| !is_pending_folder(folder_id));
1032 let target = ChatMenuTarget {
1036 let target = ChatMenuTarget {
1033 id: item.id.clone(),
1037 id: item.id.clone(),
1034 title: item.title.clone(),
1038 title: item.title.clone(),
@@ -1054,6 +1058,15 @@ impl SidebarView {
1054 let title = dragged.title.clone();
1058 let title = dragged.title.clone();
1055 cx.new(|_| DragGhost { title })
1059 cx.new(|_| DragGhost { title })
1056 })
1060 })
1061 .when_some(reorder_folder, |row, folder_id| {
1062 let (drop_state, target_id) = (self.state.clone(), item.id.clone());
1063 row.drag_over::<DraggedChat>(|style, _, _, _| style.bg(theme::drop_background()))
1064 .on_drop(move |dragged: &DraggedChat, _, cx| {
1065 drop_state.update(cx, |state, cx| {
1066 state.drop_chat_on(&dragged.id, &target_id, &folder_id, cx)
1067 });
1068 })
1069 })
1057 .child(avatar)
1070 .child(avatar)
1058 .child(lines)
1071 .child(lines)
1059 .on_click(move |_, _, cx| {
1072 .on_click(move |_, _, cx| {
crates/app/src/views/status_menu.rs +30 −30
@@ -10,23 +10,26 @@ use gpui_kit::component::{
10 10 use gpui_kit::*;
11 11 use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12 12
13 use super::avatar::{person_avatar, with_presence};
13 use super::avatar::{person_avatar, with_presence, with_presence_badge};
14 14 use super::widgets::{icon, symbol};
15 15 use crate::app_state::AppState;
16 16 use crate::data::{Person, PresenceKind};
17 use crate::settings_section::SettingsSection;
18 17 use crate::own_status::{
19 18 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 19 presence_kind_for, state_summary, work_location_label,
21 20 };
21 use crate::settings_section::SettingsSection;
22 22 use crate::theme;
23 23
24 24 pub const MENU_WIDTH: f32 = 250.;
25 const TITLE_AVATAR_SIZE: f32 = 26.;
25 pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
26 pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
27 const TITLE_PRESENCE_SIZE: f32 = 14.;
26 28 const HEADER_AVATAR_SIZE: f32 = 40.;
27 const RING_WIDTH: f32 = 2.;
28 29 const PRESENCE_OVERHANG: f32 = 2.;
29 const OWN_STATUS_BUTTON_SIZE: f32 = TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH + PRESENCE_OVERHANG);
30 const TITLE_BUTTON_INSET: f32 = 2.;
31 const OWN_STATUS_BUTTON_SIZE: f32 =
32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
30 33 const MENU_ICON_SIZE: f32 = 14.;
31 34 const ICON_COLUMN: f32 = 16.;
32 35 const HEADER_INSET: f32 = 24.;
@@ -44,7 +47,6 @@ struct MenuContext {
44 47 pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
45 48 let person = state.directory.me.clone()?;
46 49 let presence = state.directory.presence_of(&person.user_id);
47 let open = state.status_menu_open;
48 50 let summary = state_summary(&state.own_status, state.own_presence_kind(), &Local::now());
49 51 let context = MenuContext {
50 52 app: app.clone(),
@@ -54,28 +56,19 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
54 56 summary,
55 57 person: person.clone(),
56 58 };
57 let ringed = div()
58 .p(px(1.))
59 .rounded_full()
60 .border(px(RING_WIDTH))
61 .border_color(if open {
62 theme::accent()
63 } else {
64 transparent_black()
65 })
66 .child(person_avatar(
59 let avatar = with_presence_badge(
60 person_avatar(
67 61 &state.directory,
68 62 Some(&person.user_id),
69 63 &person.display_name,
70 64 TITLE_AVATAR_SIZE,
71 ))
72 .into_any_element();
73 let ringed = with_presence(
74 ringed,
65 ),
75 66 presence,
76 TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH),
67 TITLE_AVATAR_SIZE,
68 TITLE_PRESENCE_SIZE,
77 69 theme::background(),
78 );
70 )
71 .debug_selector(|| OWN_AVATAR_DISC.into());
79 72 let toggle = app.clone();
80 73 Some(
81 74 div()
@@ -92,7 +85,7 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
92 85 div()
93 86 .debug_selector(|| "shell/title-bar/own-status/avatar".into())
94 87 .p(px(PRESENCE_OVERHANG))
95 .child(ringed),
88 .child(avatar),
96 89 )
97 90 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
98 91 status_menu(popup, window, cx, &context)
@@ -197,6 +190,7 @@ fn status_menu(
197 190 let translation_app = context.app.clone();
198 191 let general_app = context.app.clone();
199 192 let call_app = context.app.clone();
193 let zoom_app = context.app.clone();
200 194 let row_label = match &context.summary.until {
201 195 Some(until) => format!("{} {until}", context.summary.label),
202 196 None => context.summary.label.to_owned(),
@@ -230,16 +224,18 @@ fn status_menu(
230 224 PopupMenuItem::new("Chat list")
231 225 .icon(menu_icon(IconName::LayoutList))
232 226 .on_click(move |_, _, cx| {
233 chat_list_app
234 .update(cx, |state, cx| state.open_settings(SettingsSection::Chats, cx));
227 chat_list_app.update(cx, |state, cx| {
228 state.open_settings(SettingsSection::Chats, cx)
229 });
235 230 }),
236 231 )
237 232 .item(
238 233 PopupMenuItem::new("Translation")
239 234 .icon(menu_icon(IconName::Languages))
240 235 .on_click(move |_, _, cx| {
241 translation_app
242 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
236 translation_app.update(cx, |state, cx| {
237 state.open_settings(SettingsSection::General, cx)
238 });
243 239 }),
244 240 )
245 241 .item(
@@ -262,10 +258,14 @@ fn status_menu(
262 258 PopupMenuItem::new("Settings")
263 259 .icon(menu_icon(IconName::Settings))
264 260 .on_click(move |_, _, cx| {
265 general_app
266 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
261 general_app.update(cx, |state, cx| {
262 state.open_settings(SettingsSection::General, cx)
263 });
267 264 }),
268 );
265 )
266 .item(PopupMenuItem::element(move |_, cx| {
267 super::window_zoom::menu_row(&zoom_app, cx)
268 }));
269 269 if !demo {
270 270 return popup;
271 271 }
@@ -10,23 +10,26 @@ use gpui_kit::component::{
10use gpui_kit::*;
10use gpui_kit::*;
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12
12
13use super::avatar::{person_avatar, with_presence};
13use super::avatar::{person_avatar, with_presence, with_presence_badge};
14use super::widgets::{icon, symbol};
14use super::widgets::{icon, symbol};
15use crate::app_state::AppState;
15use crate::app_state::AppState;
16use crate::data::{Person, PresenceKind};
16use crate::data::{Person, PresenceKind};
17use crate::settings_section::SettingsSection;
18use crate::own_status::{
17use crate::own_status::{
19 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
18 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 presence_kind_for, state_summary, work_location_label,
19 presence_kind_for, state_summary, work_location_label,
21};
20};
21use crate::settings_section::SettingsSection;
22use crate::theme;
22use crate::theme;
23
23
24pub const MENU_WIDTH: f32 = 250.;
24pub const MENU_WIDTH: f32 = 250.;
25const TITLE_AVATAR_SIZE: f32 = 26.;
25pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
26pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
27const TITLE_PRESENCE_SIZE: f32 = 14.;
26const HEADER_AVATAR_SIZE: f32 = 40.;
28const HEADER_AVATAR_SIZE: f32 = 40.;
27const RING_WIDTH: f32 = 2.;
28const PRESENCE_OVERHANG: f32 = 2.;
29const PRESENCE_OVERHANG: f32 = 2.;
29const OWN_STATUS_BUTTON_SIZE: f32 = TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH + PRESENCE_OVERHANG);
30const TITLE_BUTTON_INSET: f32 = 2.;
31const OWN_STATUS_BUTTON_SIZE: f32 =
32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
30const MENU_ICON_SIZE: f32 = 14.;
33const MENU_ICON_SIZE: f32 = 14.;
31const ICON_COLUMN: f32 = 16.;
34const ICON_COLUMN: f32 = 16.;
32const HEADER_INSET: f32 = 24.;
35const HEADER_INSET: f32 = 24.;
@@ -44,7 +47,6 @@ struct MenuContext {
44pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
47pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
45 let person = state.directory.me.clone()?;
48 let person = state.directory.me.clone()?;
46 let presence = state.directory.presence_of(&person.user_id);
49 let presence = state.directory.presence_of(&person.user_id);
47 let open = state.status_menu_open;
48 let summary = state_summary(&state.own_status, state.own_presence_kind(), &Local::now());
50 let summary = state_summary(&state.own_status, state.own_presence_kind(), &Local::now());
49 let context = MenuContext {
51 let context = MenuContext {
50 app: app.clone(),
52 app: app.clone(),
@@ -54,28 +56,19 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
54 summary,
56 summary,
55 person: person.clone(),
57 person: person.clone(),
56 };
58 };
57 let ringed = div()
59 let avatar = with_presence_badge(
58 .p(px(1.))
60 person_avatar(
59 .rounded_full()
60 .border(px(RING_WIDTH))
61 .border_color(if open {
62 theme::accent()
63 } else {
64 transparent_black()
65 })
66 .child(person_avatar(
67 &state.directory,
61 &state.directory,
68 Some(&person.user_id),
62 Some(&person.user_id),
69 &person.display_name,
63 &person.display_name,
70 TITLE_AVATAR_SIZE,
64 TITLE_AVATAR_SIZE,
71 ))
65 ),
72 .into_any_element();
73 let ringed = with_presence(
74 ringed,
75 presence,
66 presence,
76 TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH),
67 TITLE_AVATAR_SIZE,
68 TITLE_PRESENCE_SIZE,
77 theme::background(),
69 theme::background(),
78 );
70 )
71 .debug_selector(|| OWN_AVATAR_DISC.into());
79 let toggle = app.clone();
72 let toggle = app.clone();
80 Some(
73 Some(
81 div()
74 div()
@@ -92,7 +85,7 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
92 div()
85 div()
93 .debug_selector(|| "shell/title-bar/own-status/avatar".into())
86 .debug_selector(|| "shell/title-bar/own-status/avatar".into())
94 .p(px(PRESENCE_OVERHANG))
87 .p(px(PRESENCE_OVERHANG))
95 .child(ringed),
88 .child(avatar),
96 )
89 )
97 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
90 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
98 status_menu(popup, window, cx, &context)
91 status_menu(popup, window, cx, &context)
@@ -197,6 +190,7 @@ fn status_menu(
197 let translation_app = context.app.clone();
190 let translation_app = context.app.clone();
198 let general_app = context.app.clone();
191 let general_app = context.app.clone();
199 let call_app = context.app.clone();
192 let call_app = context.app.clone();
193 let zoom_app = context.app.clone();
200 let row_label = match &context.summary.until {
194 let row_label = match &context.summary.until {
201 Some(until) => format!("{} {until}", context.summary.label),
195 Some(until) => format!("{} {until}", context.summary.label),
202 None => context.summary.label.to_owned(),
196 None => context.summary.label.to_owned(),
@@ -230,16 +224,18 @@ fn status_menu(
230 PopupMenuItem::new("Chat list")
224 PopupMenuItem::new("Chat list")
231 .icon(menu_icon(IconName::LayoutList))
225 .icon(menu_icon(IconName::LayoutList))
232 .on_click(move |_, _, cx| {
226 .on_click(move |_, _, cx| {
233 chat_list_app
227 chat_list_app.update(cx, |state, cx| {
234 .update(cx, |state, cx| state.open_settings(SettingsSection::Chats, cx));
228 state.open_settings(SettingsSection::Chats, cx)
229 });
235 }),
230 }),
236 )
231 )
237 .item(
232 .item(
238 PopupMenuItem::new("Translation")
233 PopupMenuItem::new("Translation")
239 .icon(menu_icon(IconName::Languages))
234 .icon(menu_icon(IconName::Languages))
240 .on_click(move |_, _, cx| {
235 .on_click(move |_, _, cx| {
241 translation_app
236 translation_app.update(cx, |state, cx| {
242 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
237 state.open_settings(SettingsSection::General, cx)
238 });
243 }),
239 }),
244 )
240 )
245 .item(
241 .item(
@@ -262,10 +258,14 @@ fn status_menu(
262 PopupMenuItem::new("Settings")
258 PopupMenuItem::new("Settings")
263 .icon(menu_icon(IconName::Settings))
259 .icon(menu_icon(IconName::Settings))
264 .on_click(move |_, _, cx| {
260 .on_click(move |_, _, cx| {
265 general_app
261 general_app.update(cx, |state, cx| {
266 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
262 state.open_settings(SettingsSection::General, cx)
263 });
267 }),
264 }),
268 );
265 )
266 .item(PopupMenuItem::element(move |_, cx| {
267 super::window_zoom::menu_row(&zoom_app, cx)
268 }));
269 if !demo {
269 if !demo {
270 return popup;
270 return popup;
271 }
271 }
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}
crates/chatsvc/src/lib.rs +2 −0
@@ -14,6 +14,7 @@ mod json_id;
14 14 pub mod language_settings;
15 15 pub mod links;
16 16 mod mask;
17 pub mod members;
17 18 pub mod messages;
18 19 pub mod pins;
19 20 pub mod presence;
@@ -56,6 +57,7 @@ pub use language_settings::{
56 57 };
57 58 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
58 59 pub use mask::mask_conversation_id;
60 pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
59 61 pub use messages::{ConversationRef, Messages};
60 62 pub use pins::{
61 63 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -14,6 +14,7 @@ mod json_id;
14pub mod language_settings;
14pub mod language_settings;
15pub mod links;
15pub mod links;
16mod mask;
16mod mask;
17pub mod members;
17pub mod messages;
18pub mod messages;
18pub mod pins;
19pub mod pins;
19pub mod presence;
20pub mod presence;
@@ -56,6 +57,7 @@ pub use language_settings::{
56};
57};
57pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
58pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
58pub use mask::mask_conversation_id;
59pub use mask::mask_conversation_id;
60pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
59pub use messages::{ConversationRef, Messages};
61pub use messages::{ConversationRef, Messages};
60pub use pins::{
62pub use pins::{
61 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
63 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
crates/chatsvc/src/members.rs added +211 −0
@@ -0,0 +1,211 @@
1 use serde_json::{Value, json};
2 use session::{Method, Request, Session};
3
4 use crate::error::Result;
5 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6 use crate::pins::DEFAULT_REGION;
7
8 const ORGID_PREFIX: &str = "8:orgid:";
9 const MEMBER_ROLE: &str = "Admin";
10 const DAY_MS: i64 = 86_400_000;
11 pub const MAX_HISTORY_DAYS: u32 = 999;
12
13 /// How much chat history new members see, as the Teams add-people dialog offers it.
14 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15 pub enum HistoryShare {
16 #[default]
17 None,
18 Days(u32),
19 All,
20 }
21
22 impl HistoryShare {
23 /// The `shareHistoryTime` Teams sends: -1 for none, 0 for all, else the start in epoch ms.
24 pub fn share_history_time(self, now_ms: i64) -> i64 {
25 match self {
26 HistoryShare::None => -1,
27 HistoryShare::All => 0,
28 HistoryShare::Days(days) => now_ms - i64::from(days) * DAY_MS,
29 }
30 }
31 }
32
33 pub fn user_mri(user_id: &str) -> String {
34 if user_id.contains(':') {
35 user_id.to_owned()
36 } else {
37 format!("{ORGID_PREFIX}{user_id}")
38 }
39 }
40
41 pub fn threads_url(region: &str) -> String {
42 format!("https://teams.cloud.microsoft/api/chatsvc/{region}/v1/threads")
43 }
44
45 pub fn add_members_body(user_ids: &[String], share: HistoryShare, now_ms: i64) -> Value {
46 let share_history_time = share.share_history_time(now_ms);
47 let members: Vec<Value> = user_ids
48 .iter()
49 .map(|user_id| {
50 json!({
51 "id": user_mri(user_id),
52 "role": MEMBER_ROLE,
53 "shareHistoryTime": share_history_time,
54 })
55 })
56 .collect();
57 json!({ "members": members })
58 }
59
60 pub fn add_members_request(
61 region: &str,
62 thread_id: &str,
63 user_ids: &[String],
64 share: HistoryShare,
65 now_ms: i64,
66 ) -> Request {
67 Request::with_body(
68 Method::Put,
69 format!("{}/{}/members", threads_url(region), encode(thread_id)),
70 add_members_body(user_ids, share, now_ms),
71 )
72 }
73
74 pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Request {
75 Request::delete(format!(
76 "{}/{}/members/{}",
77 threads_url(region),
78 encode(thread_id),
79 user_mri(user_id)
80 ))
81 }
82
83 pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84 transport: T,
85 region: String,
86 }
87
88 impl ThreadMembers<SessionMessageTransport> {
89 pub fn new(session: &Session) -> Self {
90 ThreadMembers::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
91 }
92 }
93
94 impl<T: MessageTransport> ThreadMembers<T> {
95 pub fn with_transport(transport: T, region: &str) -> Self {
96 ThreadMembers {
97 transport,
98 region: region.to_owned(),
99 }
100 }
101
102 pub async fn add(
103 &self,
104 thread_id: &str,
105 user_ids: &[String],
106 share: HistoryShare,
107 now_ms: i64,
108 ) -> Result<()> {
109 let request = add_members_request(&self.region, thread_id, user_ids, share, now_ms);
110 ensure_success(&self.transport.send(request).await?)
111 }
112
113 pub async fn remove(&self, thread_id: &str, user_id: &str) -> Result<()> {
114 let request = remove_member_request(&self.region, thread_id, user_id);
115 ensure_success(&self.transport.send(request).await?)
116 }
117 }
118
119 #[cfg(test)]
120 mod tests {
121 use std::sync::Mutex;
122
123 use session::ApiResponse;
124
125 use super::*;
126
127 const NOW: i64 = 1_792_200_000_000;
128 const THREAD: &str = "19:abc@thread.v2";
129
130 struct Recorder {
131 status: u16,
132 requests: Mutex<Vec<Request>>,
133 }
134
135 impl MessageTransport for &Recorder {
136 async fn send(&self, request: Request) -> Result<ApiResponse> {
137 self.requests.lock().unwrap().push(request);
138 Ok(ApiResponse {
139 status: self.status,
140 body: Value::Null,
141 retry_after: None,
142 })
143 }
144 }
145
146 fn recorder(status: u16) -> Recorder {
147 Recorder {
148 status,
149 requests: Mutex::new(Vec::new()),
150 }
151 }
152
153 #[test]
154 fn history_share_maps_to_the_teams_share_history_time() {
155 assert_eq!(HistoryShare::None.share_history_time(NOW), -1);
156 assert_eq!(HistoryShare::All.share_history_time(NOW), 0);
157 assert_eq!(
158 HistoryShare::Days(3).share_history_time(NOW),
159 NOW - 3 * 86_400_000
160 );
161 }
162
163 #[test]
164 fn add_request_puts_every_member_with_role_and_history() {
165 let request = add_members_request(
166 "emea",
167 THREAD,
168 &["user-a".to_owned(), "8:orgid:user-b".to_owned()],
169 HistoryShare::Days(1),
170 NOW,
171 );
172 assert_eq!(request.method, Method::Put);
173 assert_eq!(
174 request.url,
175 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/members"
176 );
177 assert_eq!(
178 request.body,
179 Some(json!({"members": [
180 {"id": "8:orgid:user-a", "role": "Admin", "shareHistoryTime": NOW - 86_400_000},
181 {"id": "8:orgid:user-b", "role": "Admin", "shareHistoryTime": NOW - 86_400_000},
182 ]}))
183 );
184 }
185
186 #[test]
187 fn remove_request_deletes_the_member_mri() {
188 let request = remove_member_request("emea", THREAD, "user-a");
189 assert_eq!(request.method, Method::Delete);
190 assert_eq!(
191 request.url,
192 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/members/8:orgid:user-a"
193 );
194 assert_eq!(request.body, None);
195 }
196
197 #[tokio::test]
198 async fn add_sends_one_request_and_reports_failures() {
199 let ok = recorder(200);
200 ThreadMembers::with_transport(&ok, "emea")
201 .add(THREAD, &["user-a".to_owned()], HistoryShare::All, NOW)
202 .await
203 .unwrap();
204 assert_eq!(ok.requests.lock().unwrap().len(), 1);
205 let refused = recorder(403);
206 let result = ThreadMembers::with_transport(&refused, "emea")
207 .remove(THREAD, "user-a")
208 .await;
209 assert!(result.is_err());
210 }
211 }
@@ -0,0 +1,211 @@
1use serde_json::{Value, json};
2use session::{Method, Request, Session};
3
4use crate::error::Result;
5use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::pins::DEFAULT_REGION;
7
8const ORGID_PREFIX: &str = "8:orgid:";
9const MEMBER_ROLE: &str = "Admin";
10const DAY_MS: i64 = 86_400_000;
11pub const MAX_HISTORY_DAYS: u32 = 999;
12
13/// How much chat history new members see, as the Teams add-people dialog offers it.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum HistoryShare {
16 #[default]
17 None,
18 Days(u32),
19 All,
20}
21
22impl HistoryShare {
23 /// The `shareHistoryTime` Teams sends: -1 for none, 0 for all, else the start in epoch ms.
24 pub fn share_history_time(self, now_ms: i64) -> i64 {
25 match self {
26 HistoryShare::None => -1,
27 HistoryShare::All => 0,
28 HistoryShare::Days(days) => now_ms - i64::from(days) * DAY_MS,
29 }
30 }
31}
32
33pub fn user_mri(user_id: &str) -> String {
34 if user_id.contains(':') {
35 user_id.to_owned()
36 } else {
37 format!("{ORGID_PREFIX}{user_id}")
38 }
39}
40
41pub fn threads_url(region: &str) -> String {
42 format!("https://teams.cloud.microsoft/api/chatsvc/{region}/v1/threads")
43}
44
45pub fn add_members_body(user_ids: &[String], share: HistoryShare, now_ms: i64) -> Value {
46 let share_history_time = share.share_history_time(now_ms);
47 let members: Vec<Value> = user_ids
48 .iter()
49 .map(|user_id| {
50 json!({
51 "id": user_mri(user_id),
52 "role": MEMBER_ROLE,
53 "shareHistoryTime": share_history_time,
54 })
55 })
56 .collect();
57 json!({ "members": members })
58}
59
60pub fn add_members_request(
61 region: &str,
62 thread_id: &str,
63 user_ids: &[String],
64 share: HistoryShare,
65 now_ms: i64,
66) -> Request {
67 Request::with_body(
68 Method::Put,
69 format!("{}/{}/members", threads_url(region), encode(thread_id)),
70 add_members_body(user_ids, share, now_ms),
71 )
72}
73
74pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Request {
75 Request::delete(format!(
76 "{}/{}/members/{}",
77 threads_url(region),
78 encode(thread_id),
79 user_mri(user_id)
80 ))
81}
82
83pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84 transport: T,
85 region: String,
86}
87
88impl ThreadMembers<SessionMessageTransport> {
89 pub fn new(session: &Session) -> Self {
90 ThreadMembers::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
91 }
92}
93
94impl<T: MessageTransport> ThreadMembers<T> {
95 pub fn with_transport(transport: T, region: &str) -> Self {
96 ThreadMembers {
97 transport,
98 region: region.to_owned(),
99 }
100 }
101
102 pub async fn add(
103 &self,
104 thread_id: &str,
105 user_ids: &[String],
106 share: HistoryShare,
107 now_ms: i64,
108 ) -> Result<()> {
109 let request = add_members_request(&self.region, thread_id, user_ids, share, now_ms);
110 ensure_success(&self.transport.send(request).await?)
111 }
112
113 pub async fn remove(&self, thread_id: &str, user_id: &str) -> Result<()> {
114 let request = remove_member_request(&self.region, thread_id, user_id);
115 ensure_success(&self.transport.send(request).await?)
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use std::sync::Mutex;
122
123 use session::ApiResponse;
124
125 use super::*;
126
127 const NOW: i64 = 1_792_200_000_000;
128 const THREAD: &str = "19:abc@thread.v2";
129
130 struct Recorder {
131 status: u16,
132 requests: Mutex<Vec<Request>>,
133 }
134
135 impl MessageTransport for &Recorder {
136 async fn send(&self, request: Request) -> Result<ApiResponse> {
137 self.requests.lock().unwrap().push(request);
138 Ok(ApiResponse {
139 status: self.status,
140 body: Value::Null,
141 retry_after: None,
142 })
143 }
144 }
145
146 fn recorder(status: u16) -> Recorder {
147 Recorder {
148 status,
149 requests: Mutex::new(Vec::new()),
150 }
151 }
152
153 #[test]
154 fn history_share_maps_to_the_teams_share_history_time() {
155 assert_eq!(HistoryShare::None.share_history_time(NOW), -1);
156 assert_eq!(HistoryShare::All.share_history_time(NOW), 0);
157 assert_eq!(
158 HistoryShare::Days(3).share_history_time(NOW),
159 NOW - 3 * 86_400_000
160 );
161 }
162
163 #[test]
164 fn add_request_puts_every_member_with_role_and_history() {
165 let request = add_members_request(
166 "emea",
167 THREAD,
168 &["user-a".to_owned(), "8:orgid:user-b".to_owned()],
169 HistoryShare::Days(1),
170 NOW,
171 );
172 assert_eq!(request.method, Method::Put);
173 assert_eq!(
174 request.url,
175 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/members"
176 );
177 assert_eq!(
178 request.body,
179 Some(json!({"members": [
180 {"id": "8:orgid:user-a", "role": "Admin", "shareHistoryTime": NOW - 86_400_000},
181 {"id": "8:orgid:user-b", "role": "Admin", "shareHistoryTime": NOW - 86_400_000},
182 ]}))
183 );
184 }
185
186 #[test]
187 fn remove_request_deletes_the_member_mri() {
188 let request = remove_member_request("emea", THREAD, "user-a");
189 assert_eq!(request.method, Method::Delete);
190 assert_eq!(
191 request.url,
192 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/members/8:orgid:user-a"
193 );
194 assert_eq!(request.body, None);
195 }
196
197 #[tokio::test]
198 async fn add_sends_one_request_and_reports_failures() {
199 let ok = recorder(200);
200 ThreadMembers::with_transport(&ok, "emea")
201 .add(THREAD, &["user-a".to_owned()], HistoryShare::All, NOW)
202 .await
203 .unwrap();
204 assert_eq!(ok.requests.lock().unwrap().len(), 1);
205 let refused = recorder(403);
206 let result = ThreadMembers::with_transport(&refused, "emea")
207 .remove(THREAD, "user-a")
208 .await;
209 assert!(result.is_err());
210 }
211}
crates/chatsvc/src/messages.rs +17 −0
@@ -164,6 +164,23 @@ impl<T: MessageTransport> Messages<T> {
164 164 ensure_success(&answer)
165 165 }
166 166
167 pub async fn undelete_message(
168 &self,
169 conversation: &ConversationRef,
170 message_id: &str,
171 ) -> Result<()> {
172 let url = format!(
173 "{}/properties?name=deletetime",
174 self.message_url(conversation, message_id)
175 );
176 let body = json!({"deletetime": null});
177 let answer = self
178 .transport
179 .send(Request::with_body(Method::Delete, &url, body))
180 .await?;
181 ensure_success(&answer)
182 }
183
167 184 pub async fn set_emotion(
168 185 &self,
169 186 conversation: &ConversationRef,
@@ -164,6 +164,23 @@ impl<T: MessageTransport> Messages<T> {
164 ensure_success(&answer)
164 ensure_success(&answer)
165 }
165 }
166
166
167 pub async fn undelete_message(
168 &self,
169 conversation: &ConversationRef,
170 message_id: &str,
171 ) -> Result<()> {
172 let url = format!(
173 "{}/properties?name=deletetime",
174 self.message_url(conversation, message_id)
175 );
176 let body = json!({"deletetime": null});
177 let answer = self
178 .transport
179 .send(Request::with_body(Method::Delete, &url, body))
180 .await?;
181 ensure_success(&answer)
182 }
183
167 pub async fn set_emotion(
184 pub async fn set_emotion(
168 &self,
185 &self,
169 conversation: &ConversationRef,
186 conversation: &ConversationRef,
crates/chatsvc/src/pins/folders.rs +118 −24
@@ -51,7 +51,7 @@ impl Folders {
51 51
52 52 fn containing(&self, conversation_id: &str) -> Option<&Folder> {
53 53 self.folders.iter().find(|folder| {
54 folder.kind == FolderKind::UserCreated
54 matches!(folder.kind, FolderKind::Favorites | FolderKind::UserCreated)
55 55 && folder
56 56 .conversation_ids
57 57 .iter()
@@ -143,8 +143,54 @@ fn expanded_body(hierarchy_version: i64, expanded: bool) -> Value {
143 143 })
144 144 }
145 145
146 fn add_item(folder_id: &str, conversation_id: &str) -> Value {
147 json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})
146 fn add_item(folder_id: &str, conversation_id: &str, index: Option<usize>) -> Value {
147 let mut action = json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id});
148 if let Some(index) = index {
149 action["itemIndex"] = json!(index);
150 }
151 action
152 }
153
154 fn reorder_items(folder_id: &str, conversation_ids: Vec<String>) -> Value {
155 json!({"action": "ReorderItems", "folderId": folder_id, "newItemsOrder": conversation_ids})
156 }
157
158 fn placed_order(conversation_ids: &[String], conversation_id: &str, index: usize) -> Vec<String> {
159 let mut order: Vec<String> = conversation_ids
160 .iter()
161 .filter(|id| *id != conversation_id)
162 .cloned()
163 .collect();
164 order.insert(index.min(order.len()), conversation_id.to_owned());
165 order
166 }
167
168 fn place_actions(
169 state: &Folders,
170 conversation_id: &str,
171 target_folder_id: &str,
172 index: Option<usize>,
173 ) -> Result<Vec<Value>> {
174 let target = state.find(target_folder_id)?;
175 if target
176 .conversation_ids
177 .iter()
178 .any(|id| id == conversation_id)
179 {
180 let Some(index) = index else {
181 return Ok(Vec::new());
182 };
183 let order = placed_order(&target.conversation_ids, conversation_id, index);
184 if order == target.conversation_ids {
185 return Ok(Vec::new());
186 }
187 return Ok(vec![reorder_items(target_folder_id, order)]);
188 }
189 let mut actions = vec![add_item(target_folder_id, conversation_id, index)];
190 if let Some(current) = state.containing(conversation_id) {
191 actions.push(remove_item(&current.id, conversation_id));
192 }
193 Ok(actions)
148 194 }
149 195
150 196 fn remove_item(folder_id: &str, conversation_id: &str) -> Value {
@@ -220,28 +266,10 @@ impl<T: CsaTransport> Pins<T> {
220 266 &self,
221 267 conversation_id: &str,
222 268 target_folder_id: &str,
269 index: Option<usize>,
223 270 ) -> Result<Folders> {
224 self.write_folders(|state| {
225 let target = state
226 .folders
227 .iter()
228 .find(|folder| folder.id == target_folder_id)
229 .ok_or_else(|| Error::UnknownFolder(target_folder_id.to_owned()))?;
230 if target
231 .conversation_ids
232 .iter()
233 .any(|id| id == conversation_id)
234 {
235 return Ok(Vec::new());
236 }
237 let mut actions = Vec::new();
238 if let Some(current) = state.containing(conversation_id) {
239 actions.push(remove_item(&current.id, conversation_id));
240 }
241 actions.push(add_item(target_folder_id, conversation_id));
242 Ok(actions)
243 })
244 .await
271 self.write_folders(|state| place_actions(state, conversation_id, target_folder_id, index))
272 .await
245 273 }
246 274
247 275 pub async fn remove_from_folder(
@@ -491,6 +519,72 @@ mod tests {
491 519 ));
492 520 }
493 521
522 fn state(folders: &[(&str, FolderKind, &[&str])]) -> Folders {
523 Folders {
524 hierarchy_version: 1,
525 folders: folders
526 .iter()
527 .map(|(id, kind, ids)| Folder {
528 id: (*id).to_owned(),
529 name: (*id).to_owned(),
530 kind: *kind,
531 expanded: true,
532 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
533 })
534 .collect(),
535 order: Vec::new(),
536 }
537 }
538
539 #[test]
540 fn placing_inside_the_same_folder_sends_the_full_new_order() {
541 let folders = state(&[("fav", FolderKind::Favorites, &["a", "b", "c", "d"])]);
542 assert_eq!(
543 place_actions(&folders, "a", "fav", Some(2)).unwrap(),
544 [
545 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["b", "c", "a", "d"]})
546 ]
547 );
548 assert_eq!(
549 place_actions(&folders, "d", "fav", Some(1)).unwrap(),
550 [
551 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["a", "d", "b", "c"]})
552 ]
553 );
554 assert!(
555 place_actions(&folders, "b", "fav", Some(1))
556 .unwrap()
557 .is_empty()
558 );
559 assert!(
560 place_actions(&folders, "b", "fav", None)
561 .unwrap()
562 .is_empty()
563 );
564 }
565
566 #[test]
567 fn moving_out_of_favorites_adds_at_the_index_then_removes_like_teams() {
568 let folders = state(&[
569 ("fav", FolderKind::Favorites, &["a"]),
570 ("work", FolderKind::UserCreated, &["b", "c"]),
571 ]);
572 assert_eq!(
573 place_actions(&folders, "a", "work", Some(1)).unwrap(),
574 [
575 json!({"action": "AddItem", "folderId": "work", "itemId": "a", "itemIndex": 1}),
576 json!({"action": "RemoveItem", "folderId": "fav", "itemId": "a"}),
577 ]
578 );
579 assert_eq!(
580 place_actions(&folders, "b", "fav", None).unwrap(),
581 [
582 json!({"action": "AddItem", "folderId": "fav", "itemId": "b"}),
583 json!({"action": "RemoveItem", "folderId": "work", "itemId": "b"}),
584 ]
585 );
586 }
587
494 588 #[test]
495 589 fn write_body_puts_the_lock_before_the_fields() {
496 590 let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
@@ -51,7 +51,7 @@ impl Folders {
51
51
52 fn containing(&self, conversation_id: &str) -> Option<&Folder> {
52 fn containing(&self, conversation_id: &str) -> Option<&Folder> {
53 self.folders.iter().find(|folder| {
53 self.folders.iter().find(|folder| {
54 folder.kind == FolderKind::UserCreated
54 matches!(folder.kind, FolderKind::Favorites | FolderKind::UserCreated)
55 && folder
55 && folder
56 .conversation_ids
56 .conversation_ids
57 .iter()
57 .iter()
@@ -143,8 +143,54 @@ fn expanded_body(hierarchy_version: i64, expanded: bool) -> Value {
143 })
143 })
144}
144}
145
145
146fn add_item(folder_id: &str, conversation_id: &str) -> Value {
146fn add_item(folder_id: &str, conversation_id: &str, index: Option<usize>) -> Value {
147 json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id})
147 let mut action = json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id});
148 if let Some(index) = index {
149 action["itemIndex"] = json!(index);
150 }
151 action
152}
153
154fn reorder_items(folder_id: &str, conversation_ids: Vec<String>) -> Value {
155 json!({"action": "ReorderItems", "folderId": folder_id, "newItemsOrder": conversation_ids})
156}
157
158fn placed_order(conversation_ids: &[String], conversation_id: &str, index: usize) -> Vec<String> {
159 let mut order: Vec<String> = conversation_ids
160 .iter()
161 .filter(|id| *id != conversation_id)
162 .cloned()
163 .collect();
164 order.insert(index.min(order.len()), conversation_id.to_owned());
165 order
166}
167
168fn place_actions(
169 state: &Folders,
170 conversation_id: &str,
171 target_folder_id: &str,
172 index: Option<usize>,
173) -> Result<Vec<Value>> {
174 let target = state.find(target_folder_id)?;
175 if target
176 .conversation_ids
177 .iter()
178 .any(|id| id == conversation_id)
179 {
180 let Some(index) = index else {
181 return Ok(Vec::new());
182 };
183 let order = placed_order(&target.conversation_ids, conversation_id, index);
184 if order == target.conversation_ids {
185 return Ok(Vec::new());
186 }
187 return Ok(vec![reorder_items(target_folder_id, order)]);
188 }
189 let mut actions = vec![add_item(target_folder_id, conversation_id, index)];
190 if let Some(current) = state.containing(conversation_id) {
191 actions.push(remove_item(&current.id, conversation_id));
192 }
193 Ok(actions)
148}
194}
149
195
150fn remove_item(folder_id: &str, conversation_id: &str) -> Value {
196fn remove_item(folder_id: &str, conversation_id: &str) -> Value {
@@ -220,28 +266,10 @@ impl<T: CsaTransport> Pins<T> {
220 &self,
266 &self,
221 conversation_id: &str,
267 conversation_id: &str,
222 target_folder_id: &str,
268 target_folder_id: &str,
269 index: Option<usize>,
223 ) -> Result<Folders> {
270 ) -> Result<Folders> {
224 self.write_folders(|state| {
271 self.write_folders(|state| place_actions(state, conversation_id, target_folder_id, index))
225 let target = state
272 .await
226 .folders
227 .iter()
228 .find(|folder| folder.id == target_folder_id)
229 .ok_or_else(|| Error::UnknownFolder(target_folder_id.to_owned()))?;
230 if target
231 .conversation_ids
232 .iter()
233 .any(|id| id == conversation_id)
234 {
235 return Ok(Vec::new());
236 }
237 let mut actions = Vec::new();
238 if let Some(current) = state.containing(conversation_id) {
239 actions.push(remove_item(&current.id, conversation_id));
240 }
241 actions.push(add_item(target_folder_id, conversation_id));
242 Ok(actions)
243 })
244 .await
245 }
273 }
246
274
247 pub async fn remove_from_folder(
275 pub async fn remove_from_folder(
@@ -491,6 +519,72 @@ mod tests {
491 ));
519 ));
492 }
520 }
493
521
522 fn state(folders: &[(&str, FolderKind, &[&str])]) -> Folders {
523 Folders {
524 hierarchy_version: 1,
525 folders: folders
526 .iter()
527 .map(|(id, kind, ids)| Folder {
528 id: (*id).to_owned(),
529 name: (*id).to_owned(),
530 kind: *kind,
531 expanded: true,
532 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
533 })
534 .collect(),
535 order: Vec::new(),
536 }
537 }
538
539 #[test]
540 fn placing_inside_the_same_folder_sends_the_full_new_order() {
541 let folders = state(&[("fav", FolderKind::Favorites, &["a", "b", "c", "d"])]);
542 assert_eq!(
543 place_actions(&folders, "a", "fav", Some(2)).unwrap(),
544 [
545 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["b", "c", "a", "d"]})
546 ]
547 );
548 assert_eq!(
549 place_actions(&folders, "d", "fav", Some(1)).unwrap(),
550 [
551 json!({"action": "ReorderItems", "folderId": "fav", "newItemsOrder": ["a", "d", "b", "c"]})
552 ]
553 );
554 assert!(
555 place_actions(&folders, "b", "fav", Some(1))
556 .unwrap()
557 .is_empty()
558 );
559 assert!(
560 place_actions(&folders, "b", "fav", None)
561 .unwrap()
562 .is_empty()
563 );
564 }
565
566 #[test]
567 fn moving_out_of_favorites_adds_at_the_index_then_removes_like_teams() {
568 let folders = state(&[
569 ("fav", FolderKind::Favorites, &["a"]),
570 ("work", FolderKind::UserCreated, &["b", "c"]),
571 ]);
572 assert_eq!(
573 place_actions(&folders, "a", "work", Some(1)).unwrap(),
574 [
575 json!({"action": "AddItem", "folderId": "work", "itemId": "a", "itemIndex": 1}),
576 json!({"action": "RemoveItem", "folderId": "fav", "itemId": "a"}),
577 ]
578 );
579 assert_eq!(
580 place_actions(&folders, "b", "fav", None).unwrap(),
581 [
582 json!({"action": "AddItem", "folderId": "fav", "itemId": "b"}),
583 json!({"action": "RemoveItem", "folderId": "work", "itemId": "b"}),
584 ]
585 );
586 }
587
494 #[test]
588 #[test]
495 fn write_body_puts_the_lock_before_the_fields() {
589 fn write_body_puts_the_lock_before_the_fields() {
496 let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
590 let write = FolderWrite::reread(Method::Put, Some("a"), json!({"folderName": "B"}));
crates/chatsvc/tests/messages.rs +20 −0
@@ -125,6 +125,26 @@ async fn delete_is_soft_without_a_body() {
125 125 assert!(requests[0].body.is_none());
126 126 }
127 127
128 #[tokio::test]
129 async fn undelete_clears_the_delete_time_property_like_teams() {
130 let mock = Mock::new(&[200]);
131 messages(&mock)
132 .undelete_message(&ConversationRef::chat("19:a@thread.v2"), "m1")
133 .await
134 .unwrap();
135 let requests = mock.requests();
136 assert_eq!(requests.len(), 1);
137 assert_eq!(requests[0].method, Method::Delete);
138 assert_eq!(
139 requests[0].url,
140 format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=deletetime")
141 );
142 assert_eq!(
143 requests[0].body,
144 Some(serde_json::json!({"deletetime": null}))
145 );
146 }
147
128 148 #[tokio::test]
129 149 async fn edit_retries_once_on_404() {
130 150 let mock = Mock::new(&[404, 200]);
@@ -125,6 +125,26 @@ async fn delete_is_soft_without_a_body() {
125 assert!(requests[0].body.is_none());
125 assert!(requests[0].body.is_none());
126}
126}
127
127
128#[tokio::test]
129async fn undelete_clears_the_delete_time_property_like_teams() {
130 let mock = Mock::new(&[200]);
131 messages(&mock)
132 .undelete_message(&ConversationRef::chat("19:a@thread.v2"), "m1")
133 .await
134 .unwrap();
135 let requests = mock.requests();
136 assert_eq!(requests.len(), 1);
137 assert_eq!(requests[0].method, Method::Delete);
138 assert_eq!(
139 requests[0].url,
140 format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=deletetime")
141 );
142 assert_eq!(
143 requests[0].body,
144 Some(serde_json::json!({"deletetime": null}))
145 );
146}
147
128#[tokio::test]
148#[tokio::test]
129async fn edit_retries_once_on_404() {
149async fn edit_retries_once_on_404() {
130 let mock = Mock::new(&[404, 200]);
150 let mock = Mock::new(&[404, 200]);
crates/chatsvc/tests/pins.rs +31 −10
@@ -384,20 +384,23 @@ fn sections(version: i64, custom: &[(&str, &[&str])], pinned: &[&str]) -> Value
384 384 }
385 385
386 386 #[tokio::test]
387 async fn move_to_folder_removes_from_the_current_custom_folder_then_adds_in_one_request() {
387 async fn move_to_folder_adds_then_removes_from_the_current_folder_in_one_request() {
388 388 let mock = Mock::new(vec![
389 389 (200, sections(10, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
390 390 (200, sections(11, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
391 391 ]);
392 let state = pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
392 let state = pins(&mock)
393 .move_to_folder("c", "t~u~B", None)
394 .await
395 .unwrap();
393 396 assert_eq!(state.folders[2].conversation_ids, ["c"]);
394 397 let body = sent(&mock)[1].2.clone().unwrap();
395 398 assert_eq!(body["folderHierarchyVersion"], 10);
396 399 assert_eq!(
397 400 body["actions"],
398 401 json!([
399 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"},
400 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"}
402 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"},
403 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"}
401 404 ])
402 405 );
403 406 }
@@ -408,7 +411,10 @@ async fn move_to_folder_without_a_current_folder_only_adds() {
408 411 (200, sections(10, &[("t~u~B", &[])], &[])),
409 412 (200, sections(11, &[("t~u~B", &["c"])], &[])),
410 413 ]);
411 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
414 pins(&mock)
415 .move_to_folder("c", "t~u~B", None)
416 .await
417 .unwrap();
412 418 assert_eq!(
413 419 sent(&mock)[1].2.as_ref().unwrap()["actions"]
414 420 .as_array()
@@ -425,7 +431,10 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
425 431 (412, sections(15, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
426 432 (200, sections(16, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
427 433 ]);
428 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
434 pins(&mock)
435 .move_to_folder("c", "t~u~B", None)
436 .await
437 .unwrap();
429 438 let retry = sent(&mock)[2].2.clone().unwrap();
430 439 assert_eq!(retry["folderHierarchyVersion"], 15);
431 440 assert_eq!(retry["actions"].as_array().unwrap().len(), 2);
@@ -434,14 +443,20 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
434 443 #[tokio::test]
435 444 async fn move_into_the_folder_it_is_already_in_sends_nothing() {
436 445 let mock = Mock::new(vec![(200, sections(10, &[("t~u~B", &["c"])], &[]))]);
437 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
446 pins(&mock)
447 .move_to_folder("c", "t~u~B", None)
448 .await
449 .unwrap();
438 450 assert_eq!(sent(&mock).len(), 1);
439 451 }
440 452
441 453 #[tokio::test]
442 454 async fn unknown_target_folder_is_typed() {
443 455 let mock = Mock::new(vec![(200, sections(10, &[], &[]))]);
444 let error = pins(&mock).move_to_folder("c", "nope").await.unwrap_err();
456 let error = pins(&mock)
457 .move_to_folder("c", "nope", None)
458 .await
459 .unwrap_err();
445 460 assert!(matches!(error, Error::UnknownFolder(_)));
446 461 }
447 462
@@ -584,13 +599,19 @@ async fn folder_action_posts_still_take_a_full_answer_as_state() {
584 599 (200, partial),
585 600 (200, sections(11, &[("t~u~B", &["c"])], &[])),
586 601 ]);
587 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
602 pins(&mock)
603 .move_to_folder("c", "t~u~B", None)
604 .await
605 .unwrap();
588 606 assert_eq!(sent(&mock).len(), 3);
589 607 let idle = Mock::new(vec![
590 608 (200, sections(10, &[("t~u~B", &[])], &[])),
591 609 (200, sections(11, &[("t~u~B", &["c"])], &[])),
592 610 ]);
593 pins(&idle).move_to_folder("c", "t~u~B").await.unwrap();
611 pins(&idle)
612 .move_to_folder("c", "t~u~B", None)
613 .await
614 .unwrap();
594 615 assert_eq!(sent(&idle).len(), 2);
595 616 }
596 617
@@ -384,20 +384,23 @@ fn sections(version: i64, custom: &[(&str, &[&str])], pinned: &[&str]) -> Value
384}
384}
385
385
386#[tokio::test]
386#[tokio::test]
387async fn move_to_folder_removes_from_the_current_custom_folder_then_adds_in_one_request() {
387async fn move_to_folder_adds_then_removes_from_the_current_folder_in_one_request() {
388 let mock = Mock::new(vec![
388 let mock = Mock::new(vec![
389 (200, sections(10, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
389 (200, sections(10, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
390 (200, sections(11, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
390 (200, sections(11, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
391 ]);
391 ]);
392 let state = pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
392 let state = pins(&mock)
393 .move_to_folder("c", "t~u~B", None)
394 .await
395 .unwrap();
393 assert_eq!(state.folders[2].conversation_ids, ["c"]);
396 assert_eq!(state.folders[2].conversation_ids, ["c"]);
394 let body = sent(&mock)[1].2.clone().unwrap();
397 let body = sent(&mock)[1].2.clone().unwrap();
395 assert_eq!(body["folderHierarchyVersion"], 10);
398 assert_eq!(body["folderHierarchyVersion"], 10);
396 assert_eq!(
399 assert_eq!(
397 body["actions"],
400 body["actions"],
398 json!([
401 json!([
399 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"},
402 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"},
400 {"action": "AddItem", "folderId": "t~u~B", "itemId": "c"}
403 {"action": "RemoveItem", "folderId": "t~u~A", "itemId": "c"}
401 ])
404 ])
402 );
405 );
403}
406}
@@ -408,7 +411,10 @@ async fn move_to_folder_without_a_current_folder_only_adds() {
408 (200, sections(10, &[("t~u~B", &[])], &[])),
411 (200, sections(10, &[("t~u~B", &[])], &[])),
409 (200, sections(11, &[("t~u~B", &["c"])], &[])),
412 (200, sections(11, &[("t~u~B", &["c"])], &[])),
410 ]);
413 ]);
411 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
414 pins(&mock)
415 .move_to_folder("c", "t~u~B", None)
416 .await
417 .unwrap();
412 assert_eq!(
418 assert_eq!(
413 sent(&mock)[1].2.as_ref().unwrap()["actions"]
419 sent(&mock)[1].2.as_ref().unwrap()["actions"]
414 .as_array()
420 .as_array()
@@ -425,7 +431,10 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
425 (412, sections(15, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
431 (412, sections(15, &[("t~u~A", &["c"]), ("t~u~B", &[])], &[])),
426 (200, sections(16, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
432 (200, sections(16, &[("t~u~A", &[]), ("t~u~B", &["c"])], &[])),
427 ]);
433 ]);
428 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
434 pins(&mock)
435 .move_to_folder("c", "t~u~B", None)
436 .await
437 .unwrap();
429 let retry = sent(&mock)[2].2.clone().unwrap();
438 let retry = sent(&mock)[2].2.clone().unwrap();
430 assert_eq!(retry["folderHierarchyVersion"], 15);
439 assert_eq!(retry["folderHierarchyVersion"], 15);
431 assert_eq!(retry["actions"].as_array().unwrap().len(), 2);
440 assert_eq!(retry["actions"].as_array().unwrap().len(), 2);
@@ -434,14 +443,20 @@ async fn move_to_folder_retries_once_and_replans_from_the_412_state() {
434#[tokio::test]
443#[tokio::test]
435async fn move_into_the_folder_it_is_already_in_sends_nothing() {
444async fn move_into_the_folder_it_is_already_in_sends_nothing() {
436 let mock = Mock::new(vec![(200, sections(10, &[("t~u~B", &["c"])], &[]))]);
445 let mock = Mock::new(vec![(200, sections(10, &[("t~u~B", &["c"])], &[]))]);
437 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
446 pins(&mock)
447 .move_to_folder("c", "t~u~B", None)
448 .await
449 .unwrap();
438 assert_eq!(sent(&mock).len(), 1);
450 assert_eq!(sent(&mock).len(), 1);
439}
451}
440
452
441#[tokio::test]
453#[tokio::test]
442async fn unknown_target_folder_is_typed() {
454async fn unknown_target_folder_is_typed() {
443 let mock = Mock::new(vec![(200, sections(10, &[], &[]))]);
455 let mock = Mock::new(vec![(200, sections(10, &[], &[]))]);
444 let error = pins(&mock).move_to_folder("c", "nope").await.unwrap_err();
456 let error = pins(&mock)
457 .move_to_folder("c", "nope", None)
458 .await
459 .unwrap_err();
445 assert!(matches!(error, Error::UnknownFolder(_)));
460 assert!(matches!(error, Error::UnknownFolder(_)));
446}
461}
447
462
@@ -584,13 +599,19 @@ async fn folder_action_posts_still_take_a_full_answer_as_state() {
584 (200, partial),
599 (200, partial),
585 (200, sections(11, &[("t~u~B", &["c"])], &[])),
600 (200, sections(11, &[("t~u~B", &["c"])], &[])),
586 ]);
601 ]);
587 pins(&mock).move_to_folder("c", "t~u~B").await.unwrap();
602 pins(&mock)
603 .move_to_folder("c", "t~u~B", None)
604 .await
605 .unwrap();
588 assert_eq!(sent(&mock).len(), 3);
606 assert_eq!(sent(&mock).len(), 3);
589 let idle = Mock::new(vec![
607 let idle = Mock::new(vec![
590 (200, sections(10, &[("t~u~B", &[])], &[])),
608 (200, sections(10, &[("t~u~B", &[])], &[])),
591 (200, sections(11, &[("t~u~B", &["c"])], &[])),
609 (200, sections(11, &[("t~u~B", &["c"])], &[])),
592 ]);
610 ]);
593 pins(&idle).move_to_folder("c", "t~u~B").await.unwrap();
611 pins(&idle)
612 .move_to_folder("c", "t~u~B", None)
613 .await
614 .unwrap();
594 assert_eq!(sent(&idle).len(), 2);
615 assert_eq!(sent(&idle).len(), 2);
595}
616}
596
617
crates/core/src/actions.rs +35 −0
@@ -501,6 +501,27 @@ impl<R: Remote> SyncEngine<R> {
501 501 Ok(())
502 502 }
503 503
504 pub async fn add_chat_members(
505 &self,
506 chat_id: &str,
507 people: &[store::MemberRecord],
508 share: chatsvc::HistoryShare,
509 ) -> Result<()> {
510 let user_ids: Vec<String> = people
511 .iter()
512 .filter_map(|person| person.user_id.clone())
513 .collect();
514 self.remote
515 .add_chat_members(chat_id, &user_ids, share)
516 .await?;
517 if let Some(mut chat) = self.store.chat(chat_id)? {
518 crate::roster_event::merge_members(&mut chat.members, people);
519 self.store.upsert_chats(std::slice::from_ref(&chat))?;
520 }
521 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
522 Ok(())
523 }
524
504 525 pub async fn send_typing(
505 526 &self,
506 527 conversation_id: &str,
@@ -603,6 +624,20 @@ impl<R: Remote> SyncEngine<R> {
603 624 Ok(())
604 625 }
605 626
627 pub async fn undo_soft_delete_message(
628 &self,
629 conversation_id: &str,
630 message_id: &str,
631 ) -> Result<()> {
632 let target = self.message_target(conversation_id, message_id)?;
633 let user_id = self.my_user_id().await?;
634 self.remote
635 .undo_soft_delete_message(&user_id, &target)
636 .await?;
637 self.refresh_message(conversation_id, message_id).await?;
638 Ok(())
639 }
640
606 641 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
607 642 Ok(match self.resolve_stored(conversation_id)? {
608 643 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
@@ -501,6 +501,27 @@ impl<R: Remote> SyncEngine<R> {
501 Ok(())
501 Ok(())
502 }
502 }
503
503
504 pub async fn add_chat_members(
505 &self,
506 chat_id: &str,
507 people: &[store::MemberRecord],
508 share: chatsvc::HistoryShare,
509 ) -> Result<()> {
510 let user_ids: Vec<String> = people
511 .iter()
512 .filter_map(|person| person.user_id.clone())
513 .collect();
514 self.remote
515 .add_chat_members(chat_id, &user_ids, share)
516 .await?;
517 if let Some(mut chat) = self.store.chat(chat_id)? {
518 crate::roster_event::merge_members(&mut chat.members, people);
519 self.store.upsert_chats(std::slice::from_ref(&chat))?;
520 }
521 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
522 Ok(())
523 }
524
504 pub async fn send_typing(
525 pub async fn send_typing(
505 &self,
526 &self,
506 conversation_id: &str,
527 conversation_id: &str,
@@ -603,6 +624,20 @@ impl<R: Remote> SyncEngine<R> {
603 Ok(())
624 Ok(())
604 }
625 }
605
626
627 pub async fn undo_soft_delete_message(
628 &self,
629 conversation_id: &str,
630 message_id: &str,
631 ) -> Result<()> {
632 let target = self.message_target(conversation_id, message_id)?;
633 let user_id = self.my_user_id().await?;
634 self.remote
635 .undo_soft_delete_message(&user_id, &target)
636 .await?;
637 self.refresh_message(conversation_id, message_id).await?;
638 Ok(())
639 }
640
606 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
641 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
607 Ok(match self.resolve_stored(conversation_id)? {
642 Ok(match self.resolve_stored(conversation_id)? {
608 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
643 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
crates/core/src/avatars.rs +28 −2
@@ -1,4 +1,4 @@
1 use chrono::{Duration, Utc};
1 use chrono::{DateTime, Duration, Utc};
2 2 use store::{AvatarRecord, is_bot_id};
3 3
4 4 use crate::engine::SyncEngine;
@@ -8,6 +8,14 @@ use crate::remote::Remote;
8 8
9 9 const AVATAR_MAX_AGE_DAYS: i64 = 7;
10 10 const AVATAR_BATCH: usize = 60;
11 const PHOTO_RENDITION_SINCE: &str = "2026-10-17T17:00:00Z";
12
13 fn avatar_cutoff(now: DateTime<Utc>) -> DateTime<Utc> {
14 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
15 .map(|since| since.with_timezone(&Utc))
16 .unwrap_or(DateTime::UNIX_EPOCH);
17 (now - Duration::days(AVATAR_MAX_AGE_DAYS)).max(since)
18 }
11 19
12 20 #[derive(Debug, Clone, PartialEq, Eq)]
13 21 pub struct Avatar {
@@ -25,7 +33,7 @@ impl<R: Remote> SyncEngine<R> {
25 33 }
26 34
27 35 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
28 let cutoff = Utc::now() - Duration::days(AVATAR_MAX_AGE_DAYS);
36 let cutoff = avatar_cutoff(Utc::now());
29 37 let mut unique = user_ids.to_vec();
30 38 unique.sort();
31 39 unique.dedup();
@@ -124,3 +132,21 @@ impl<R: Remote> SyncEngine<R> {
124 132 }
125 133 }
126 134 }
135
136 #[cfg(test)]
137 mod tests {
138 use super::*;
139
140 #[test]
141 fn photos_fetched_before_the_larger_rendition_count_as_stale() {
142 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
143 .unwrap()
144 .with_timezone(&Utc);
145 assert_eq!(avatar_cutoff(since + Duration::days(1)), since);
146 let later = since + Duration::days(30);
147 assert_eq!(
148 avatar_cutoff(later),
149 later - Duration::days(AVATAR_MAX_AGE_DAYS)
150 );
151 }
152 }
@@ -1,4 +1,4 @@
1use chrono::{Duration, Utc};
1use chrono::{DateTime, Duration, Utc};
2use store::{AvatarRecord, is_bot_id};
2use store::{AvatarRecord, is_bot_id};
3
3
4use crate::engine::SyncEngine;
4use crate::engine::SyncEngine;
@@ -8,6 +8,14 @@ use crate::remote::Remote;
8
8
9const AVATAR_MAX_AGE_DAYS: i64 = 7;
9const AVATAR_MAX_AGE_DAYS: i64 = 7;
10const AVATAR_BATCH: usize = 60;
10const AVATAR_BATCH: usize = 60;
11const PHOTO_RENDITION_SINCE: &str = "2026-10-17T17:00:00Z";
12
13fn avatar_cutoff(now: DateTime<Utc>) -> DateTime<Utc> {
14 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
15 .map(|since| since.with_timezone(&Utc))
16 .unwrap_or(DateTime::UNIX_EPOCH);
17 (now - Duration::days(AVATAR_MAX_AGE_DAYS)).max(since)
18}
11
19
12#[derive(Debug, Clone, PartialEq, Eq)]
20#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Avatar {
21pub struct Avatar {
@@ -25,7 +33,7 @@ impl<R: Remote> SyncEngine<R> {
25 }
33 }
26
34
27 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
35 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
28 let cutoff = Utc::now() - Duration::days(AVATAR_MAX_AGE_DAYS);
36 let cutoff = avatar_cutoff(Utc::now());
29 let mut unique = user_ids.to_vec();
37 let mut unique = user_ids.to_vec();
30 unique.sort();
38 unique.sort();
31 unique.dedup();
39 unique.dedup();
@@ -124,3 +132,21 @@ impl<R: Remote> SyncEngine<R> {
124 }
132 }
125 }
133 }
126}
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[test]
141 fn photos_fetched_before_the_larger_rendition_count_as_stale() {
142 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
143 .unwrap()
144 .with_timezone(&Utc);
145 assert_eq!(avatar_cutoff(since + Duration::days(1)), since);
146 let later = since + Duration::days(30);
147 assert_eq!(
148 avatar_cutoff(later),
149 later - Duration::days(AVATAR_MAX_AGE_DAYS)
150 );
151 }
152}
crates/core/src/folders.rs +5 −2
@@ -81,6 +81,7 @@ pub trait FolderSource: Send + Sync {
81 81 &'a self,
82 82 conversation_id: &'a str,
83 83 target_folder_id: &'a str,
84 index: Option<usize>,
84 85 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
85 86 fn remove_from_folder<'a>(
86 87 &'a self,
@@ -204,11 +205,12 @@ impl FolderSource for ChatsvcFolderSource {
204 205 &'a self,
205 206 conversation_id: &'a str,
206 207 target_folder_id: &'a str,
208 index: Option<usize>,
207 209 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
208 210 Box::pin(async move {
209 211 Ok(convert(
210 212 self.pins
211 .move_to_folder(conversation_id, target_folder_id)
213 .move_to_folder(conversation_id, target_folder_id, index)
212 214 .await?,
213 215 ))
214 216 })
@@ -543,10 +545,11 @@ impl<R: Remote> SyncEngine<R> {
543 545 &self,
544 546 conversation_id: &str,
545 547 target_folder_id: &str,
548 index: Option<usize>,
546 549 ) -> Result<()> {
547 550 let folders = self
548 551 .folder_source()?
549 .move_to_folder(conversation_id, target_folder_id)
552 .move_to_folder(conversation_id, target_folder_id, index)
550 553 .await?;
551 554 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
552 555 }
@@ -81,6 +81,7 @@ pub trait FolderSource: Send + Sync {
81 &'a self,
81 &'a self,
82 conversation_id: &'a str,
82 conversation_id: &'a str,
83 target_folder_id: &'a str,
83 target_folder_id: &'a str,
84 index: Option<usize>,
84 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
85 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
85 fn remove_from_folder<'a>(
86 fn remove_from_folder<'a>(
86 &'a self,
87 &'a self,
@@ -204,11 +205,12 @@ impl FolderSource for ChatsvcFolderSource {
204 &'a self,
205 &'a self,
205 conversation_id: &'a str,
206 conversation_id: &'a str,
206 target_folder_id: &'a str,
207 target_folder_id: &'a str,
208 index: Option<usize>,
207 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
209 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
208 Box::pin(async move {
210 Box::pin(async move {
209 Ok(convert(
211 Ok(convert(
210 self.pins
212 self.pins
211 .move_to_folder(conversation_id, target_folder_id)
213 .move_to_folder(conversation_id, target_folder_id, index)
212 .await?,
214 .await?,
213 ))
215 ))
214 })
216 })
@@ -543,10 +545,11 @@ impl<R: Remote> SyncEngine<R> {
543 &self,
545 &self,
544 conversation_id: &str,
546 conversation_id: &str,
545 target_folder_id: &str,
547 target_folder_id: &str,
548 index: Option<usize>,
546 ) -> Result<()> {
549 ) -> Result<()> {
547 let folders = self
550 let folders = self
548 .folder_source()?
551 .folder_source()?
549 .move_to_folder(conversation_id, target_folder_id)
552 .move_to_folder(conversation_id, target_folder_id, index)
550 .await?;
553 .await?;
551 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
554 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
552 }
555 }
crates/core/src/lib.rs +1 −0
@@ -49,6 +49,7 @@ mod profile;
49 49 mod receipts;
50 50 mod recording_rights;
51 51 mod remote;
52 pub mod roster_event;
52 53 mod scheduled;
53 54 mod search;
54 55 mod server_search;
@@ -49,6 +49,7 @@ mod profile;
49mod receipts;
49mod receipts;
50mod recording_rights;
50mod recording_rights;
51mod remote;
51mod remote;
52pub mod roster_event;
52mod scheduled;
53mod scheduled;
53mod search;
54mod search;
54mod server_search;
55mod server_search;
crates/core/src/mapping.rs +26 −3
@@ -8,6 +8,7 @@ use crate::forwarded::FORWARDED_CONTENT_TYPE;
8 8 use crate::links::EMPTY_LINKS;
9 9 use crate::markdown::plain_text_to_html;
10 10 use crate::preview::OwnedPreview;
11 use crate::roster_event::RosterEvent;
11 12 use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
12 13
13 14 pub fn graph_hidden(chat: &Chat) -> bool {
@@ -117,7 +118,12 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
117 118 .as_ref()
118 119 .and_then(CallEvent::from_graph)
119 120 .filter(|_| is_system);
120 if is_system && call_event.is_none() {
121 let roster_event = message
122 .event_detail
123 .as_ref()
124 .and_then(|detail| RosterEvent::from_graph(detail, message.created_date_time))
125 .filter(|event| is_system && !event.member_ids.is_empty());
126 if is_system && call_event.is_none() && roster_event.is_none() {
121 127 return None;
122 128 }
123 129 let created_at = message.created_date_time?;
@@ -139,7 +145,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
139 145 created_at,
140 146 edited_at: message.last_edited_date_time,
141 147 deleted,
142 body_html: if deleted || call_event.is_some() {
148 body_html: if deleted || call_event.is_some() || roster_event.is_some() {
143 149 String::new()
144 150 } else {
145 151 body_html(message)
@@ -172,7 +178,10 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
172 178 .map(str::trim)
173 179 .filter(|subject| !subject.is_empty())
174 180 .map(str::to_owned),
175 call_event_json: call_event.as_ref().map(CallEvent::to_json),
181 call_event_json: call_event
182 .as_ref()
183 .map(CallEvent::to_json)
184 .or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),
176 185 })
177 186 }
178 187
@@ -527,6 +536,20 @@ mod tests {
527 536 assert!(call_record("systemEventMessage", json!(null)).is_none());
528 537 }
529 538
539 #[test]
540 fn member_changes_are_kept_as_roster_events() {
541 let detail = json!({
542 "@odata.type": "#microsoft.graph.membersAddedEventMessageDetail",
543 "members": [{"id": "user-ann", "displayName": "Ann"}],
544 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
545 });
546 let record = call_record("systemEventMessage", detail).unwrap();
547 assert!(record.body_html.is_empty());
548 let event = crate::roster_event::roster_event(&record).unwrap();
549 assert_eq!(event.member_ids, ["user-ann"]);
550 assert!(crate::call_event(&record).is_none());
551 }
552
530 553 #[test]
531 554 fn regular_messages_never_become_call_events() {
532 555 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
@@ -8,6 +8,7 @@ use crate::forwarded::FORWARDED_CONTENT_TYPE;
8use crate::links::EMPTY_LINKS;
8use crate::links::EMPTY_LINKS;
9use crate::markdown::plain_text_to_html;
9use crate::markdown::plain_text_to_html;
10use crate::preview::OwnedPreview;
10use crate::preview::OwnedPreview;
11use crate::roster_event::RosterEvent;
11use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
12use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
12
13
13pub fn graph_hidden(chat: &Chat) -> bool {
14pub fn graph_hidden(chat: &Chat) -> bool {
@@ -117,7 +118,12 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
117 .as_ref()
118 .as_ref()
118 .and_then(CallEvent::from_graph)
119 .and_then(CallEvent::from_graph)
119 .filter(|_| is_system);
120 .filter(|_| is_system);
120 if is_system && call_event.is_none() {
121 let roster_event = message
122 .event_detail
123 .as_ref()
124 .and_then(|detail| RosterEvent::from_graph(detail, message.created_date_time))
125 .filter(|event| is_system && !event.member_ids.is_empty());
126 if is_system && call_event.is_none() && roster_event.is_none() {
121 return None;
127 return None;
122 }
128 }
123 let created_at = message.created_date_time?;
129 let created_at = message.created_date_time?;
@@ -139,7 +145,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
139 created_at,
145 created_at,
140 edited_at: message.last_edited_date_time,
146 edited_at: message.last_edited_date_time,
141 deleted,
147 deleted,
142 body_html: if deleted || call_event.is_some() {
148 body_html: if deleted || call_event.is_some() || roster_event.is_some() {
143 String::new()
149 String::new()
144 } else {
150 } else {
145 body_html(message)
151 body_html(message)
@@ -172,7 +178,10 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
172 .map(str::trim)
178 .map(str::trim)
173 .filter(|subject| !subject.is_empty())
179 .filter(|subject| !subject.is_empty())
174 .map(str::to_owned),
180 .map(str::to_owned),
175 call_event_json: call_event.as_ref().map(CallEvent::to_json),
181 call_event_json: call_event
182 .as_ref()
183 .map(CallEvent::to_json)
184 .or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),
176 })
185 })
177}
186}
178
187
@@ -527,6 +536,20 @@ mod tests {
527 assert!(call_record("systemEventMessage", json!(null)).is_none());
536 assert!(call_record("systemEventMessage", json!(null)).is_none());
528 }
537 }
529
538
539 #[test]
540 fn member_changes_are_kept_as_roster_events() {
541 let detail = json!({
542 "@odata.type": "#microsoft.graph.membersAddedEventMessageDetail",
543 "members": [{"id": "user-ann", "displayName": "Ann"}],
544 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
545 });
546 let record = call_record("systemEventMessage", detail).unwrap();
547 assert!(record.body_html.is_empty());
548 let event = crate::roster_event::roster_event(&record).unwrap();
549 assert_eq!(event.member_ids, ["user-ann"]);
550 assert!(crate::call_event(&record).is_none());
551 }
552
530 #[test]
553 #[test]
531 fn regular_messages_never_become_call_events() {
554 fn regular_messages_never_become_call_events() {
532 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
555 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
crates/core/src/preview.rs +6 −2
@@ -5,6 +5,7 @@ use store::{ChatPreview, MessageRecord};
5 5 use crate::call_event::{CallEvent, CallPhase, call_event};
6 6 use crate::external_image::is_giphy_url;
7 7 use crate::forwarded::FORWARDED_CONTENT_TYPE;
8 use crate::roster_event::{RosterChange, roster_event};
8 9 use crate::spans::{Span, html_to_spans};
9 10 use crate::stored::{AttachmentInfo, attachments};
10 11
@@ -249,20 +250,23 @@ impl OwnedPreview {
249 250
250 251 pub(crate) fn from_record(record: &MessageRecord) -> Self {
251 252 let event = call_event(record);
253 let roster = roster_event(record);
252 254 let text = if record.deleted {
253 255 None
254 256 } else if let Some(event) = &event {
255 257 call_phase_preview(event.phase).map(str::to_owned)
258 } else if let Some(roster) = &roster {
259 (roster.change == RosterChange::Added).then(|| USER_ADDED_PREVIEW.to_owned())
256 260 } else {
257 261 message_preview(&record.body_html, &attachments(record))
258 262 };
259 let sender = event.is_none();
263 let sender = event.is_none() && roster.is_none();
260 264 OwnedPreview {
261 265 text,
262 266 sender_id: record.sender_id.clone().filter(|_| sender),
263 267 sender_name: record.sender_name.clone().filter(|_| sender),
264 268 deleted: record.deleted,
265 system: event.is_some(),
269 system: !sender,
266 270 call: event.is_some_and(|event| event.phase.is_call()),
267 271 }
268 272 }
@@ -5,6 +5,7 @@ use store::{ChatPreview, MessageRecord};
5use crate::call_event::{CallEvent, CallPhase, call_event};
5use crate::call_event::{CallEvent, CallPhase, call_event};
6use crate::external_image::is_giphy_url;
6use crate::external_image::is_giphy_url;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
8use crate::roster_event::{RosterChange, roster_event};
8use crate::spans::{Span, html_to_spans};
9use crate::spans::{Span, html_to_spans};
9use crate::stored::{AttachmentInfo, attachments};
10use crate::stored::{AttachmentInfo, attachments};
10
11
@@ -249,20 +250,23 @@ impl OwnedPreview {
249
250
250 pub(crate) fn from_record(record: &MessageRecord) -> Self {
251 pub(crate) fn from_record(record: &MessageRecord) -> Self {
251 let event = call_event(record);
252 let event = call_event(record);
253 let roster = roster_event(record);
252 let text = if record.deleted {
254 let text = if record.deleted {
253 None
255 None
254 } else if let Some(event) = &event {
256 } else if let Some(event) = &event {
255 call_phase_preview(event.phase).map(str::to_owned)
257 call_phase_preview(event.phase).map(str::to_owned)
258 } else if let Some(roster) = &roster {
259 (roster.change == RosterChange::Added).then(|| USER_ADDED_PREVIEW.to_owned())
256 } else {
260 } else {
257 message_preview(&record.body_html, &attachments(record))
261 message_preview(&record.body_html, &attachments(record))
258 };
262 };
259 let sender = event.is_none();
263 let sender = event.is_none() && roster.is_none();
260 OwnedPreview {
264 OwnedPreview {
261 text,
265 text,
262 sender_id: record.sender_id.clone().filter(|_| sender),
266 sender_id: record.sender_id.clone().filter(|_| sender),
263 sender_name: record.sender_name.clone().filter(|_| sender),
267 sender_name: record.sender_name.clone().filter(|_| sender),
264 deleted: record.deleted,
268 deleted: record.deleted,
265 system: event.is_some(),
269 system: !sender,
266 call: event.is_some_and(|event| event.phase.is_call()),
270 call: event.is_some_and(|event| event.phase.is_call()),
267 }
271 }
268 }
272 }
crates/core/src/remote.rs +37 −7
@@ -8,12 +8,13 @@ use chatsvc::{
8 8 };
9 9 use chatsvc::{
10 10 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
11 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,
12 InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,
13 MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,
14 PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,
15 ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,
16 Translator, WindowDirection, WorkLocationKind,
11 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
12 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
13 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
14 PinnedMessage, Pins, PresenceLookup, PresenceService, PresenceStatus, Receipts,
15 RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,
16 TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,
17 WorkLocationKind,
17 18 };
18 19 use chrono::{DateTime, Utc};
19 20 use graph::{
@@ -130,6 +131,12 @@ pub trait Remote {
130 131 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
131 132 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
132 133 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
134 async fn add_chat_members(
135 &self,
136 chat_id: &str,
137 user_ids: &[String],
138 share: HistoryShare,
139 ) -> Result<()>;
133 140 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
134 141 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
135 142 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
@@ -149,6 +156,7 @@ pub trait Remote {
149 156 extras: &MessageExtras,
150 157 ) -> Result<()>;
151 158 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
159 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
152 160 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
153 161 async fn create_group(
154 162 &self,
@@ -704,7 +712,20 @@ impl Remote for Graph {
704 712 }
705 713
706 714 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
707 Ok(Graph::remove_chat_member(self, chat_id, user_id).await?)
715 Ok(ThreadMembers::new(self.session())
716 .remove(chat_id, user_id)
717 .await?)
718 }
719
720 async fn add_chat_members(
721 &self,
722 chat_id: &str,
723 user_ids: &[String],
724 share: HistoryShare,
725 ) -> Result<()> {
726 Ok(ThreadMembers::new(self.session())
727 .add(chat_id, user_ids, share, Utc::now().timestamp_millis())
728 .await?)
708 729 }
709 730
710 731 async fn chat_states(&self) -> Result<Vec<ConversationState>> {
@@ -794,6 +815,15 @@ impl Remote for Graph {
794 815 }
795 816 }
796 817
818 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
819 match chatsvc_conversation(target) {
820 Some(conversation) => Ok(Messages::new(self.session())
821 .undelete_message(&conversation, target.message_id())
822 .await?),
823 None => Ok(Graph::undo_soft_delete_message(self, user_id, target).await?),
824 }
825 }
826
797 827 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
798 828 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
799 829 }
@@ -8,12 +8,13 @@ use chatsvc::{
8};
8};
9use chatsvc::{
9use chatsvc::{
10 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
10 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
11 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,
11 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
12 InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,
12 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
13 MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,
13 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
14 PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,
14 PinnedMessage, Pins, PresenceLookup, PresenceService, PresenceStatus, Receipts,
15 ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,
15 RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,
16 Translator, WindowDirection, WorkLocationKind,
16 TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,
17 WorkLocationKind,
17};
18};
18use chrono::{DateTime, Utc};
19use chrono::{DateTime, Utc};
19use graph::{
20use graph::{
@@ -130,6 +131,12 @@ pub trait Remote {
130 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
131 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
131 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
132 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
132 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
133 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
134 async fn add_chat_members(
135 &self,
136 chat_id: &str,
137 user_ids: &[String],
138 share: HistoryShare,
139 ) -> Result<()>;
133 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
140 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
134 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
141 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
135 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
142 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
@@ -149,6 +156,7 @@ pub trait Remote {
149 extras: &MessageExtras,
156 extras: &MessageExtras,
150 ) -> Result<()>;
157 ) -> Result<()>;
151 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
158 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
159 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
152 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
160 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
153 async fn create_group(
161 async fn create_group(
154 &self,
162 &self,
@@ -704,7 +712,20 @@ impl Remote for Graph {
704 }
712 }
705
713
706 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
714 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
707 Ok(Graph::remove_chat_member(self, chat_id, user_id).await?)
715 Ok(ThreadMembers::new(self.session())
716 .remove(chat_id, user_id)
717 .await?)
718 }
719
720 async fn add_chat_members(
721 &self,
722 chat_id: &str,
723 user_ids: &[String],
724 share: HistoryShare,
725 ) -> Result<()> {
726 Ok(ThreadMembers::new(self.session())
727 .add(chat_id, user_ids, share, Utc::now().timestamp_millis())
728 .await?)
708 }
729 }
709
730
710 async fn chat_states(&self) -> Result<Vec<ConversationState>> {
731 async fn chat_states(&self) -> Result<Vec<ConversationState>> {
@@ -794,6 +815,15 @@ impl Remote for Graph {
794 }
815 }
795 }
816 }
796
817
818 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
819 match chatsvc_conversation(target) {
820 Some(conversation) => Ok(Messages::new(self.session())
821 .undelete_message(&conversation, target.message_id())
822 .await?),
823 None => Ok(Graph::undo_soft_delete_message(self, user_id, target).await?),
824 }
825 }
826
797 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
827 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
798 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
828 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
799 }
829 }
crates/core/src/roster_event.rs added +302 −0
@@ -0,0 +1,302 @@
1 use chrono::{DateTime, Datelike, Utc};
2 use serde::{Deserialize, Serialize};
3 use serde_json::Value;
4 use store::{MemberRecord, MessageRecord};
5
6 const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7 const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8 const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9 const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10 const DAY_SECONDS: i64 = 86_400;
11
12 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13 pub enum RosterChange {
14 Added,
15 Removed,
16 Left,
17 }
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
20 pub enum SharedHistory {
21 #[default]
22 None,
23 Days(u32),
24 All,
25 }
26
27 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28 pub struct RosterEvent {
29 pub change: RosterChange,
30 pub initiator_id: Option<String>,
31 pub initiator_name: Option<String>,
32 pub member_ids: Vec<String>,
33 pub member_names: Vec<Option<String>>,
34 #[serde(default)]
35 pub history: SharedHistory,
36 }
37
38 #[derive(Serialize, Deserialize)]
39 struct StoredRoster {
40 roster: RosterEvent,
41 }
42
43 impl RosterEvent {
44 pub fn from_graph(detail: &Value, created_at: Option<DateTime<Utc>>) -> Option<RosterEvent> {
45 let kind = detail.get("@odata.type")?.as_str()?;
46 let members: Vec<(String, Option<String>)> = detail
47 .get("members")
48 .and_then(Value::as_array)
49 .into_iter()
50 .flatten()
51 .filter_map(|member| {
52 let user_id = member.get("id")?.as_str()?.to_owned();
53 Some((user_id, display_name(member)))
54 })
55 .collect();
56 let initiator = detail
57 .pointer("/initiator/user")
58 .or_else(|| detail.pointer("/initiator/application"));
59 let initiator_id = initiator
60 .and_then(|identity| identity.get("id"))
61 .and_then(Value::as_str)
62 .map(str::to_owned);
63 let only_initiator =
64 members.len() == 1 && initiator_id.as_deref() == Some(members[0].0.as_str());
65 let change = match kind {
66 MEMBERS_ADDED_TYPE => RosterChange::Added,
67 MEMBERS_LEFT_TYPE => RosterChange::Left,
68 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69 MEMBERS_DELETED_TYPE => RosterChange::Removed,
70 _ => return None,
71 };
72 let history = match change {
73 RosterChange::Added => shared_history(
74 detail
75 .get("visibleHistoryStartDateTime")
76 .and_then(Value::as_str),
77 created_at,
78 ),
79 _ => SharedHistory::None,
80 };
81 let (member_ids, member_names) = members.into_iter().unzip();
82 Some(RosterEvent {
83 change,
84 initiator_name: initiator.and_then(display_name),
85 initiator_id,
86 member_ids,
87 member_names,
88 history,
89 })
90 }
91
92 pub fn from_json(json: &str) -> Option<RosterEvent> {
93 serde_json::from_str::<StoredRoster>(json)
94 .ok()
95 .map(|stored| stored.roster)
96 }
97
98 pub fn to_json(&self) -> String {
99 serde_json::to_string(&StoredRoster {
100 roster: self.clone(),
101 })
102 .unwrap_or_default()
103 }
104
105 /// Teams wording; `name_of` gets each user id with the name the event carries.
106 pub fn text(&self, name_of: impl Fn(Option<&str>, Option<&str>) -> String) -> String {
107 let initiator = name_of(self.initiator_id.as_deref(), self.initiator_name.as_deref());
108 let targets: Vec<String> = self
109 .member_ids
110 .iter()
111 .zip(&self.member_names)
112 .map(|(user_id, name)| name_of(Some(user_id), name.as_deref()))
113 .collect();
114 let targets = join_targets(&targets);
115 match self.change {
116 RosterChange::Left => format!("{initiator} left the chat."),
117 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118 RosterChange::Added => match self.history {
119 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
120 SharedHistory::All => {
121 format!("{initiator} added {targets} to the chat and shared all chat history.")
122 }
123 SharedHistory::Days(1) => format!(
124 "{initiator} added {targets} to the chat and shared chat history from the past day."
125 ),
126 SharedHistory::Days(days) => format!(
127 "{initiator} added {targets} to the chat and shared chat history from the past {days} days."
128 ),
129 },
130 }
131 }
132 }
133
134 pub fn roster_event(record: &MessageRecord) -> Option<RosterEvent> {
135 RosterEvent::from_json(record.call_event_json.as_deref()?)
136 }
137
138 pub fn merge_members(members: &mut Vec<MemberRecord>, added: &[MemberRecord]) {
139 for person in added {
140 let known = members
141 .iter()
142 .any(|member| member.user_id.is_some() && member.user_id == person.user_id);
143 if !known {
144 members.push(person.clone());
145 }
146 }
147 }
148
149 fn join_targets(targets: &[String]) -> String {
150 match targets {
151 [] => String::new(),
152 [only] => only.clone(),
153 [first, second] => format!("{first} and {second}"),
154 [first, rest @ ..] => format!("{first} and {} others", rest.len()),
155 }
156 }
157
158 fn display_name(identity: &Value) -> Option<String> {
159 identity
160 .get("displayName")
161 .and_then(Value::as_str)
162 .map(str::trim)
163 .filter(|name| !name.is_empty() && !name.starts_with(UNRESOLVED_NAME_PREFIX))
164 .map(str::to_owned)
165 }
166
167 fn shared_history(visible_from: Option<&str>, created_at: Option<DateTime<Utc>>) -> SharedHistory {
168 let Some(visible_from) = visible_from.and_then(|text| DateTime::parse_from_rfc3339(text).ok())
169 else {
170 return SharedHistory::None;
171 };
172 if visible_from.year() <= 1 {
173 return SharedHistory::All;
174 }
175 let Some(created_at) = created_at else {
176 return SharedHistory::None;
177 };
178 let seconds = (created_at - visible_from.with_timezone(&Utc)).num_seconds();
179 match (seconds + DAY_SECONDS / 2) / DAY_SECONDS {
180 days if days >= 1 => SharedHistory::Days(u32::try_from(days).unwrap_or(u32::MAX)),
181 _ => SharedHistory::None,
182 }
183 }
184
185 #[cfg(test)]
186 mod tests {
187 use chrono::TimeZone;
188 use serde_json::json;
189
190 use super::*;
191
192 fn created() -> Option<DateTime<Utc>> {
193 Some(Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap())
194 }
195
196 fn added(members: Value, visible_from: Value) -> RosterEvent {
197 RosterEvent::from_graph(
198 &json!({
199 "@odata.type": MEMBERS_ADDED_TYPE,
200 "visibleHistoryStartDateTime": visible_from,
201 "members": members,
202 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
203 }),
204 created(),
205 )
206 .unwrap()
207 }
208
209 fn plain_names(user_id: Option<&str>, name: Option<&str>) -> String {
210 name.or(user_id).unwrap_or("Unknown").to_owned()
211 }
212
213 #[test]
214 fn added_without_history_reads_like_teams() {
215 let event = added(
216 json!([{"id": "ann", "displayName": "Ann"}]),
217 json!("2026-10-17T09:00:00Z"),
218 );
219 assert_eq!(event.history, SharedHistory::None);
220 assert_eq!(event.text(plain_names), "Daniel added Ann to the chat.");
221 }
222
223 #[test]
224 fn shared_history_is_all_or_rounded_days() {
225 let all = added(json!([{"id": "ann"}]), json!("0001-01-01T00:00:00Z"));
226 assert_eq!(all.history, SharedHistory::All);
227 assert_eq!(
228 all.text(plain_names),
229 "Daniel added ann to the chat and shared all chat history."
230 );
231 let one = added(json!([{"id": "ann"}]), json!("2026-10-16T08:59:58Z"));
232 assert_eq!(
233 one.text(plain_names),
234 "Daniel added ann to the chat and shared chat history from the past day."
235 );
236 let week = added(json!([{"id": "ann"}]), json!("2026-10-10T09:00:00Z"));
237 assert_eq!(week.history, SharedHistory::Days(7));
238 }
239
240 #[test]
241 fn targets_join_with_and_then_count_the_rest() {
242 let two = added(json!([{"id": "ann"}, {"id": "bob"}]), Value::Null);
243 assert_eq!(
244 two.text(plain_names),
245 "Daniel added ann and bob to the chat."
246 );
247 let four = added(
248 json!([{"id": "ann"}, {"id": "bob"}, {"id": "cid"}, {"id": "dan"}]),
249 Value::Null,
250 );
251 assert_eq!(
252 four.text(plain_names),
253 "Daniel added ann and 3 others to the chat."
254 );
255 }
256
257 #[test]
258 fn self_removal_is_leaving() {
259 let detail = json!({
260 "@odata.type": MEMBERS_DELETED_TYPE,
261 "members": [{"id": "me"}],
262 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
263 });
264 let event = RosterEvent::from_graph(&detail, created()).unwrap();
265 assert_eq!(event.change, RosterChange::Left);
266 assert_eq!(event.text(plain_names), "Daniel left the chat.");
267 let mut removed = detail.clone();
268 removed["members"] = json!([{"id": "ann", "displayName": "Ann"}]);
269 let event = RosterEvent::from_graph(&removed, created()).unwrap();
270 assert_eq!(event.text(plain_names), "Daniel removed Ann from the chat.");
271 }
272
273 #[test]
274 fn stored_json_round_trips_and_is_not_a_call_event() {
275 let event = added(json!([{"id": "ann"}]), Value::Null);
276 let json = event.to_json();
277 assert_eq!(RosterEvent::from_json(&json), Some(event));
278 assert!(crate::CallEvent::from_json(&json).is_none());
279 assert!(RosterEvent::from_json("{\"phase\":\"Ended\"}").is_none());
280 }
281
282 #[test]
283 fn other_events_are_not_roster_changes() {
284 let joined = json!({"@odata.type": "#microsoft.graph.membersJoinedEventMessageDetail"});
285 assert!(RosterEvent::from_graph(&joined, created()).is_none());
286 }
287
288 #[test]
289 fn merging_skips_known_members() {
290 let member = |user_id: &str| MemberRecord {
291 user_id: Some(user_id.to_owned()),
292 display_name: user_id.to_owned(),
293 };
294 let mut members = vec![member("me"), member("ann")];
295 merge_members(&mut members, &[member("ann"), member("bob")]);
296 let ids: Vec<_> = members
297 .iter()
298 .filter_map(|record| record.user_id.clone())
299 .collect();
300 assert_eq!(ids, ["me", "ann", "bob"]);
301 }
302 }
@@ -0,0 +1,302 @@
1use chrono::{DateTime, Datelike, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use store::{MemberRecord, MessageRecord};
5
6const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10const DAY_SECONDS: i64 = 86_400;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13pub enum RosterChange {
14 Added,
15 Removed,
16 Left,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
20pub enum SharedHistory {
21 #[default]
22 None,
23 Days(u32),
24 All,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct RosterEvent {
29 pub change: RosterChange,
30 pub initiator_id: Option<String>,
31 pub initiator_name: Option<String>,
32 pub member_ids: Vec<String>,
33 pub member_names: Vec<Option<String>>,
34 #[serde(default)]
35 pub history: SharedHistory,
36}
37
38#[derive(Serialize, Deserialize)]
39struct StoredRoster {
40 roster: RosterEvent,
41}
42
43impl RosterEvent {
44 pub fn from_graph(detail: &Value, created_at: Option<DateTime<Utc>>) -> Option<RosterEvent> {
45 let kind = detail.get("@odata.type")?.as_str()?;
46 let members: Vec<(String, Option<String>)> = detail
47 .get("members")
48 .and_then(Value::as_array)
49 .into_iter()
50 .flatten()
51 .filter_map(|member| {
52 let user_id = member.get("id")?.as_str()?.to_owned();
53 Some((user_id, display_name(member)))
54 })
55 .collect();
56 let initiator = detail
57 .pointer("/initiator/user")
58 .or_else(|| detail.pointer("/initiator/application"));
59 let initiator_id = initiator
60 .and_then(|identity| identity.get("id"))
61 .and_then(Value::as_str)
62 .map(str::to_owned);
63 let only_initiator =
64 members.len() == 1 && initiator_id.as_deref() == Some(members[0].0.as_str());
65 let change = match kind {
66 MEMBERS_ADDED_TYPE => RosterChange::Added,
67 MEMBERS_LEFT_TYPE => RosterChange::Left,
68 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69 MEMBERS_DELETED_TYPE => RosterChange::Removed,
70 _ => return None,
71 };
72 let history = match change {
73 RosterChange::Added => shared_history(
74 detail
75 .get("visibleHistoryStartDateTime")
76 .and_then(Value::as_str),
77 created_at,
78 ),
79 _ => SharedHistory::None,
80 };
81 let (member_ids, member_names) = members.into_iter().unzip();
82 Some(RosterEvent {
83 change,
84 initiator_name: initiator.and_then(display_name),
85 initiator_id,
86 member_ids,
87 member_names,
88 history,
89 })
90 }
91
92 pub fn from_json(json: &str) -> Option<RosterEvent> {
93 serde_json::from_str::<StoredRoster>(json)
94 .ok()
95 .map(|stored| stored.roster)
96 }
97
98 pub fn to_json(&self) -> String {
99 serde_json::to_string(&StoredRoster {
100 roster: self.clone(),
101 })
102 .unwrap_or_default()
103 }
104
105 /// Teams wording; `name_of` gets each user id with the name the event carries.
106 pub fn text(&self, name_of: impl Fn(Option<&str>, Option<&str>) -> String) -> String {
107 let initiator = name_of(self.initiator_id.as_deref(), self.initiator_name.as_deref());
108 let targets: Vec<String> = self
109 .member_ids
110 .iter()
111 .zip(&self.member_names)
112 .map(|(user_id, name)| name_of(Some(user_id), name.as_deref()))
113 .collect();
114 let targets = join_targets(&targets);
115 match self.change {
116 RosterChange::Left => format!("{initiator} left the chat."),
117 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118 RosterChange::Added => match self.history {
119 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
120 SharedHistory::All => {
121 format!("{initiator} added {targets} to the chat and shared all chat history.")
122 }
123 SharedHistory::Days(1) => format!(
124 "{initiator} added {targets} to the chat and shared chat history from the past day."
125 ),
126 SharedHistory::Days(days) => format!(
127 "{initiator} added {targets} to the chat and shared chat history from the past {days} days."
128 ),
129 },
130 }
131 }
132}
133
134pub fn roster_event(record: &MessageRecord) -> Option<RosterEvent> {
135 RosterEvent::from_json(record.call_event_json.as_deref()?)
136}
137
138pub fn merge_members(members: &mut Vec<MemberRecord>, added: &[MemberRecord]) {
139 for person in added {
140 let known = members
141 .iter()
142 .any(|member| member.user_id.is_some() && member.user_id == person.user_id);
143 if !known {
144 members.push(person.clone());
145 }
146 }
147}
148
149fn join_targets(targets: &[String]) -> String {
150 match targets {
151 [] => String::new(),
152 [only] => only.clone(),
153 [first, second] => format!("{first} and {second}"),
154 [first, rest @ ..] => format!("{first} and {} others", rest.len()),
155 }
156}
157
158fn display_name(identity: &Value) -> Option<String> {
159 identity
160 .get("displayName")
161 .and_then(Value::as_str)
162 .map(str::trim)
163 .filter(|name| !name.is_empty() && !name.starts_with(UNRESOLVED_NAME_PREFIX))
164 .map(str::to_owned)
165}
166
167fn shared_history(visible_from: Option<&str>, created_at: Option<DateTime<Utc>>) -> SharedHistory {
168 let Some(visible_from) = visible_from.and_then(|text| DateTime::parse_from_rfc3339(text).ok())
169 else {
170 return SharedHistory::None;
171 };
172 if visible_from.year() <= 1 {
173 return SharedHistory::All;
174 }
175 let Some(created_at) = created_at else {
176 return SharedHistory::None;
177 };
178 let seconds = (created_at - visible_from.with_timezone(&Utc)).num_seconds();
179 match (seconds + DAY_SECONDS / 2) / DAY_SECONDS {
180 days if days >= 1 => SharedHistory::Days(u32::try_from(days).unwrap_or(u32::MAX)),
181 _ => SharedHistory::None,
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use chrono::TimeZone;
188 use serde_json::json;
189
190 use super::*;
191
192 fn created() -> Option<DateTime<Utc>> {
193 Some(Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap())
194 }
195
196 fn added(members: Value, visible_from: Value) -> RosterEvent {
197 RosterEvent::from_graph(
198 &json!({
199 "@odata.type": MEMBERS_ADDED_TYPE,
200 "visibleHistoryStartDateTime": visible_from,
201 "members": members,
202 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
203 }),
204 created(),
205 )
206 .unwrap()
207 }
208
209 fn plain_names(user_id: Option<&str>, name: Option<&str>) -> String {
210 name.or(user_id).unwrap_or("Unknown").to_owned()
211 }
212
213 #[test]
214 fn added_without_history_reads_like_teams() {
215 let event = added(
216 json!([{"id": "ann", "displayName": "Ann"}]),
217 json!("2026-10-17T09:00:00Z"),
218 );
219 assert_eq!(event.history, SharedHistory::None);
220 assert_eq!(event.text(plain_names), "Daniel added Ann to the chat.");
221 }
222
223 #[test]
224 fn shared_history_is_all_or_rounded_days() {
225 let all = added(json!([{"id": "ann"}]), json!("0001-01-01T00:00:00Z"));
226 assert_eq!(all.history, SharedHistory::All);
227 assert_eq!(
228 all.text(plain_names),
229 "Daniel added ann to the chat and shared all chat history."
230 );
231 let one = added(json!([{"id": "ann"}]), json!("2026-10-16T08:59:58Z"));
232 assert_eq!(
233 one.text(plain_names),
234 "Daniel added ann to the chat and shared chat history from the past day."
235 );
236 let week = added(json!([{"id": "ann"}]), json!("2026-10-10T09:00:00Z"));
237 assert_eq!(week.history, SharedHistory::Days(7));
238 }
239
240 #[test]
241 fn targets_join_with_and_then_count_the_rest() {
242 let two = added(json!([{"id": "ann"}, {"id": "bob"}]), Value::Null);
243 assert_eq!(
244 two.text(plain_names),
245 "Daniel added ann and bob to the chat."
246 );
247 let four = added(
248 json!([{"id": "ann"}, {"id": "bob"}, {"id": "cid"}, {"id": "dan"}]),
249 Value::Null,
250 );
251 assert_eq!(
252 four.text(plain_names),
253 "Daniel added ann and 3 others to the chat."
254 );
255 }
256
257 #[test]
258 fn self_removal_is_leaving() {
259 let detail = json!({
260 "@odata.type": MEMBERS_DELETED_TYPE,
261 "members": [{"id": "me"}],
262 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
263 });
264 let event = RosterEvent::from_graph(&detail, created()).unwrap();
265 assert_eq!(event.change, RosterChange::Left);
266 assert_eq!(event.text(plain_names), "Daniel left the chat.");
267 let mut removed = detail.clone();
268 removed["members"] = json!([{"id": "ann", "displayName": "Ann"}]);
269 let event = RosterEvent::from_graph(&removed, created()).unwrap();
270 assert_eq!(event.text(plain_names), "Daniel removed Ann from the chat.");
271 }
272
273 #[test]
274 fn stored_json_round_trips_and_is_not_a_call_event() {
275 let event = added(json!([{"id": "ann"}]), Value::Null);
276 let json = event.to_json();
277 assert_eq!(RosterEvent::from_json(&json), Some(event));
278 assert!(crate::CallEvent::from_json(&json).is_none());
279 assert!(RosterEvent::from_json("{\"phase\":\"Ended\"}").is_none());
280 }
281
282 #[test]
283 fn other_events_are_not_roster_changes() {
284 let joined = json!({"@odata.type": "#microsoft.graph.membersJoinedEventMessageDetail"});
285 assert!(RosterEvent::from_graph(&joined, created()).is_none());
286 }
287
288 #[test]
289 fn merging_skips_known_members() {
290 let member = |user_id: &str| MemberRecord {
291 user_id: Some(user_id.to_owned()),
292 display_name: user_id.to_owned(),
293 };
294 let mut members = vec![member("me"), member("ann")];
295 merge_members(&mut members, &[member("ann"), member("bob")]);
296 let ids: Vec<_> = members
297 .iter()
298 .filter_map(|record| record.user_id.clone())
299 .collect();
300 assert_eq!(ids, ["me", "ann", "bob"]);
301 }
302}
crates/core/tests/engine.rs +54 −2
@@ -558,6 +558,19 @@ impl Remote for Handle {
558 558 Ok(())
559 559 }
560 560
561 async fn add_chat_members(
562 &self,
563 chat_id: &str,
564 user_ids: &[String],
565 share: chatsvc::HistoryShare,
566 ) -> Result<()> {
567 self.record(format!(
568 "add members {chat_id} {} {share:?}",
569 user_ids.join(",")
570 ));
571 Ok(())
572 }
573
561 574 async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {
562 575 if *self.muted_fails.lock().unwrap() {
563 576 return Err(Error::Unsupported("forced failure"));
@@ -663,6 +676,11 @@ impl Remote for Handle {
663 676 Ok(())
664 677 }
665 678
679 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
680 self.record(format!("undo_soft_delete {user_id} {}", describe(target)));
681 Ok(())
682 }
683
666 684 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
667 685 self.record(format!("one_on_one {my_user_id} {user_id}"));
668 686 Ok(chat("19:new@thread.v2", None, 40, 40, ME, false))
@@ -1500,6 +1518,34 @@ async fn removing_a_member_drops_them_from_the_cached_chat() {
1500 1518 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1501 1519 }
1502 1520
1521 #[tokio::test]
1522 async fn adding_members_writes_them_and_extends_the_cached_chat() {
1523 let fake = Arc::new(Fake::default());
1524 let engine = chat_engine(&fake, small_pages()).await;
1525 let mut events = engine.subscribe();
1526 let people = [store::MemberRecord {
1527 user_id: Some("user-bob".to_owned()),
1528 display_name: "Bob".to_owned(),
1529 }];
1530
1531 engine
1532 .add_chat_members(CHAT, &people, chatsvc::HistoryShare::Days(7))
1533 .await
1534 .unwrap();
1535 assert_eq!(
1536 fake.calls().last().unwrap(),
1537 &format!("add members {CHAT} user-bob Days(7)")
1538 );
1539 let chats = engine.sidebar().unwrap().chats;
1540 assert!(
1541 chats[0]
1542 .members
1543 .iter()
1544 .any(|member| member.user_id.as_deref() == Some("user-bob"))
1545 );
1546 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1547 }
1548
1503 1549 #[tokio::test]
1504 1550 async fn failing_channel_listing_is_reported_not_fatal() {
1505 1551 let fake = Arc::new(Fake::default());
@@ -2564,12 +2610,17 @@ async fn chat_actions_call_graph_with_the_right_ids() {
2564 2610 .await
2565 2611 .unwrap();
2566 2612 engine.soft_delete_message(CHAT, "m0003").await.unwrap();
2613 engine
2614 .undo_soft_delete_message(CHAT, "m0003")
2615 .await
2616 .unwrap();
2567 2617 let calls = fake.calls();
2568 2618 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2569 2619 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2570 2620 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2571 2621 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2572 2622 assert!(calls.contains(&format!("soft_delete {ME} m0003")));
2623 assert!(calls.contains(&format!("undo_soft_delete {ME} m0003")));
2573 2624 assert!(!engine.sidebar().unwrap().chats[0].unread);
2574 2625 }
2575 2626
@@ -3072,6 +3123,7 @@ impl FolderSource for FakeFolders {
3072 3123 &'a self,
3073 3124 conversation_id: &'a str,
3074 3125 target_folder_id: &'a str,
3126 _index: Option<usize>,
3075 3127 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
3076 3128 Box::pin(async move {
3077 3129 self.calls
@@ -3226,7 +3278,7 @@ async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() {
3226 3278 engine.refresh_folders().await.unwrap();
3227 3279 assert!(events.try_recv().is_err());
3228 3280
3229 engine.move_to_folder("a", "work").await.unwrap();
3281 engine.move_to_folder("a", "work", None).await.unwrap();
3230 3282 assert_eq!(
3231 3283 engine.chat_folders().unwrap()[1].conversation_ids,
3232 3284 ids(&["c", "a"])
@@ -3490,7 +3542,7 @@ async fn folders_without_a_source_are_unsupported() {
3490 3542 Err(Error::Unsupported(_))
3491 3543 ));
3492 3544 assert!(matches!(
3493 engine.move_to_folder("a", "b").await,
3545 engine.move_to_folder("a", "b", None).await,
3494 3546 Err(Error::Unsupported(_))
3495 3547 ));
3496 3548 }
@@ -558,6 +558,19 @@ impl Remote for Handle {
558 Ok(())
558 Ok(())
559 }
559 }
560
560
561 async fn add_chat_members(
562 &self,
563 chat_id: &str,
564 user_ids: &[String],
565 share: chatsvc::HistoryShare,
566 ) -> Result<()> {
567 self.record(format!(
568 "add members {chat_id} {} {share:?}",
569 user_ids.join(",")
570 ));
571 Ok(())
572 }
573
561 async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {
574 async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {
562 if *self.muted_fails.lock().unwrap() {
575 if *self.muted_fails.lock().unwrap() {
563 return Err(Error::Unsupported("forced failure"));
576 return Err(Error::Unsupported("forced failure"));
@@ -663,6 +676,11 @@ impl Remote for Handle {
663 Ok(())
676 Ok(())
664 }
677 }
665
678
679 async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> {
680 self.record(format!("undo_soft_delete {user_id} {}", describe(target)));
681 Ok(())
682 }
683
666 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
684 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
667 self.record(format!("one_on_one {my_user_id} {user_id}"));
685 self.record(format!("one_on_one {my_user_id} {user_id}"));
668 Ok(chat("19:new@thread.v2", None, 40, 40, ME, false))
686 Ok(chat("19:new@thread.v2", None, 40, 40, ME, false))
@@ -1500,6 +1518,34 @@ async fn removing_a_member_drops_them_from_the_cached_chat() {
1500 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1518 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1501}
1519}
1502
1520
1521#[tokio::test]
1522async fn adding_members_writes_them_and_extends_the_cached_chat() {
1523 let fake = Arc::new(Fake::default());
1524 let engine = chat_engine(&fake, small_pages()).await;
1525 let mut events = engine.subscribe();
1526 let people = [store::MemberRecord {
1527 user_id: Some("user-bob".to_owned()),
1528 display_name: "Bob".to_owned(),
1529 }];
1530
1531 engine
1532 .add_chat_members(CHAT, &people, chatsvc::HistoryShare::Days(7))
1533 .await
1534 .unwrap();
1535 assert_eq!(
1536 fake.calls().last().unwrap(),
1537 &format!("add members {CHAT} user-bob Days(7)")
1538 );
1539 let chats = engine.sidebar().unwrap().chats;
1540 assert!(
1541 chats[0]
1542 .members
1543 .iter()
1544 .any(|member| member.user_id.as_deref() == Some("user-bob"))
1545 );
1546 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1547}
1548
1503#[tokio::test]
1549#[tokio::test]
1504async fn failing_channel_listing_is_reported_not_fatal() {
1550async fn failing_channel_listing_is_reported_not_fatal() {
1505 let fake = Arc::new(Fake::default());
1551 let fake = Arc::new(Fake::default());
@@ -2564,12 +2610,17 @@ async fn chat_actions_call_graph_with_the_right_ids() {
2564 .await
2610 .await
2565 .unwrap();
2611 .unwrap();
2566 engine.soft_delete_message(CHAT, "m0003").await.unwrap();
2612 engine.soft_delete_message(CHAT, "m0003").await.unwrap();
2613 engine
2614 .undo_soft_delete_message(CHAT, "m0003")
2615 .await
2616 .unwrap();
2567 let calls = fake.calls();
2617 let calls = fake.calls();
2568 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2618 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2569 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2619 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2570 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2620 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2571 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2621 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2572 assert!(calls.contains(&format!("soft_delete {ME} m0003")));
2622 assert!(calls.contains(&format!("soft_delete {ME} m0003")));
2623 assert!(calls.contains(&format!("undo_soft_delete {ME} m0003")));
2573 assert!(!engine.sidebar().unwrap().chats[0].unread);
2624 assert!(!engine.sidebar().unwrap().chats[0].unread);
2574}
2625}
2575
2626
@@ -3072,6 +3123,7 @@ impl FolderSource for FakeFolders {
3072 &'a self,
3123 &'a self,
3073 conversation_id: &'a str,
3124 conversation_id: &'a str,
3074 target_folder_id: &'a str,
3125 target_folder_id: &'a str,
3126 _index: Option<usize>,
3075 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
3127 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
3076 Box::pin(async move {
3128 Box::pin(async move {
3077 self.calls
3129 self.calls
@@ -3226,7 +3278,7 @@ async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() {
3226 engine.refresh_folders().await.unwrap();
3278 engine.refresh_folders().await.unwrap();
3227 assert!(events.try_recv().is_err());
3279 assert!(events.try_recv().is_err());
3228
3280
3229 engine.move_to_folder("a", "work").await.unwrap();
3281 engine.move_to_folder("a", "work", None).await.unwrap();
3230 assert_eq!(
3282 assert_eq!(
3231 engine.chat_folders().unwrap()[1].conversation_ids,
3283 engine.chat_folders().unwrap()[1].conversation_ids,
3232 ids(&["c", "a"])
3284 ids(&["c", "a"])
@@ -3490,7 +3542,7 @@ async fn folders_without_a_source_are_unsupported() {
3490 Err(Error::Unsupported(_))
3542 Err(Error::Unsupported(_))
3491 ));
3543 ));
3492 assert!(matches!(
3544 assert!(matches!(
3493 engine.move_to_folder("a", "b").await,
3545 engine.move_to_folder("a", "b", None).await,
3494 Err(Error::Unsupported(_))
3546 Err(Error::Unsupported(_))
3495 ));
3547 ));
3496}
3548}
crates/graph/src/people.rs +31 −2
@@ -18,14 +18,43 @@ struct BinaryBody {
18 18 }
19 19
20 20 impl Graph {
21 /// `Ok(None)` for users without a photo (404).
21 /// `Ok(None)` for users without a photo. A 404 on the sized rendition
22 /// also comes back for photos stored smaller in Entra ID, so those ask for the original.
22 23 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
24 let mut photos = self.photo_batch(user_ids, urls::user_photo).await?;
25 let missing: Vec<usize> = photos
26 .iter()
27 .enumerate()
28 .filter(|(_, photo)| matches!(photo, Ok(None)))
29 .map(|(index, _)| index)
30 .collect();
31 if missing.is_empty() {
32 return Ok(photos);
33 }
34 let missing_ids: Vec<String> = missing
35 .iter()
36 .map(|index| user_ids[*index].clone())
37 .collect();
38 let originals = self
39 .photo_batch(&missing_ids, urls::user_photo_original)
40 .await?;
41 for (index, original) in missing.into_iter().zip(originals) {
42 photos[index] = original;
43 }
44 Ok(photos)
45 }
46
47 async fn photo_batch(
48 &self,
49 user_ids: &[String],
50 url: fn(&str) -> String,
51 ) -> Result<Vec<Result<Option<Photo>>>> {
23 52 let scope = Scope::graph(PHOTO_SCOPE);
24 53 let mut photos = Vec::with_capacity(user_ids.len());
25 54 for chunk in user_ids.chunks(BATCH_SIZE) {
26 55 let requests: Vec<Request> = chunk
27 56 .iter()
28 .map(|user_id| Request::binary_get(urls::user_photo(user_id)))
57 .map(|user_id| Request::binary_get(url(user_id)))
29 58 .collect();
30 59 let answers = self.session().batch(&requests, &scope).await?;
31 60 photos.extend(
@@ -18,14 +18,43 @@ struct BinaryBody {
18}
18}
19
19
20impl Graph {
20impl Graph {
21 /// `Ok(None)` for users without a photo (404).
21 /// `Ok(None)` for users without a photo. A 404 on the sized rendition
22 /// also comes back for photos stored smaller in Entra ID, so those ask for the original.
22 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
23 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
24 let mut photos = self.photo_batch(user_ids, urls::user_photo).await?;
25 let missing: Vec<usize> = photos
26 .iter()
27 .enumerate()
28 .filter(|(_, photo)| matches!(photo, Ok(None)))
29 .map(|(index, _)| index)
30 .collect();
31 if missing.is_empty() {
32 return Ok(photos);
33 }
34 let missing_ids: Vec<String> = missing
35 .iter()
36 .map(|index| user_ids[*index].clone())
37 .collect();
38 let originals = self
39 .photo_batch(&missing_ids, urls::user_photo_original)
40 .await?;
41 for (index, original) in missing.into_iter().zip(originals) {
42 photos[index] = original;
43 }
44 Ok(photos)
45 }
46
47 async fn photo_batch(
48 &self,
49 user_ids: &[String],
50 url: fn(&str) -> String,
51 ) -> Result<Vec<Result<Option<Photo>>>> {
23 let scope = Scope::graph(PHOTO_SCOPE);
52 let scope = Scope::graph(PHOTO_SCOPE);
24 let mut photos = Vec::with_capacity(user_ids.len());
53 let mut photos = Vec::with_capacity(user_ids.len());
25 for chunk in user_ids.chunks(BATCH_SIZE) {
54 for chunk in user_ids.chunks(BATCH_SIZE) {
26 let requests: Vec<Request> = chunk
55 let requests: Vec<Request> = chunk
27 .iter()
56 .iter()
28 .map(|user_id| Request::binary_get(urls::user_photo(user_id)))
57 .map(|user_id| Request::binary_get(url(user_id)))
29 .collect();
58 .collect();
30 let answers = self.session().batch(&requests, &scope).await?;
59 let answers = self.session().batch(&requests, &scope).await?;
31 photos.extend(
60 photos.extend(
crates/graph/src/target.rs +19 −0
@@ -76,6 +76,16 @@ impl MessageTarget {
76 76 }
77 77 }
78 78
79 pub(crate) fn undo_soft_delete_url(&self, user_id: &str) -> String {
80 match self {
81 MessageTarget::Chat {
82 chat_id,
83 message_id,
84 } => urls::undo_soft_delete(user_id, chat_id, message_id),
85 channel => format!("{}/undoSoftDelete", channel.url()),
86 }
87 }
88
79 89 pub(crate) fn reaction_url(&self, action: &str) -> String {
80 90 format!("{}/{action}", self.url())
81 91 }
@@ -125,6 +135,15 @@ mod tests {
125 135 chat.soft_delete_url("u1"),
126 136 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/softDelete"
127 137 );
138 assert_eq!(
139 chat.undo_soft_delete_url("u1"),
140 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/undoSoftDelete"
141 );
142 assert!(
143 MessageTarget::channel("t", "19:c@thread.tacv2", "r1", Some("m1"))
144 .undo_soft_delete_url("u")
145 .ends_with("/messages/m1/replies/r1/undoSoftDelete")
146 );
128 147 assert!(
129 148 chat.reaction_url("unsetReaction")
130 149 .ends_with("/messages/m1/unsetReaction")
@@ -76,6 +76,16 @@ impl MessageTarget {
76 }
76 }
77 }
77 }
78
78
79 pub(crate) fn undo_soft_delete_url(&self, user_id: &str) -> String {
80 match self {
81 MessageTarget::Chat {
82 chat_id,
83 message_id,
84 } => urls::undo_soft_delete(user_id, chat_id, message_id),
85 channel => format!("{}/undoSoftDelete", channel.url()),
86 }
87 }
88
79 pub(crate) fn reaction_url(&self, action: &str) -> String {
89 pub(crate) fn reaction_url(&self, action: &str) -> String {
80 format!("{}/{action}", self.url())
90 format!("{}/{action}", self.url())
81 }
91 }
@@ -125,6 +135,15 @@ mod tests {
125 chat.soft_delete_url("u1"),
135 chat.soft_delete_url("u1"),
126 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/softDelete"
136 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/softDelete"
127 );
137 );
138 assert_eq!(
139 chat.undo_soft_delete_url("u1"),
140 "https://graph.microsoft.com/v1.0/users/u1/chats/19%3Aa%40thread.v2/messages/m1/undoSoftDelete"
141 );
142 assert!(
143 MessageTarget::channel("t", "19:c@thread.tacv2", "r1", Some("m1"))
144 .undo_soft_delete_url("u")
145 .ends_with("/messages/m1/replies/r1/undoSoftDelete")
146 );
128 assert!(
147 assert!(
129 chat.reaction_url("unsetReaction")
148 chat.reaction_url("unsetReaction")
130 .ends_with("/messages/m1/unsetReaction")
149 .ends_with("/messages/m1/unsetReaction")
crates/graph/src/urls.rs +34 −6
@@ -16,13 +16,19 @@ pub fn me() -> String {
16 16 format!("{GRAPH}/v1.0/me?$select=id,displayName,mail,userPrincipalName")
17 17 }
18 18
19 const PHOTO_SIZE: &str = "240x240";
20
19 21 pub fn user_photo(user_id: &str) -> String {
20 22 format!(
21 "{GRAPH}/v1.0/users/{}/photos/48x48/$value",
23 "{GRAPH}/v1.0/users/{}/photos/{PHOTO_SIZE}/$value",
22 24 segment(user_id)
23 25 )
24 26 }
25 27
28 pub fn user_photo_original(user_id: &str) -> String {
29 format!("{GRAPH}/v1.0/users/{}/photo/$value", segment(user_id))
30 }
31
26 32 pub fn user_profile(user_id: &str) -> String {
27 33 format!(
28 34 "{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\
@@ -83,8 +89,21 @@ pub fn chat_message(chat_id: &str, message_id: &str) -> String {
83 89 }
84 90
85 91 pub fn soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
92 user_chat_message_action(user_id, chat_id, message_id, "softDelete")
93 }
94
95 pub fn undo_soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
96 user_chat_message_action(user_id, chat_id, message_id, "undoSoftDelete")
97 }
98
99 fn user_chat_message_action(
100 user_id: &str,
101 chat_id: &str,
102 message_id: &str,
103 action: &str,
104 ) -> String {
86 105 format!(
87 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/softDelete",
106 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/{action}",
88 107 segment(user_id),
89 108 segment(chat_id),
90 109 segment(message_id)
@@ -201,10 +220,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
201 220 }
202 221
203 222 pub fn shared_drive_item(share_id: &str) -> String {
204 format!(
205 "{GRAPH}/v1.0/shares/{}/driveItem",
206 segment(share_id)
207 )
223 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
208 224 }
209 225
210 226 pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
@@ -342,6 +358,18 @@ mod tests {
342 358
343 359 use super::*;
344 360
361 #[test]
362 fn photos_ask_for_the_240_rendition_then_the_original() {
363 assert_eq!(
364 user_photo("a b"),
365 format!("{GRAPH}/v1.0/users/a%20b/photos/240x240/$value")
366 );
367 assert_eq!(
368 user_photo_original("a b"),
369 format!("{GRAPH}/v1.0/users/a%20b/photo/$value")
370 );
371 }
372
345 373 #[test]
346 374 fn chat_ids_are_path_encoded() {
347 375 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
@@ -16,13 +16,19 @@ pub fn me() -> String {
16 format!("{GRAPH}/v1.0/me?$select=id,displayName,mail,userPrincipalName")
16 format!("{GRAPH}/v1.0/me?$select=id,displayName,mail,userPrincipalName")
17}
17}
18
18
19const PHOTO_SIZE: &str = "240x240";
20
19pub fn user_photo(user_id: &str) -> String {
21pub fn user_photo(user_id: &str) -> String {
20 format!(
22 format!(
21 "{GRAPH}/v1.0/users/{}/photos/48x48/$value",
23 "{GRAPH}/v1.0/users/{}/photos/{PHOTO_SIZE}/$value",
22 segment(user_id)
24 segment(user_id)
23 )
25 )
24}
26}
25
27
28pub fn user_photo_original(user_id: &str) -> String {
29 format!("{GRAPH}/v1.0/users/{}/photo/$value", segment(user_id))
30}
31
26pub fn user_profile(user_id: &str) -> String {
32pub fn user_profile(user_id: &str) -> String {
27 format!(
33 format!(
28 "{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\
34 "{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\
@@ -83,8 +89,21 @@ pub fn chat_message(chat_id: &str, message_id: &str) -> String {
83}
89}
84
90
85pub fn soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
91pub fn soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
92 user_chat_message_action(user_id, chat_id, message_id, "softDelete")
93}
94
95pub fn undo_soft_delete(user_id: &str, chat_id: &str, message_id: &str) -> String {
96 user_chat_message_action(user_id, chat_id, message_id, "undoSoftDelete")
97}
98
99fn user_chat_message_action(
100 user_id: &str,
101 chat_id: &str,
102 message_id: &str,
103 action: &str,
104) -> String {
86 format!(
105 format!(
87 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/softDelete",
106 "{GRAPH}/v1.0/users/{}/chats/{}/messages/{}/{action}",
88 segment(user_id),
107 segment(user_id),
89 segment(chat_id),
108 segment(chat_id),
90 segment(message_id)
109 segment(message_id)
@@ -201,10 +220,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
201}
220}
202
221
203pub fn shared_drive_item(share_id: &str) -> String {
222pub fn shared_drive_item(share_id: &str) -> String {
204 format!(
223 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
205 "{GRAPH}/v1.0/shares/{}/driveItem",
206 segment(share_id)
207 )
208}
224}
209
225
210pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
226pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
@@ -342,6 +358,18 @@ mod tests {
342
358
343 use super::*;
359 use super::*;
344
360
361 #[test]
362 fn photos_ask_for_the_240_rendition_then_the_original() {
363 assert_eq!(
364 user_photo("a b"),
365 format!("{GRAPH}/v1.0/users/a%20b/photos/240x240/$value")
366 );
367 assert_eq!(
368 user_photo_original("a b"),
369 format!("{GRAPH}/v1.0/users/a%20b/photo/$value")
370 );
371 }
372
345 #[test]
373 #[test]
346 fn chat_ids_are_path_encoded() {
374 fn chat_ids_are_path_encoded() {
347 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
375 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
crates/graph/src/writes.rs +15 −0
@@ -225,6 +225,21 @@ impl Graph {
225 225 .await
226 226 }
227 227
228 /// `user_id` is only used for chats.
229 pub async fn undo_soft_delete_message(
230 &self,
231 user_id: &str,
232 target: &MessageTarget,
233 ) -> Result<()> {
234 self.write(
235 Method::Post,
236 &target.undo_soft_delete_url(user_id),
237 target.write_scope(),
238 None,
239 )
240 .await
241 }
242
228 243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
229 244 let body = json!({
230 245 "chatType": "oneOnOne",
@@ -225,6 +225,21 @@ impl Graph {
225 .await
225 .await
226 }
226 }
227
227
228 /// `user_id` is only used for chats.
229 pub async fn undo_soft_delete_message(
230 &self,
231 user_id: &str,
232 target: &MessageTarget,
233 ) -> Result<()> {
234 self.write(
235 Method::Post,
236 &target.undo_soft_delete_url(user_id),
237 target.write_scope(),
238 None,
239 )
240 .await
241 }
242
228 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
229 let body = json!({
244 let body = json!({
230 "chatType": "oneOnOne",
245 "chatType": "oneOnOne",
vendor/gpui-component/src/message_scroller.rs +5 −0
@@ -67,6 +67,11 @@ impl MessageScrollerState {
67 67 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
68 68 }
69 69
70 /// Return the index of the row at the top of the viewport.
71 pub fn top_item(&self) -> usize {
72 self.list_state.logical_scroll_top().item_ix
73 }
74
70 75 /// Return whether the list is actively following its tail.
71 76 pub fn is_following_tail(&self) -> bool {
72 77 self.list_state.is_following_tail()
@@ -67,6 +67,11 @@ impl MessageScrollerState {
67 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
67 && !self.list_state.is_scrolled_to_end().unwrap_or(false)
68 }
68 }
69
69
70 /// Return the index of the row at the top of the viewport.
71 pub fn top_item(&self) -> usize {
72 self.list_state.logical_scroll_top().item_ix
73 }
74
70 /// Return whether the list is actively following its tail.
75 /// Return whether the list is actively following its tail.
71 pub fn is_following_tail(&self) -> bool {
76 pub fn is_following_tail(&self) -> bool {
72 self.list_state.is_following_tail()
77 self.list_state.is_following_tail()