Merge remote-tracking branch 'origin/main' into feat/chat-quick-wins
@@ -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",@@ -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 else24
| 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
@@ -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 = true15
chatsvc.workspace = true15
chatsvc.workspace = true16
chrono.workspace = true16
chrono.workspace = true17
directories.workspace = true17
directories.workspace = true18
futures-channel = "0.3"18
futures-util = { workspace = true, features = ["io"] }19
futures-util = { workspace = true, features = ["io"] }19
gpui-kit.workspace = true20
gpui-kit.workspace = true20
log = "0.4"21
log = "0.4"@@ -26,13 +27,12 @@ store.workspace = true26
teams-core.workspace = true27
teams-core.workspace = true27
tokio.workspace = true28
tokio.workspace = true28
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }29
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }30
raw-window-handle = "0.6"29
31
30
[target.'cfg(target_os = "linux")'.dependencies]32
[target.'cfg(target_os = "linux")'.dependencies]31
raw-window-handle = "0.6"32
x11rb = { version = "0.13", features = ["shape"] }33
x11rb = { version = "0.13", features = ["shape"] }33
34
34
[target.'cfg(windows)'.dependencies]35
[target.'cfg(windows)'.dependencies]35
raw-window-handle = "0.6"36
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }36
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }37
tray-icon = { version = "0.21", default-features = false }37
tray-icon = { version = "0.21", default-features = false }38
windows = { version = "0.62", features = [38
windows = { 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",@@ -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 @@1
use store::Store;1
use store::Store;2
2
3
use crate::theme::{self, ColorScheme};3
use crate::theme::{self, ColorScheme, Shade};4
4
5
const META_KEY: &str = "appearance.settings";5
const META_KEY: &str = "appearance.settings";6
const COLOR_SCHEME_KEY: &str = "color_scheme";6
const COLOR_SCHEME_KEY: &str = "color_scheme";7
const APP_ICON_KEY: &str = "app_icon";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
const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");14
const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");9
const MICROSOFT_TEAMS_ICON_PNG: &[u8] =15
const 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)]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::ALL82
.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
pub struct AppearanceSettings {114
pub 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
54
impl Default for AppearanceSettings {121
impl 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
132
pub fn nearest_zoom_step(zoom: f32) -> f32 {133
ZOOM_STEPS134
.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_STEPS141
.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_STEPS148
.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 u32156
}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 != 0177
}178
179
#[cfg(not(windows))]180
pub fn system_high_contrast() -> bool {181
false182
}183
63
pub fn load(store: &Store) -> AppearanceSettings {184
pub fn load(store: &Store) -> AppearanceSettings {64
store185
store65
.meta(META_KEY)186
.meta(META_KEY)@@ -75,9 +196,11 @@ pub fn save(store: &Store, settings: &AppearanceSettings) {75
196
76
fn serialize(settings: &AppearanceSettings) -> String {197
fn 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.zoom81
)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 {@@ -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 @@1
use std::io::Cursor;1
use std::io::Cursor;2
use std::sync::{Arc, Mutex};2
3
4
use gpui_kit::RenderImage;3
use image::imageops::FilterType;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;8
const MAX_TEXTURES: usize = 8;7
const MARGIN: f32 = 2.;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>> {12
pub 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();17
pub 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
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
bytes36
};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
let mut encoded = Vec::new();67
let mut encoded = Vec::new();19
resized68
source20
.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
25
fn apply_circle_mask(texture: &mut RgbaImage) {74
pub 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 u3229
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.);80
fn 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
37
pub fn visible_fraction() -> f32 {84
pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {38
(TEXTURE_SIZE as f32 - 2. * MARGIN) / TEXTURE_SIZE as f3285
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
square92
} 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)]42
mod tests {102
mod 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
}@@ -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;36
pub mod updater;36
pub mod updater;37
pub mod user_activity;37
pub mod user_activity;38
pub mod version;38
pub mod version;39
pub mod zoom;39
40
40
pub const APP_NAME: &str = "Rusty Teams";41
pub const APP_NAME: &str = "Rusty Teams";@@ -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
35
pub fn exclude_from_capture(_handle: NativeHandle) {}35
pub fn exclude_from_capture(_handle: NativeHandle) {}36
36
37
pub fn include_in_capture(_handle: NativeHandle) {}38
37
#[cfg(target_os = "linux")]39
#[cfg(target_os = "linux")]38
pub fn make_window_click_through(window: &Window) {40
pub fn make_window_click_through(window: &Window) {39
super::x11_input::make_input_transparent(window);41
super::x11_input::make_input_transparent(window);@@ -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
};40
use windows::core::{BOOL, PCWSTR, w};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
pub fn make_window_click_through(window: &Window) {281
pub 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);@@ -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::*;7
mod schemes;7
mod schemes;8
8
9
pub use schemes::{9
pub 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
14
const FONT_FAMILY: &str = "Google Sans Flex";15
const FONT_FAMILY: &str = "Google Sans Flex";@@ -22,13 +23,6 @@ const FONT_FILES: [&[u8]; 4] = [22
];23
];23
24
24
const WHITE: u32 = 0xffffff;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
const CLOSE_BUTTON_ICON: u32 = 0xffffff;26
const CLOSE_BUTTON_ICON: u32 = 0xffffff;33
27
34
pub fn color(hex: u32) -> Hsla {28
pub 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::Dark52
} else {53
ThemeMode::Light54
};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
115
fn elevation_tokens() -> ElevationTokens {114
fn 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
151
pub fn popup_nested() -> Hsla {150
pub fn popup_nested() -> Hsla {152
color(scheme().popup_nested)151
color(palette().popup_nested)153
}152
}154
153
155
pub trait ElevatedSurface: Styled + Sized {154
pub trait ElevatedSurface: Styled + Sized {@@ -177,99 +176,99 @@ pub fn font_family() -> SharedString {177
}176
}178
177
179
pub fn background() -> Hsla {178
pub fn background() -> Hsla {180
color(scheme().background)179
color(palette().background)181
}180
}182
181
183
pub fn background_hex() -> u32 {182
pub fn background_hex() -> u32 {184
scheme().background183
palette().background185
}184
}186
185
187
pub fn toast_mention_fill() -> Hsla {186
pub fn toast_mention_fill() -> Hsla {188
color(scheme().toast_mention)187
color(palette().toast_mention)189
}188
}190
189
191
pub fn surface() -> Hsla {190
pub fn surface() -> Hsla {192
color(scheme().surface)191
color(palette().surface)193
}192
}194
193
195
pub fn surface_raised() -> Hsla {194
pub fn surface_raised() -> Hsla {196
color(scheme().surface_raised)195
color(palette().surface_raised)197
}196
}198
197
199
pub fn row_hover() -> Hsla {198
pub fn row_hover() -> Hsla {200
color(scheme().row_hover)199
color(palette().row_hover)201
}200
}202
201
203
pub fn popup() -> Hsla {202
pub fn popup() -> Hsla {204
color(scheme().popup)203
color(palette().popup)205
}204
}206
205
207
pub fn popup_hover() -> Hsla {206
pub fn popup_hover() -> Hsla {208
color(scheme().popup_hover)207
color(palette().popup_hover)209
}208
}210
209
211
pub fn reply_surface() -> Hsla {210
pub fn reply_surface() -> Hsla {212
color(scheme().reply_surface)211
color(palette().reply_surface)213
}212
}214
213
215
pub fn border() -> Hsla {214
pub fn border() -> Hsla {216
color(scheme().border)215
color(palette().border)217
}216
}218
217
219
pub fn selection() -> Hsla {218
pub fn selection() -> Hsla {220
color_with_alpha(scheme().selection)219
color_with_alpha(palette().selection)221
}220
}222
221
223
pub fn border_strong() -> Hsla {222
pub fn border_strong() -> Hsla {224
color(scheme().border_strong)223
color(palette().border_strong)225
}224
}226
225
227
pub fn text() -> Hsla {226
pub fn text() -> Hsla {228
color(scheme().foreground)227
color(palette().foreground)229
}228
}230
229
231
pub fn text_strong() -> Hsla {230
pub fn text_strong() -> Hsla {232
color(scheme().text_strong)231
color(palette().text_strong)233
}232
}234
233
235
pub fn text_soft() -> Hsla {234
pub fn text_soft() -> Hsla {236
color(scheme().text_soft)235
color(palette().text_soft)237
}236
}238
237
239
pub fn text_muted() -> Hsla {238
pub fn text_muted() -> Hsla {240
color(scheme().text_muted)239
color(palette().text_muted)241
}240
}242
241
243
pub fn text_faint() -> Hsla {242
pub fn text_faint() -> Hsla {244
color(scheme().text_faint)243
color(palette().text_faint)245
}244
}246
245
247
pub fn accent() -> Hsla {246
pub fn accent() -> Hsla {248
color(scheme().accent)247
color(palette().accent)249
}248
}250
249
251
pub fn accent_text() -> Hsla {250
pub fn accent_text() -> Hsla {252
color(scheme().accent_text)251
color(palette().accent_text)253
}252
}254
253
255
pub fn accent_soft() -> Hsla {254
pub fn accent_soft() -> Hsla {256
color(scheme().accent_soft)255
color(palette().accent_soft)257
}256
}258
257
259
pub fn on_accent() -> Hsla {258
pub fn on_accent() -> Hsla {260
color(scheme().on_accent)259
color(palette().on_accent)261
}260
}262
261
263
pub fn bubble_own() -> Hsla {262
pub fn bubble_own() -> Hsla {264
color(scheme().bubble_own)263
color(palette().bubble_own)265
}264
}266
265
267
pub fn bubble_other() -> Hsla {266
pub fn bubble_other() -> Hsla {268
color(scheme().bubble_other)267
color(palette().bubble_other)269
}268
}270
269
271
pub fn reaction_on_own() -> Hsla {270
pub fn reaction_on_own() -> Hsla {272
color(scheme().reaction_on_own)271
color(palette().reaction_on_own)273
}272
}274
273
275
pub fn white() -> Hsla {274
pub fn white() -> Hsla {@@ -278,113 +277,114 @@ pub fn white() -> Hsla {278
277
279
pub fn mention_background(own: bool) -> Hsla {278
pub fn mention_background(own: bool) -> Hsla {280
color(if own {279
color(if own {281
scheme().mention_background_own280
palette().mention_background_own282
} else {281
} else {283
scheme().mention_background282
palette().mention_background284
})283
})285
}284
}286
285
287
pub fn own_meta() -> Hsla {286
pub fn own_meta() -> Hsla {288
color(scheme().own_meta)287
color(palette().own_meta)289
}288
}290
289
291
pub fn own_read() -> Hsla {290
pub fn own_read() -> Hsla {292
color(scheme().own_read)291
color(palette().own_read)293
}292
}294
293
295
pub fn mention_text() -> Hsla {294
pub fn mention_text() -> Hsla {296
color(scheme().accent_soft)295
color(palette().accent_soft)297
}296
}298
297
299
pub fn drop_background() -> Hsla {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
pub fn code_surface() -> Hsla {302
pub fn code_surface() -> Hsla {304
color_with_alpha(CODE_SURFACE)303
color_with_alpha(palette().code_surface)305
}304
}306
305
307
pub fn code_header_border() -> Hsla {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
pub fn inline_code_fill(own: bool) -> Hsla {310
pub fn inline_code_fill(own: bool) -> Hsla {312
color_with_alpha(if own {311
color_with_alpha(if own {313
INLINE_CODE_FILL_OWN312
palette().inline_code_fill_own314
} else {313
} else {315
INLINE_CODE_FILL314
palette().inline_code_fill316
})315
})317
}316
}318
317
319
pub fn quote_fill() -> Hsla {318
pub fn quote_fill() -> Hsla {320
color_with_alpha(QUOTE_FILL)319
color_with_alpha(palette().quote_fill)321
}320
}322
321
323
pub fn inline_code_border() -> Hsla {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
pub fn table_header() -> Hsla {326
pub fn table_header() -> Hsla {328
color_with_alpha(TABLE_HEADER)327
color_with_alpha(palette().table_header)329
}328
}330
329
331
pub fn rule(own: bool) -> Hsla {330
pub 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
339
pub fn badge_muted() -> Hsla {338
pub fn badge_muted() -> Hsla {340
color(scheme().badge_muted)339
color(palette().badge_muted)341
}340
}342
341
343
pub fn green() -> Hsla {342
pub fn green() -> Hsla {344
color(scheme().green)343
color(palette().green)345
}344
}346
345
347
pub fn red() -> Hsla {346
pub fn red() -> Hsla {348
color(scheme().red)347
color(palette().red)349
}348
}350
349
351
pub fn red_soft() -> Hsla {350
pub fn red_soft() -> Hsla {352
color(scheme().red_soft)351
color(palette().red_soft)353
}352
}354
353
355
pub fn red_tint() -> Hsla {354
pub fn red_tint() -> Hsla {356
color(scheme().red_tint)355
color(palette().red_tint)357
}356
}358
357
359
pub fn amber() -> Hsla {358
pub fn amber() -> Hsla {360
color(scheme().amber)359
color(palette().amber)361
}360
}362
361
363
pub fn out_of_office() -> Hsla {362
pub fn out_of_office() -> Hsla {364
color(scheme().out_of_office)363
color(palette().out_of_office)365
}364
}366
365
367
pub fn meeting_avatar() -> Hsla {366
pub fn meeting_avatar() -> Hsla {368
color(scheme().meeting_avatar)367
color(palette().meeting_avatar)369
}368
}370
369
371
pub fn bot_avatar() -> Hsla {370
pub fn bot_avatar() -> Hsla {372
color(scheme().bot_avatar)371
color(palette().bot_avatar)373
}372
}374
373
375
pub fn avatar_color(index: usize) -> Hsla {374
pub 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
380
pub fn avatar_palette_len() -> usize {379
pub 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)]385
mod tests {384
mod 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]@@ -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 @@1
use std::cell::Cell;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
#[derive(Debug, PartialEq, Eq)]36
#[derive(Debug, PartialEq, Eq)]5
pub struct ColorScheme {37
pub 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
54
pub const RUSTY_TEAMS: ColorScheme = ColorScheme {92
#[derive(Debug, PartialEq, Eq)]55
id: "rusty-teams",93
pub 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,100
impl 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,110
const AVATAR_PALETTE: [u32; 6] = [0x9a4a22, 0x44606e, 0x8a3434, 0x4f6a3c, 0x6a4f7a, 0x2f6b63];73
accent: 0xce6a3b,111
74
accent_text: 0xe08a5c,112
const 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
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_BASE177
};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_BASE224
},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_BASE267
},101
};268
};102
269
103
pub const TEAMS: ColorScheme = ColorScheme {270
pub 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_BASE315
},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_BASE358
},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
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_BASE150
};411
};151
412
152
pub const SCHEMES: [&ColorScheme; 2] = [&RUSTY_TEAMS, &TEAMS];413
pub const SCHEMES: [&ColorScheme; 2] = [&RUSTY_TEAMS, &TEAMS];153
414
154
static ACTIVE_SCHEME: AtomicUsize = AtomicUsize::new(0);415
static ACTIVE_SCHEME: AtomicUsize = AtomicUsize::new(0);416
static ACTIVE_SHADE: AtomicU8 = AtomicU8::new(0);155
417
156
thread_local! {418
thread_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
160
pub fn default_scheme() -> &'static ColorScheme {423
pub 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
445
pub fn active_shade() -> Shade {446
THREAD_SHADE447
.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
pub fn set_active_scheme(id: &str) {455
pub 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
459
pub fn set_active_shade(shade: Shade) {460
ACTIVE_SHADE.store(shade.index(), Ordering::Relaxed);461
}462
186
pub fn set_thread_scheme(id: Option<&str>) {463
pub 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
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::ALL474
.into_iter()475
.map(move |shade| (scheme, scheme.palette(shade)))476
})477
}478
190
#[cfg(test)]479
#[cfg(test)]191
mod tests {480
mod 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.92489
} 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.id554
scheme.id234
);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.id561
);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.id576
scheme.id240
);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.shade610
);611
}612
}613
assert!(614
contrast(palette.on_accent, palette.accent) >= 4.5,615
"{} {:?}: on_accent",616
scheme.id,617
palette.shade618
);619
assert!(620
contrast(palette.own_meta, palette.bubble_own) >= 3.,621
"{} {:?}: own_meta",622
scheme.id,623
palette.shade624
);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
}@@ -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 @@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
shared28
.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>> = shared43
.windows44
.borrow_mut()45
.drain(..)46
.filter_map(|window| window.upgrade())47
.collect();48
shared49
.windows50
.borrow_mut()51
.extend(windows.iter().map(Rc::downgrade));52
shared53
.executor54
.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_resizable74
}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_ZOOM90
}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.inner747
.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.inner773
.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
region800
.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.inner833
.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
}@@ -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
187
pub const DEMO_GALLERY_GUESTS: usize = 12;193
pub const DEMO_GALLERY_GUESTS: usize = 12;188
const DEMO_SHARING_GUESTS: usize = 9;194
const DEMO_SHARING_GUESTS: usize = 9;195
const DEMO_SHARED_WINDOW: &str = "Standup board";189
const BREAKOUT_AT_TICKS: u32 = 20;196
const BREAKOUT_AT_TICKS: u32 = 20;190
const WHITEBOARD_AT_TICKS: u32 = 5;197
const WHITEBOARD_AT_TICKS: u32 = 5;191
const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";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
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::Call467
DemoScene::Call458
| DemoScene::Mini468
| DemoScene::Mini459
| DemoScene::MiniOff469
| DemoScene::MiniOff@@ -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>>,
@@ -238,6 +239,7 @@ impl AppState {
238
239
selection: None,
239
240
late_arrivals: LateArrivals::default(),
240
241
new_chat: false,
242
new_chat_people: Vec::new(),
241
243
connection: if mode.demo {
242
244
ConnectionState::Online
243
245
} else {
@@ -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>>,@@ -238,6 +239,7 @@ impl AppState {238
selection: None,239
selection: None,239
late_arrivals: LateArrivals::default(),240
late_arrivals: LateArrivals::default(),240
new_chat: false,241
new_chat: false,242
new_chat_people: Vec::new(),241
connection: if mode.demo {243
connection: if mode.demo {242
ConnectionState::Online244
ConnectionState::Online243
} else {245
} else {@@ -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;14
pub mod record_load;14
pub mod record_load;15
pub mod reminder;15
pub mod reminder;16
pub mod share_actions;16
pub mod share_actions;17
pub mod share_overlay;17
pub mod schedule;18
pub mod schedule;18
pub mod target;19
pub mod target;19
pub mod view_actions;20
pub mod view_actions;@@ -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
120
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {121
call_active && main_minimized122
}123
124
pub fn parse_position(text: &str) -> Option<(i32, i32)> {120
pub 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!(@@ -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
3
use chrono::{DateTime, FixedOffset, NaiveDate, Utc};3
use chrono::{DateTime, FixedOffset, NaiveDate, Utc};4
use store::MessageRecord;4
use store::MessageRecord;5
use teams_core::roster_event::RosterEvent;5
use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};6
use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};6
7
7
use crate::format;8
use crate::format;@@ -12,6 +13,8 @@ const RECAP_DATE_FORMAT: &str = "%A, %-d %B %Y %H:%M";12
const RECAP_TIME_FORMAT: &str = "%H:%M";13
const RECAP_TIME_FORMAT: &str = "%H:%M";13
const AUTO_STOP_SECONDS: i64 = 5;14
const AUTO_STOP_SECONDS: i64 = 5;14
const WEEKDAY_STAMP_DAYS: i64 = 6;15
const WEEKDAY_STAMP_DAYS: i64 = 6;16
const OWN_NAME: &str = "You";17
const UNKNOWN_USER: &str = "Unknown User";15
18
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]19
#[derive(Debug, Clone, Copy, PartialEq, Eq)]17
pub enum CallIcon {20
pub 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.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
pub struct CallClock<'a> {136
pub struct CallClock<'a> {@@ -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
3
use chrono::{DateTime, Duration, Local, Offset, Utc};3
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use gpui_kit::*;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
use crate::app_state::{AppState, Selection, chat_title};9
use crate::app_state::{AppState, Selection, chat_title};8
use crate::notice::{NoticeAction, short_error, truncated};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 _ = self259
.store260
.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
engine271
.add_chat_members(&owned_chat_id, &people, share)272
.await273
},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: people293
.iter()294
.filter_map(|person| person.user_id.clone())295
.collect(),296
member_names: people297
.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.sidebar325
self.sidebar243
.chats326
.chats@@ -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
@@ -557,21 +558,24 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
557
558
store.pinned_channel_ids().unwrap_or_default()
558
559
}
559
560
560
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> {
561
562
let record = store.avatar(user_id).ok().flatten()?;
562
Some(record.bytes.map(|bytes| {
563
if is_bot_id(user_id) {
564
Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
565
} else {
566
avatar_image_from(&record.content_type, bytes)
567
}
568
}))
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
})
569
567
}
570
568
571
pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
572
match crate::avatar_image::circular_png(&bytes) {
573
Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
574
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,
575
579
}
576
580
}
577
581
@@ -871,7 +875,7 @@ mod tests {
871
875
#[test]
872
876
fn missing_avatars_skip_known_and_duplicates() {
873
877
let mut directory = Directory::default();
874
directory.set_avatar("known", None);
878
directory.set_avatar("known", AvatarState::Missing);
875
879
let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
876
880
assert_eq!(wanted, vec!["x", "y"]);
877
881
directory.mark_avatars_pending(&wanted);
@@ -9,6 +9,7 @@ use store::{ChatRecord, Store, is_bot_id};9
use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};9
use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};10
use tokio::sync::oneshot;10
use tokio::sync::oneshot;11
11
12
use crate::avatar_image::AvatarPhoto;12
use crate::backend::Engine;13
use crate::backend::Engine;13
use crate::runtime;14
use crate::runtime;14
15
@@ -113,7 +114,8 @@ impl Presence {113
pub enum AvatarState {114
pub 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
@@ -557,21 +558,24 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {557
store.pinned_channel_ids().unwrap_or_default()558
store.pinned_channel_ids().unwrap_or_default()558
}559
}559
560
560
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> {561
let record = store.avatar(user_id).ok().flatten()?;562
let record = store.avatar(user_id).ok().flatten()?;562
Some(record.bytes.map(|bytes| {563
Some(match record.bytes {563
if is_bot_id(user_id) {564
Some(bytes) => avatar_state_from(&record.content_type, bytes, is_bot_id(user_id)),564
Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))565
None => AvatarState::Missing,565
} else {566
})566
avatar_image_from(&record.content_type, bytes)567
}568
}))569
}567
}570
568
571
pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {569
pub fn avatar_state_from(content_type: &str, bytes: Vec<u8>, is_bot: bool) -> AvatarState {572
match crate::avatar_image::circular_png(&bytes) {570
if image_format(content_type) == ImageFormat::Svg {573
Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),571
if is_bot {574
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,575
}579
}576
}580
}577
581
@@ -871,7 +875,7 @@ mod tests {871
#[test]875
#[test]872
fn missing_avatars_skip_known_and_duplicates() {876
fn missing_avatars_skip_known_and_duplicates() {873
let mut directory = Directory::default();877
let mut directory = Directory::default();874
directory.set_avatar("known", None);878
directory.set_avatar("known", AvatarState::Missing);875
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));876
assert_eq!(wanted, vec!["x", "y"]);880
assert_eq!(wanted, vec!["x", "y"]);877
directory.mark_avatars_pending(&wanted);881
directory.mark_avatars_pending(&wanted);@@ -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, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
10
10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
@@ -19,7 +19,7 @@ use teams_core::{
19
19
use crate::activity::{Actor, Entry, Kind};
20
20
use crate::app_state::{AppState, Selection};
21
21
use crate::card_actions::{CardAnswer, CardTask};
22
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
22
use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
23
23
use crate::demo_gifs;
24
24
use crate::message_actions::ForwardSource;
25
25
@@ -30,6 +30,7 @@ const DEMO_USER_NAME: &str = "Dana Demo";
30
30
const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
31
31
const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
32
32
const PHOTO_SIZE: usize = 48;
33
const DEMO_PHOTO_SIDE: usize = 240;
33
34
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
34
35
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
35
36
const STAGING_SIZE: (usize, usize) = (960, 540);
@@ -866,8 +867,8 @@ fn seed_agent_access(store: &Store) {
866
867
});
867
868
}
868
869
869
fn photo(palette: &Palette) -> Arc<Image> {
870
crate::data::avatar_image_from("image/png", encode_png(palette))
870
fn photo(palette: &Palette) -> AvatarState {
871
crate::data::avatar_state_from("image/png", encode_png(palette), false)
871
872
}
872
873
873
874
pub fn seed_directory(state: &mut AppState) {
@@ -932,9 +933,9 @@ pub fn seed_directory(state: &mut AppState) {
932
933
directory
933
934
.unread_counts
934
935
.insert("demo-chat-allhands".to_owned(), 120);
935
directory.set_avatar(MARA_ID, Some(photo(&MARA)));
936
directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
937
directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
936
directory.set_avatar(MARA_ID, photo(&MARA));
937
directory.set_avatar(PRIYA_ID, photo(&PRIYA));
938
directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
938
939
for (user_id, kind) in [
939
940
(MARA_ID, PresenceKind::Available),
940
941
(JONAS_ID, PresenceKind::Busy),
@@ -1059,6 +1060,25 @@ fn message(
1059
1060
}
1060
1061
}
1061
1062
1063
pub fn roster_record(
1064
conversation: &str,
1065
id: &str,
1066
time: DateTime<Utc>,
1067
event: &teams_core::roster_event::RosterEvent,
1068
) -> MessageRecord {
1069
MessageRecord {
1070
conversation_id: conversation.to_owned(),
1071
message_id: id.to_owned(),
1072
created_at: time,
1073
links_json: "[]".to_owned(),
1074
attachments_json: "[]".to_owned(),
1075
reactions_json: "[]".to_owned(),
1076
mentions_json: "[]".to_owned(),
1077
call_event_json: Some(event.to_json()),
1078
..MessageRecord::default()
1079
}
1080
}
1081
1062
1082
fn call_record(
1063
1083
conversation: &str,
1064
1084
id: &str,
@@ -2154,8 +2174,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2154
2174
}
2155
2175
2156
2176
fn encode_png(palette: &Palette) -> Vec<u8> {
2157
encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
2158
let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
2177
let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2178
encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {
2179
let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);
2159
2180
if inside(x, y, (24., 21.), (8.5, 9.5)) {
2160
2181
palette.skin
2161
2182
} else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
@@ -1,10 +1,10 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
use std::path::PathBuf;2
use std::path::PathBuf;3
use std::sync::{Arc, OnceLock};3
use std::sync::OnceLock;4
use std::time::Instant;4
use std::time::Instant;5
5
6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};7
use gpui_kit::{App, Entity, Image};7
use gpui_kit::{App, Entity};8
use store::{8
use store::{9
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,@@ -19,7 +19,7 @@ use teams_core::{19
use crate::activity::{Actor, Entry, Kind};19
use crate::activity::{Actor, Entry, Kind};20
use crate::app_state::{AppState, Selection};20
use crate::app_state::{AppState, Selection};21
use crate::card_actions::{CardAnswer, CardTask};21
use crate::card_actions::{CardAnswer, CardTask};22
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};22
use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};23
use crate::demo_gifs;23
use crate::demo_gifs;24
use crate::message_actions::ForwardSource;24
use crate::message_actions::ForwardSource;25
25
@@ -30,6 +30,7 @@ const DEMO_USER_NAME: &str = "Dana Demo";30
const DEMO_USER_EMAIL: &str = "dana.demo@example.com";30
const DEMO_USER_EMAIL: &str = "dana.demo@example.com";31
const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";31
const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";32
const PHOTO_SIZE: usize = 48;32
const PHOTO_SIZE: usize = 48;33
const DEMO_PHOTO_SIDE: usize = 240;33
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";34
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";34
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";35
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";35
const STAGING_SIZE: (usize, usize) = (960, 540);36
const STAGING_SIZE: (usize, usize) = (960, 540);@@ -866,8 +867,8 @@ fn seed_agent_access(store: &Store) {866
});867
});867
}868
}868
869
869
fn photo(palette: &Palette) -> Arc<Image> {870
fn photo(palette: &Palette) -> AvatarState {870
crate::data::avatar_image_from("image/png", encode_png(palette))871
crate::data::avatar_state_from("image/png", encode_png(palette), false)871
}872
}872
873
873
pub fn seed_directory(state: &mut AppState) {874
pub fn seed_directory(state: &mut AppState) {@@ -932,9 +933,9 @@ pub fn seed_directory(state: &mut AppState) {932
directory933
directory933
.unread_counts934
.unread_counts934
.insert("demo-chat-allhands".to_owned(), 120);935
.insert("demo-chat-allhands".to_owned(), 120);935
directory.set_avatar(MARA_ID, Some(photo(&MARA)));936
directory.set_avatar(MARA_ID, photo(&MARA));936
directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));937
directory.set_avatar(PRIYA_ID, photo(&PRIYA));937
directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));938
directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));938
for (user_id, kind) in [939
for (user_id, kind) in [939
(MARA_ID, PresenceKind::Available),940
(MARA_ID, PresenceKind::Available),940
(JONAS_ID, PresenceKind::Busy),941
(JONAS_ID, PresenceKind::Busy),@@ -1059,6 +1060,25 @@ fn message(1059
}1060
}1060
}1061
}1061
1062
1063
pub fn roster_record(1064
conversation: &str,1065
id: &str,1066
time: DateTime<Utc>,1067
event: &teams_core::roster_event::RosterEvent,1068
) -> MessageRecord {1069
MessageRecord {1070
conversation_id: conversation.to_owned(),1071
message_id: id.to_owned(),1072
created_at: time,1073
links_json: "[]".to_owned(),1074
attachments_json: "[]".to_owned(),1075
reactions_json: "[]".to_owned(),1076
mentions_json: "[]".to_owned(),1077
call_event_json: Some(event.to_json()),1078
..MessageRecord::default()1079
}1080
}1081
1062
fn call_record(1082
fn call_record(1063
conversation: &str,1083
conversation: &str,1064
id: &str,1084
id: &str,@@ -2154,8 +2174,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {2154
}2174
}2155
2175
2156
fn encode_png(palette: &Palette) -> Vec<u8> {2176
fn encode_png(palette: &Palette) -> Vec<u8> {2157
encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {2177
let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;2158
let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);2178
encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {2179
let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);2159
if inside(x, y, (24., 21.), (8.5, 9.5)) {2180
if inside(x, y, (24., 21.), (8.5, 9.5)) {2160
palette.skin2181
palette.skin2161
} else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {2182
} else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {@@ -49,5 +49,5 @@ pub use app_base::{
49
49
APP_NAME, appearance, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
50
50
demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
51
51
emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
52
single_instance, stickers, theme, translation, updater, user_activity,
52
single_instance, stickers, theme, translation, updater, user_activity, zoom,
53
53
};
@@ -49,5 +49,5 @@ pub use app_base::{49
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,50
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,51
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,52
single_instance, stickers, theme, translation, updater, user_activity,52
single_instance, stickers, theme, translation, updater, user_activity, zoom,53
};53
};@@ -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;5
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};5
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};6
use gpui_kit::Image;6
use gpui_kit::Image;7
use store::MessageRecord;7
use store::MessageRecord;8
use teams_core::roster_event::{RosterEvent, roster_event};8
use teams_core::{9
use 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
};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
use crate::card_state::CardOverride;23
use crate::card_state::CardOverride;23
use crate::format;24
use crate::format;24
use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};25
use 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
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 = event651
.initiator_name652
.clone()653
.or_else(|| {654
event655
.initiator_id656
.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
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
record696
record615
.created_at697
.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;@@ -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};7
use super::hooks::jump_to_quoted;7
use super::hooks::jump_to_quoted;8
use super::selectable::{Pill, SelectableRichText};8
use super::selectable::{Pill, SelectableRichText};9
use super::syntax::{self, Token};9
use super::syntax::{self, Token};10
use app_base::theme;11
use crate::widgets::symbol;10
use crate::widgets::symbol;11
use app_base::theme;12
12
13
const LIST_GAP: f32 = 2.;13
const LIST_GAP: f32 = 2.;14
const MARKER_WIDTH: f32 = 18.;14
const 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
}@@ -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 @@1
use gpui_kit::*;1
use gpui_kit::*;2
use store::Store;2
use store::Store;3
3
4
use crate::appearance::{self, AppIcon, AppearanceSettings};4
use crate::appearance::{self, AppIcon, AppearanceSettings, SystemTheme, ThemeChoice};5
use crate::theme::{self, ColorScheme};5
use crate::theme::{self, ColorScheme};6
use crate::zoom;6
7
7
#[derive(Default)]8
#[derive(Default)]8
pub struct ActiveAppearance {9
pub struct ActiveAppearance {9
settings: AppearanceSettings,10
settings: AppearanceSettings,11
system: SystemTheme,10
}12
}11
13
12
impl Global for ActiveAppearance {}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::VibrantDark21
),22
high_contrast: appearance::system_high_contrast(),23
}24
}25
14
pub fn install(store: &Store, cx: &mut App) {26
pub 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
20
pub fn current(cx: &App) -> AppearanceSettings {35
pub 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
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
pub fn set_color_scheme(scheme: &'static ColorScheme, store: &Store, cx: &mut App) {65
pub 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();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
pub fn set_app_icon(icon: AppIcon, store: &Store, cx: &mut App) {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
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
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
cx.refresh_windows();110
cx.refresh_windows();111
true46
}112
}47
113
48
#[cfg(test)]114
#[cfg(test)]49
mod tests {115
mod 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
}@@ -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::*;7
use super::model::format_elapsed;7
use super::model::format_elapsed;8
use super::overlay_layout::{8
use 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
};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
use crate::app_state::AppState;17
use crate::app_state::AppState;13
use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};18
use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};14
use crate::views::call_mini_window::MiniWindowView;19
use crate::views::call_mini_window::MiniWindowView;15
use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};20
use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};21
use crate::views::call_share_gallery::ShareGalleryView;16
use crate::views::share_bar::{ShareBarView, ShareBorderView};22
use crate::views::share_bar::{ShareBarView, ShareBorderView};17
23
18
const TICK: Duration = Duration::from_millis(100);24
const TICK: Duration = Duration::from_millis(100);@@ -24,6 +30,7 @@ const BORDER_SIDES: usize = 4;24
enum Role {30
enum 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
81
pub struct CallWindows {89
pub 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
139
impl CallWindows {153
impl 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 = app155
let saved_position = |key: &str, cx: &App| {142
.read(cx)156
app.read(cx)143
.store157
.store144
.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_collapsed213
self.bar_collapsed191
}214
}192
215
216
pub fn gallery_layout(&self) -> GalleryLayout {217
self.gallery_layout218
}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_excluded236
}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
TICK290
TICK252
}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) = geometry356
let Some(work) = geometry309
.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 = self400
.share401
.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_window420
.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) = self543
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 = self437
.windows556
.windows438
.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 _ = self595
let _ = self452
.app596
.app453
.read(cx)597
.read(cx)454
.store598
.store455
.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 => cx654
.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()))@@ -192,6 +192,7 @@ mod frames {
192
192
OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
193
193
};
194
194
use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
195
use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
195
196
196
197
const GUARDED: &[&str] = &[
197
198
"shell",
@@ -199,6 +200,7 @@ mod frames {
199
200
"shell/title-bar/search",
200
201
"shell/title-bar/own-status",
201
202
"shell/title-bar/own-status/avatar",
203
OWN_AVATAR_DISC,
202
204
"shell/islands",
203
205
"shell/islands/rail",
204
206
"shell/islands/sidebar",
@@ -315,6 +317,7 @@ mod frames {
315
317
const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
316
318
const TOLERANCE: f32 = 0.5;
317
319
const KNOWN_VIOLATIONS: &[&str] = &[];
320
const ZOOM_STEP: f32 = 1.25;
318
321
319
322
type Tag = (&'static str, Bounds<Pixels>);
320
323
@@ -730,11 +733,31 @@ mod frames {
730
733
731
734
#[gpui_kit::test]
732
735
fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
736
check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);
737
}
738
739
#[gpui_kit::test]
740
fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {
741
let (width, height) = SIZES[1];
742
let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];
743
check_layout(cx, &zoomed, ZOOM_STEP, &[]);
744
}
745
746
fn check_layout(
747
cx: &mut TestAppContext,
748
sizes: &[(f32, f32)],
749
zoom: f32,
750
known_violations: &[&str],
751
) {
733
752
let (handle, app) = mount(cx);
753
let platform_scale = cx
754
.update_window(handle, |_, window, _| window.scale_factor())
755
.expect("test window");
756
cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);
734
757
let mut visual = VisualTestContext::from_window(handle, cx);
735
758
let mut seen_known = HashSet::new();
736
759
let mut unexpected = Vec::new();
737
for (width, height) in SIZES {
760
for &(width, height) in sizes {
738
761
visual.simulate_resize(size(px(width), px(height)));
739
762
let window = Bounds {
740
763
origin: point(px(0.), px(0.)),
@@ -919,7 +942,7 @@ mod frames {
919
942
}
920
943
for (key, message) in found {
921
944
let full_key = format!("{screen_name}@{width}x{height}:{key}");
922
if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
945
if known_violations.contains(&full_key.as_str()) {
923
946
seen_known.insert(full_key);
924
947
} else {
925
948
unexpected.push(format!("{full_key}: {message}"));
@@ -927,7 +950,7 @@ mod frames {
927
950
}
928
951
}
929
952
}
930
let stale: Vec<String> = KNOWN_VIOLATIONS
953
let stale: Vec<String> = known_violations
931
954
.iter()
932
955
.filter(|key| !seen_known.contains(**key))
933
956
.map(|key| format!("stale known violation, remove it: {key}"))
@@ -942,6 +965,40 @@ mod frames {
942
965
.join("\n")
943
966
);
944
967
}
968
#[gpui_kit::test]
969
fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
970
let (handle, _) = mount(cx);
971
let mut visual = VisualTestContext::from_window(handle, cx);
972
visual.simulate_resize(size(px(1280.), px(800.)));
973
collect(&mut visual, Some(OWN_AVATAR_DISC));
974
let disc = visual
975
.debug_bounds(OWN_AVATAR_DISC)
976
.expect("own avatar rendered");
977
let bar = visual
978
.debug_bounds("shell/title-bar")
979
.expect("title bar rendered");
980
assert_eq!(
981
f32::from(disc.size.width),
982
TITLE_AVATAR_SIZE,
983
"{}",
984
describe(disc)
985
);
986
assert_eq!(
987
f32::from(disc.size.height),
988
TITLE_AVATAR_SIZE,
989
"{}",
990
describe(disc)
991
);
992
let top = f32::from(disc.top() - bar.top());
993
let bottom = f32::from(bar.bottom() - disc.bottom());
994
assert!(
995
(top - bottom).abs() <= 1.,
996
"own avatar {} is not centered in the title bar {}",
997
describe(disc),
998
describe(bar)
999
);
1000
}
1001
945
1002
const TITLE_SEARCH: &str = "shell/title-bar/search";
946
1003
const TITLE_NEIGHBOURS: &[&str] = &[
947
1004
"shell/title-bar/leading",
@@ -1195,6 +1252,13 @@ mod frames {
1195
1252
crate::theme::set_thread_scheme(None);
1196
1253
}
1197
1254
1255
#[gpui_kit::test]
1256
fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {
1257
crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));
1258
check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1259
crate::theme::set_thread_shade(None);
1260
}
1261
1198
1262
fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1199
1263
let (handle, state) = mount_with(cx, true);
1200
1264
let mut visual = VisualTestContext::from_window(handle, cx);
@@ -192,6 +192,7 @@ mod frames {192
OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,192
OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,193
};193
};194
use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;194
use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;195
use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};195
196
196
const GUARDED: &[&str] = &[197
const GUARDED: &[&str] = &[197
"shell",198
"shell",@@ -199,6 +200,7 @@ mod frames {199
"shell/title-bar/search",200
"shell/title-bar/search",200
"shell/title-bar/own-status",201
"shell/title-bar/own-status",201
"shell/title-bar/own-status/avatar",202
"shell/title-bar/own-status/avatar",203
OWN_AVATAR_DISC,202
"shell/islands",204
"shell/islands",203
"shell/islands/rail",205
"shell/islands/rail",204
"shell/islands/sidebar",206
"shell/islands/sidebar",@@ -315,6 +317,7 @@ mod frames {315
const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];317
const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];316
const TOLERANCE: f32 = 0.5;318
const TOLERANCE: f32 = 0.5;317
const KNOWN_VIOLATIONS: &[&str] = &[];319
const KNOWN_VIOLATIONS: &[&str] = &[];320
const ZOOM_STEP: f32 = 1.25;318
321
319
type Tag = (&'static str, Bounds<Pixels>);322
type Tag = (&'static str, Bounds<Pixels>);320
323
@@ -730,11 +733,31 @@ mod frames {730
733
731
#[gpui_kit::test]734
#[gpui_kit::test]732
fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {735
fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {736
check_layout(cx, &SIZES, 1., KNOWN_VIOLATIONS);737
}738
739
#[gpui_kit::test]740
fn layout_holds_at_a_zoomed_step(cx: &mut TestAppContext) {741
let (width, height) = SIZES[1];742
let zoomed = [(width / ZOOM_STEP, height / ZOOM_STEP)];743
check_layout(cx, &zoomed, ZOOM_STEP, &[]);744
}745
746
fn check_layout(747
cx: &mut TestAppContext,748
sizes: &[(f32, f32)],749
zoom: f32,750
known_violations: &[&str],751
) {733
let (handle, app) = mount(cx);752
let (handle, app) = mount(cx);753
let platform_scale = cx754
.update_window(handle, |_, window, _| window.scale_factor())755
.expect("test window");756
cx.simulate_window_scale_factor_change(handle, platform_scale * zoom);734
let mut visual = VisualTestContext::from_window(handle, cx);757
let mut visual = VisualTestContext::from_window(handle, cx);735
let mut seen_known = HashSet::new();758
let mut seen_known = HashSet::new();736
let mut unexpected = Vec::new();759
let mut unexpected = Vec::new();737
for (width, height) in SIZES {760
for &(width, height) in sizes {738
visual.simulate_resize(size(px(width), px(height)));761
visual.simulate_resize(size(px(width), px(height)));739
let window = Bounds {762
let window = Bounds {740
origin: point(px(0.), px(0.)),763
origin: point(px(0.), px(0.)),@@ -919,7 +942,7 @@ mod frames {919
}942
}920
for (key, message) in found {943
for (key, message) in found {921
let full_key = format!("{screen_name}@{width}x{height}:{key}");944
let full_key = format!("{screen_name}@{width}x{height}:{key}");922
if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {945
if known_violations.contains(&full_key.as_str()) {923
seen_known.insert(full_key);946
seen_known.insert(full_key);924
} else {947
} else {925
unexpected.push(format!("{full_key}: {message}"));948
unexpected.push(format!("{full_key}: {message}"));@@ -927,7 +950,7 @@ mod frames {927
}950
}928
}951
}929
}952
}930
let stale: Vec<String> = KNOWN_VIOLATIONS953
let stale: Vec<String> = known_violations931
.iter()954
.iter()932
.filter(|key| !seen_known.contains(**key))955
.filter(|key| !seen_known.contains(**key))933
.map(|key| format!("stale known violation, remove it: {key}"))956
.map(|key| format!("stale known violation, remove it: {key}"))@@ -942,6 +965,40 @@ mod frames {942
.join("\n")965
.join("\n")943
);966
);944
}967
}968
#[gpui_kit::test]969
fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {970
let (handle, _) = mount(cx);971
let mut visual = VisualTestContext::from_window(handle, cx);972
visual.simulate_resize(size(px(1280.), px(800.)));973
collect(&mut visual, Some(OWN_AVATAR_DISC));974
let disc = visual975
.debug_bounds(OWN_AVATAR_DISC)976
.expect("own avatar rendered");977
let bar = visual978
.debug_bounds("shell/title-bar")979
.expect("title bar rendered");980
assert_eq!(981
f32::from(disc.size.width),982
TITLE_AVATAR_SIZE,983
"{}",984
describe(disc)985
);986
assert_eq!(987
f32::from(disc.size.height),988
TITLE_AVATAR_SIZE,989
"{}",990
describe(disc)991
);992
let top = f32::from(disc.top() - bar.top());993
let bottom = f32::from(bar.bottom() - disc.bottom());994
assert!(995
(top - bottom).abs() <= 1.,996
"own avatar {} is not centered in the title bar {}",997
describe(disc),998
describe(bar)999
);1000
}1001
945
const TITLE_SEARCH: &str = "shell/title-bar/search";1002
const TITLE_SEARCH: &str = "shell/title-bar/search";946
const TITLE_NEIGHBOURS: &[&str] = &[1003
const TITLE_NEIGHBOURS: &[&str] = &[947
"shell/title-bar/leading",1004
"shell/title-bar/leading",@@ -1195,6 +1252,13 @@ mod frames {1195
crate::theme::set_thread_scheme(None);1252
crate::theme::set_thread_scheme(None);1196
}1253
}1197
1254
1255
#[gpui_kit::test]1256
fn settings_dialog_keeps_its_inset_in_the_light_theme(cx: &mut TestAppContext) {1257
crate::theme::set_thread_shade(Some(crate::theme::Shade::Light));1258
check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);1259
crate::theme::set_thread_shade(None);1260
}1261
1198
fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {1262
fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {1199
let (handle, state) = mount_with(cx, true);1263
let (handle, state) = mount_with(cx, true);1200
let mut visual = VisualTestContext::from_window(handle, cx);1264
let mut visual = VisualTestContext::from_window(handle, cx);@@ -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
}@@ -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
button373
button374
.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);@@ -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};2
use gpui_kit::prelude::FluentBuilder as _;2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;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
use crate::active_appearance;6
use crate::active_appearance;7
use crate::app_state::AppState;7
use crate::app_state::AppState;8
use crate::appearance::AppIcon;8
use crate::appearance::{AppIcon, ThemeChoice};9
use crate::theme::{self, ColorScheme};9
use crate::theme::{self, Palette};10
use crate::views::title_bar::app_icon_image;10
use crate::views::title_bar::app_icon_image;11
11
12
const TILE_WIDTH: f32 = 168.;12
const TILE_WIDTH: f32 = 168.;@@ -19,6 +19,9 @@ const PREVIEW_ICON_SIZE: f32 = 48.;19
const RADIO_SIZE: f32 = 16.;19
const RADIO_SIZE: f32 = 16.;20
const RADIO_DOT_SIZE: f32 = 8.;20
const RADIO_DOT_SIZE: f32 = 8.;21
const COLOR_SCHEME_DETAIL: &str = "The colors to use for Rusty Teams";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
#[cfg(windows)]25
#[cfg(windows)]23
const APP_ICON_DETAIL: &str =26
const 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::ALL60
.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
151
fn scheme_preview(scheme: &ColorScheme) -> Div {175
fn 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
)@@ -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 @@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
members52
.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> = app85
.read(cx)86
.sidebar87
.chats88
.iter()89
.find(|chat| chat.id == chat_id)90
.map(|chat| {91
chat.members92
.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
input107
});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 = state151
.sidebar152
.chats153
.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
dialog258
.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
}@@ -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 @@1
use gpui_kit::prelude::FluentBuilder as _;1
use gpui_kit::prelude::FluentBuilder as _;2
use gpui_kit::*;2
use gpui_kit::*;3
3
4
use std::sync::Arc;4
use std::time::Duration;5
use std::time::Duration;5
6
6
use gpui_kit::assets::IconName;7
use gpui_kit::assets::IconName;7
8
9
use crate::avatar_image::{AvatarPhoto, device_span};8
use crate::card_state::BotIdentity;10
use crate::card_state::BotIdentity;9
use crate::data::{AvatarState, Directory, Presence, PresenceKind};11
use crate::data::{AvatarState, Directory, Presence, PresenceKind};10
use crate::format;12
use 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
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
pub fn person_avatar(106
pub 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)) => tile151
Some(AvatarState::Ready(photo)) => tile152
.child(photo_disc(photo, size, radius))153
.into_any_element(),154
Some(AvatarState::Icon(image)) => tile126
.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
146
pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<Div> {175
fn 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
184
fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {214
fn 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
202
pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {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
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: Hs222
.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: Hs232
.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();@@ -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))@@ -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;3
use calling::VideoKey;3
use calling::VideoKey;4
use gpui_kit::assets::IconName;4
use gpui_kit::assets::IconName;5
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};5
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};6
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;7
use gpui_kit::*;7
8
8
use super::avatar::person_avatar;9
use super::avatar::person_avatar;10
use super::call_share_gallery::{SHOW_MORE_PEOPLE, view_switch_button};9
use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};11
use super::call_view::{camera_button, leave_button, mute_button, round_control, status_line};10
use super::widgets::icon;12
use super::widgets::icon;11
use crate::app_state::AppState;13
use 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
}@@ -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
}@@ -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
971
pub(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
980
fn person_tile_body(990
fn 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
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
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
1059
fn own_tile_body(1079
fn own_tile_body(@@ -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};6
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;7
use gpui_kit::*;8
8
9
use super::add_people_dialog::open_add_people;9
use super::avatar::{person_avatar, with_presence};10
use super::avatar::{person_avatar, with_presence};10
use super::profile_card::opens_profile;11
use super::profile_card::opens_profile;11
use super::sidebar::confirm_leave;12
use 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());@@ -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
button2677
button2678
.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(|| {@@ -39,11 +39,12 @@ use super::avatar::{
39
39
};
40
40
use super::call_controls::header_call_controls;
41
41
use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
42
use super::add_people_dialog::open_add_people;
42
43
use super::chat_members::members_popover;
43
44
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
44
45
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
45
46
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
46
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder};
47
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
47
48
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
48
49
use super::post_card::render_post;
49
50
use super::profile_card::opens_profile;
@@ -930,6 +931,23 @@ impl ConversationView {
930
931
self.on_draft_changed(window, cx);
931
932
self.rebuild(true, cx);
932
933
}
934
let people = self
935
.app
936
.update(cx, |state, _| std::mem::take(&mut state.new_chat_people));
937
if !people.is_empty() {
938
let chips = people
939
.into_iter()
940
.filter_map(|person| {
941
Some(Pick {
942
user_id: person.user_id?,
943
name: person.display_name,
944
mail: None,
945
})
946
})
947
.collect();
948
self.draft
949
.update(cx, |draft, cx| draft.set_chips(chips, cx));
950
}
933
951
self.draft
934
952
.update(cx, |draft, cx| draft.focus_query(window, cx));
935
953
cx.notify();
@@ -3252,6 +3270,9 @@ impl ConversationView {
3252
3270
}
3253
3271
_ => String::new(),
3254
3272
};
3273
if is_one_on_one(chat) {
3274
stack = Some(add_people_button(&self.app, chat_id));
3275
}
3255
3276
} else {
3256
3277
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3257
3278
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
@@ -3722,6 +3743,17 @@ fn progress_bar() -> impl IntoElement {
3722
3743
)
3723
3744
}
3724
3745
3746
fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
3747
let (app, chat_id) = (app.clone(), chat_id.to_owned());
3748
Button::new("chat-add-people")
3749
.ghost()
3750
.compact()
3751
.icon(IconName::UserPlus)
3752
.tooltip("Add people")
3753
.on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
3754
.into_any_element()
3755
}
3756
3725
3757
#[cfg(test)]
3726
3758
mod tests {
3727
3759
use std::sync::Arc;
@@ -39,11 +39,12 @@ use super::avatar::{39
};39
};40
use super::call_controls::header_call_controls;40
use super::call_controls::header_call_controls;41
use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};41
use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};42
use super::add_people_dialog::open_add_people;42
use super::chat_members::members_popover;43
use super::chat_members::members_popover;43
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};44
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};44
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};45
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};45
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};46
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};46
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder};47
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};47
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};48
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};48
use super::post_card::render_post;49
use super::post_card::render_post;49
use super::profile_card::opens_profile;50
use super::profile_card::opens_profile;@@ -930,6 +931,23 @@ impl ConversationView {930
self.on_draft_changed(window, cx);931
self.on_draft_changed(window, cx);931
self.rebuild(true, cx);932
self.rebuild(true, cx);932
}933
}934
let people = self935
.app936
.update(cx, |state, _| std::mem::take(&mut state.new_chat_people));937
if !people.is_empty() {938
let chips = people939
.into_iter()940
.filter_map(|person| {941
Some(Pick {942
user_id: person.user_id?,943
name: person.display_name,944
mail: None,945
})946
})947
.collect();948
self.draft949
.update(cx, |draft, cx| draft.set_chips(chips, cx));950
}933
self.draft951
self.draft934
.update(cx, |draft, cx| draft.focus_query(window, cx));952
.update(cx, |draft, cx| draft.focus_query(window, cx));935
cx.notify();953
cx.notify();@@ -3252,6 +3270,9 @@ impl ConversationView {3252
}3270
}3253
_ => String::new(),3271
_ => String::new(),3254
};3272
};3273
if is_one_on_one(chat) {3274
stack = Some(add_people_button(&self.app, chat_id));3275
}3255
} else {3276
} else {3256
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));3277
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));3257
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));3278
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));@@ -3722,6 +3743,17 @@ fn progress_bar() -> impl IntoElement {3722
)3743
)3723
}3744
}3724
3745
3746
fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {3747
let (app, chat_id) = (app.clone(), chat_id.to_owned());3748
Button::new("chat-add-people")3749
.ghost()3750
.compact()3751
.icon(IconName::UserPlus)3752
.tooltip("Add people")3753
.on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))3754
.into_any_element()3755
}3756
3725
#[cfg(test)]3757
#[cfg(test)]3726
mod tests {3758
mod tests {3727
use std::sync::Arc;3759
use std::sync::Arc;@@ -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::*;10
use image::{Frame, ImageReader};10
use image::{Frame, ImageReader};11
11
12
use super::avatar::person_avatar;12
use super::avatar::person_avatar;13
use super::shortcuts::{ZoomIn, ZoomOut, ZoomReset};13
use super::widgets::symbol;14
use super::widgets::symbol;14
use crate::app_state::AppState;15
use crate::app_state::AppState;15
use crate::downloads;16
use 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(@@ -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 @@1
pub mod actions;1
pub mod actions;2
pub mod activity_panel;2
pub mod activity_panel;3
pub mod adaptive_card;3
pub mod adaptive_card;4
pub mod add_people_dialog;4
pub mod attachment_tray;5
pub mod attachment_tray;5
pub mod attachments;6
pub mod attachments;6
pub mod avatar;7
pub mod avatar;@@ -17,6 +18,7 @@ pub mod call_mini_window;17
pub mod call_organizer;18
pub mod call_organizer;18
pub mod call_people;19
pub mod call_people;19
pub mod call_pop_out;20
pub mod call_pop_out;21
pub mod call_share_gallery;20
pub mod call_record;22
pub mod call_record;21
pub mod call_stage;23
pub mod call_stage;22
pub mod call_transcript;24
pub mod call_transcript;@@ -77,6 +79,7 @@ pub mod title_bar;77
pub mod toolbar_placement;79
pub mod toolbar_placement;78
pub mod transfer_picker;80
pub mod transfer_picker;79
pub mod translation_line;81
pub mod translation_line;82
pub mod window_zoom;80
83
81
pub use app_ui_kit::{84
pub 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,@@ -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
87
fn without_excluded(picks: Vec<Pick>, excluded: &[String]) -> Vec<Pick> {88
picks89
.into_iter()90
.filter(|pick| !excluded.contains(&pick.user_id))91
.collect()92
}93
87
pub fn suggested_people(94
pub 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
self211
self203
}212
}204
213
214
pub fn excluding(mut self, user_ids: Vec<String>) -> Self {215
self.excluded = user_ids;216
self217
}218
205
pub fn chips(&self) -> &[Pick] {219
pub fn chips(&self) -> &[Pick] {206
&self.chips220
&self.chips207
}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);@@ -22,8 +22,10 @@ use super::shortcuts::{
22
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,6 +1034,9 @@ impl Render for AppShell {
1027
1034
this.state
1028
1035
.update(cx, |state, cx| state.toggle_call_fullscreen(cx));
1029
1036
}))
1037
.on_action(cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)))
1038
.on_action(cx.listener(|this, _: &ZoomOut, _, cx| change_zoom(&this.state, WindowZoom::Out, cx)))
1039
.on_action(cx.listener(|this, _: &ZoomReset, _, cx| change_zoom(&this.state, WindowZoom::Reset, cx)))
1030
1040
.on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1031
1041
.on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1032
1042
.on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
@@ -22,8 +22,10 @@ use super::shortcuts::{22
AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, 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
};28
use super::window_zoom::{WindowZoom, change_zoom};27
use super::call_pop_out::zoom_listener;29
use super::call_pop_out::zoom_listener;28
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};30
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};29
use super::sidebar::SidebarView;31
use 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
145
impl AppShell {148
impl 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.state298
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
shell342
shell@@ -1027,6 +1034,9 @@ impl Render for AppShell {1027
this.state1034
this.state1028
.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))@@ -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,
@@ -41,7 +48,10 @@ actions!(
41
48
ZoomShareOut,
42
49
ZoomShareReset,
43
50
ShowShortcuts,
44
OpenSettings
51
OpenSettings,
52
ZoomIn,
53
ZoomOut,
54
ZoomReset
45
55
]
46
56
);
47
57
@@ -108,6 +118,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
108
118
shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
109
119
shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
110
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),
111
124
shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
112
125
shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
113
126
shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
@@ -173,7 +186,7 @@ impl Shortcut {
173
186
keys.extend(
174
187
ALTERNATE_KEYS
175
188
.iter()
176
.filter(|(primary, _)| *primary == self.keys)
189
.filter(|(label, _)| *label == self.label)
177
190
.map(|(_, alternate)| *alternate),
178
191
);
179
192
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
@@ -358,6 +371,43 @@ mod tests {
358
371
assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
359
372
}
360
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
361
411
#[gpui_kit::test]
362
412
fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
363
413
registered(cx);
@@ -10,8 +10,15 @@ use super::actions::{10
const TEXT_FIELD_CONTEXT: &str = "Input";10
const TEXT_FIELD_CONTEXT: &str = "Input";11
const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";11
const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";12
const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";12
const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";13
const ALTERNATE_KEYS: &[(&str, &str)] =13
const 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
16
actions!(23
actions!(17
teams,24
teams,@@ -41,7 +48,10 @@ actions!(41
ZoomShareOut,48
ZoomShareOut,42
ZoomShareReset,49
ZoomShareReset,43
ShowShortcuts,50
ShowShortcuts,44
OpenSettings51
OpenSettings,52
ZoomIn,53
ZoomOut,54
ZoomReset45
]55
]46
);56
);47
57
@@ -108,6 +118,9 @@ pub const SHORTCUTS: &[Shortcut] = &[108
shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),118
shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),109
shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),119
shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),110
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),111
shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),124
shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),112
shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),125
shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),113
shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),126
shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),@@ -173,7 +186,7 @@ impl Shortcut {173
keys.extend(186
keys.extend(174
ALTERNATE_KEYS187
ALTERNATE_KEYS175
.iter()188
.iter()176
.filter(|(primary, _)| *primary == self.keys)189
.filter(|(label, _)| *label == self.label)177
.map(|(_, alternate)| *alternate),190
.map(|(_, alternate)| *alternate),178
);191
);179
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));192
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));@@ -358,6 +371,43 @@ mod tests {358
assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");371
assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");359
}372
}360
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
SHORTCUTS380
.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
361
#[gpui_kit::test]411
#[gpui_kit::test]362
fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {412
fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {363
registered(cx);413
registered(cx);@@ -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 @@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
button98
.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
}@@ -13,6 +13,7 @@ mod json_id;
13
13
pub mod language_settings;
14
14
pub mod links;
15
15
mod mask;
16
pub mod members;
16
17
pub mod messages;
17
18
pub mod pins;
18
19
pub mod presence;
@@ -54,6 +55,7 @@ pub use language_settings::{
54
55
};
55
56
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
56
57
pub use mask::mask_conversation_id;
58
pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
57
59
pub use messages::{ConversationRef, Messages};
58
60
pub use pins::{
59
61
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -13,6 +13,7 @@ mod json_id;13
pub mod language_settings;13
pub mod language_settings;14
pub mod links;14
pub mod links;15
mod mask;15
mod mask;16
pub mod members;16
pub mod messages;17
pub mod messages;17
pub mod pins;18
pub mod pins;18
pub mod presence;19
pub mod presence;@@ -54,6 +55,7 @@ pub use language_settings::{54
};55
};55
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};56
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};56
pub use mask::mask_conversation_id;57
pub use mask::mask_conversation_id;58
pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};57
pub use messages::{ConversationRef, Messages};59
pub use messages::{ConversationRef, Messages};58
pub use pins::{60
pub use pins::{59
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,61
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,@@ -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 @@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_ids48
.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_000160
);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
.await203
.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
}@@ -489,6 +489,27 @@ impl<R: Remote> SyncEngine<R> {
489
489
Ok(())
490
490
}
491
491
492
pub async fn add_chat_members(
493
&self,
494
chat_id: &str,
495
people: &[store::MemberRecord],
496
share: chatsvc::HistoryShare,
497
) -> Result<()> {
498
let user_ids: Vec<String> = people
499
.iter()
500
.filter_map(|person| person.user_id.clone())
501
.collect();
502
self.remote
503
.add_chat_members(chat_id, &user_ids, share)
504
.await?;
505
if let Some(mut chat) = self.store.chat(chat_id)? {
506
crate::roster_event::merge_members(&mut chat.members, people);
507
self.store.upsert_chats(std::slice::from_ref(&chat))?;
508
}
509
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
510
Ok(())
511
}
512
492
513
pub async fn send_typing(
493
514
&self,
494
515
conversation_id: &str,
@@ -489,6 +489,27 @@ impl<R: Remote> SyncEngine<R> {489
Ok(())489
Ok(())490
}490
}491
491
492
pub async fn add_chat_members(493
&self,494
chat_id: &str,495
people: &[store::MemberRecord],496
share: chatsvc::HistoryShare,497
) -> Result<()> {498
let user_ids: Vec<String> = people499
.iter()500
.filter_map(|person| person.user_id.clone())501
.collect();502
self.remote503
.add_chat_members(chat_id, &user_ids, share)504
.await?;505
if let Some(mut chat) = self.store.chat(chat_id)? {506
crate::roster_event::merge_members(&mut chat.members, people);507
self.store.upsert_chats(std::slice::from_ref(&chat))?;508
}509
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);510
Ok(())511
}512
492
pub async fn send_typing(513
pub async fn send_typing(493
&self,514
&self,494
conversation_id: &str,515
conversation_id: &str,@@ -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 @@1
use chrono::{Duration, Utc};1
use chrono::{DateTime, Duration, Utc};2
use store::{AvatarRecord, is_bot_id};2
use store::{AvatarRecord, is_bot_id};3
3
4
use crate::engine::SyncEngine;4
use crate::engine::SyncEngine;@@ -8,6 +8,14 @@ use crate::remote::Remote;8
8
9
const AVATAR_MAX_AGE_DAYS: i64 = 7;9
const AVATAR_MAX_AGE_DAYS: i64 = 7;10
const AVATAR_BATCH: usize = 60;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
#[derive(Debug, Clone, PartialEq, Eq)]20
#[derive(Debug, Clone, PartialEq, Eq)]13
pub struct Avatar {21
pub 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)]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
}@@ -48,6 +48,7 @@ mod profile;
48
48
mod receipts;
49
49
mod recording_rights;
50
50
mod remote;
51
pub mod roster_event;
51
52
mod scheduled;
52
53
mod search;
53
54
mod server_search;
@@ -48,6 +48,7 @@ mod profile;48
mod receipts;48
mod receipts;49
mod recording_rights;49
mod recording_rights;50
mod remote;50
mod remote;51
pub mod roster_event;51
mod scheduled;52
mod scheduled;52
mod search;53
mod search;53
mod server_search;54
mod server_search;@@ -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;8
use crate::links::EMPTY_LINKS;8
use crate::links::EMPTY_LINKS;9
use crate::markdown::plain_text_to_html;9
use crate::markdown::plain_text_to_html;10
use crate::preview::OwnedPreview;10
use crate::preview::OwnedPreview;11
use crate::roster_event::RosterEvent;11
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};12
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};12
13
13
pub fn graph_hidden(chat: &Chat) -> bool {14
pub fn graph_hidden(chat: &Chat) -> bool {@@ -117,7 +118,12 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag117
.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 = message122
.event_detail123
.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<Messag139
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<Messag172
.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_event182
.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();@@ -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};5
use crate::call_event::{CallEvent, CallPhase, call_event};5
use crate::call_event::{CallEvent, CallPhase, call_event};6
use crate::external_image::is_giphy_url;6
use crate::external_image::is_giphy_url;7
use crate::forwarded::FORWARDED_CONTENT_TYPE;7
use crate::forwarded::FORWARDED_CONTENT_TYPE;8
use crate::roster_event::{RosterChange, roster_event};8
use crate::spans::{Span, html_to_spans};9
use crate::spans::{Span, html_to_spans};9
use crate::stored::{AttachmentInfo, attachments};10
use 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
None255
None254
} 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
}@@ -4,12 +4,13 @@ use chatsvc::substrate_search::{
4
4
};
5
5
use chatsvc::{
6
6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,
8
InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,
9
MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,
10
PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,
11
ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,
12
Translator, WindowDirection, WorkLocationKind,
7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
8
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
9
MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
10
PinnedMessage, Pins, PresenceLookup, PresenceService, PresenceStatus, Receipts,
11
RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,
12
TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,
13
WorkLocationKind,
13
14
};
14
15
use chrono::{DateTime, Utc};
15
16
use graph::{
@@ -126,6 +127,12 @@ pub trait Remote {
126
127
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
127
128
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
128
129
async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
130
async fn add_chat_members(
131
&self,
132
chat_id: &str,
133
user_ids: &[String],
134
share: HistoryShare,
135
) -> Result<()>;
129
136
async fn chat_states(&self) -> Result<Vec<ConversationState>>;
130
137
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
131
138
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
@@ -671,7 +678,20 @@ impl Remote for Graph {
671
678
}
672
679
673
680
async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
674
Ok(Graph::remove_chat_member(self, chat_id, user_id).await?)
681
Ok(ThreadMembers::new(self.session())
682
.remove(chat_id, user_id)
683
.await?)
684
}
685
686
async fn add_chat_members(
687
&self,
688
chat_id: &str,
689
user_ids: &[String],
690
share: HistoryShare,
691
) -> Result<()> {
692
Ok(ThreadMembers::new(self.session())
693
.add(chat_id, user_ids, share, Utc::now().timestamp_millis())
694
.await?)
675
695
}
676
696
677
697
async fn chat_states(&self) -> Result<Vec<ConversationState>> {
@@ -4,12 +4,13 @@ use chatsvc::substrate_search::{4
};4
};5
use chatsvc::{5
use chatsvc::{6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,8
InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,8
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,9
MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,9
MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,10
PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,10
PinnedMessage, Pins, PresenceLookup, PresenceService, PresenceStatus, Receipts,11
ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,11
RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,12
Translator, WindowDirection, WorkLocationKind,12
TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,13
WorkLocationKind,13
};14
};14
use chrono::{DateTime, Utc};15
use chrono::{DateTime, Utc};15
use graph::{16
use graph::{@@ -126,6 +127,12 @@ pub trait Remote {126
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;127
async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;127
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;128
async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;128
async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;129
async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;130
async fn add_chat_members(131
&self,132
chat_id: &str,133
user_ids: &[String],134
share: HistoryShare,135
) -> Result<()>;129
async fn chat_states(&self) -> Result<Vec<ConversationState>>;136
async fn chat_states(&self) -> Result<Vec<ConversationState>>;130
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;137
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;131
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;138
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;@@ -671,7 +678,20 @@ impl Remote for Graph {671
}678
}672
679
673
async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {680
async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {674
Ok(Graph::remove_chat_member(self, chat_id, user_id).await?)681
Ok(ThreadMembers::new(self.session())682
.remove(chat_id, user_id)683
.await?)684
}685
686
async fn add_chat_members(687
&self,688
chat_id: &str,689
user_ids: &[String],690
share: HistoryShare,691
) -> Result<()> {692
Ok(ThreadMembers::new(self.session())693
.add(chat_id, user_ids, share, Utc::now().timestamp_millis())694
.await?)675
}695
}676
696
677
async fn chat_states(&self) -> Result<Vec<ConversationState>> {697
async fn chat_states(&self) -> Result<Vec<ConversationState>> {@@ -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 @@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>)> = detail47
.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 = detail57
.pointer("/initiator/user")58
.or_else(|| detail.pointer("/initiator/application"));59
let initiator_id = initiator60
.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
detail75
.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> = self109
.member_ids110
.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 = members141
.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
identity160
.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<_> = members297
.iter()298
.filter_map(|record| record.user_id.clone())299
.collect();300
assert_eq!(ids, ["me", "ann", "bob"]);301
}302
}@@ -556,6 +556,19 @@ impl Remote for Handle {
556
556
Ok(())
557
557
}
558
558
559
async fn add_chat_members(
560
&self,
561
chat_id: &str,
562
user_ids: &[String],
563
share: chatsvc::HistoryShare,
564
) -> Result<()> {
565
self.record(format!(
566
"add members {chat_id} {} {share:?}",
567
user_ids.join(",")
568
));
569
Ok(())
570
}
571
559
572
async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {
560
573
if *self.muted_fails.lock().unwrap() {
561
574
return Err(Error::Unsupported("forced failure"));
@@ -1460,6 +1473,34 @@ async fn removing_a_member_drops_them_from_the_cached_chat() {
1460
1473
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1461
1474
}
1462
1475
1476
#[tokio::test]
1477
async fn adding_members_writes_them_and_extends_the_cached_chat() {
1478
let fake = Arc::new(Fake::default());
1479
let engine = chat_engine(&fake, small_pages()).await;
1480
let mut events = engine.subscribe();
1481
let people = [store::MemberRecord {
1482
user_id: Some("user-bob".to_owned()),
1483
display_name: "Bob".to_owned(),
1484
}];
1485
1486
engine
1487
.add_chat_members(CHAT, &people, chatsvc::HistoryShare::Days(7))
1488
.await
1489
.unwrap();
1490
assert_eq!(
1491
fake.calls().last().unwrap(),
1492
&format!("add members {CHAT} user-bob Days(7)")
1493
);
1494
let chats = engine.sidebar().unwrap().chats;
1495
assert!(
1496
chats[0]
1497
.members
1498
.iter()
1499
.any(|member| member.user_id.as_deref() == Some("user-bob"))
1500
);
1501
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1502
}
1503
1463
1504
#[tokio::test]
1464
1505
async fn failing_channel_listing_is_reported_not_fatal() {
1465
1506
let fake = Arc::new(Fake::default());
@@ -556,6 +556,19 @@ impl Remote for Handle {556
Ok(())556
Ok(())557
}557
}558
558
559
async fn add_chat_members(560
&self,561
chat_id: &str,562
user_ids: &[String],563
share: chatsvc::HistoryShare,564
) -> Result<()> {565
self.record(format!(566
"add members {chat_id} {} {share:?}",567
user_ids.join(",")568
));569
Ok(())570
}571
559
async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {572
async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> {560
if *self.muted_fails.lock().unwrap() {573
if *self.muted_fails.lock().unwrap() {561
return Err(Error::Unsupported("forced failure"));574
return Err(Error::Unsupported("forced failure"));@@ -1460,6 +1473,34 @@ async fn removing_a_member_drops_them_from_the_cached_chat() {1460
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);1473
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);1461
}1474
}1462
1475
1476
#[tokio::test]1477
async fn adding_members_writes_them_and_extends_the_cached_chat() {1478
let fake = Arc::new(Fake::default());1479
let engine = chat_engine(&fake, small_pages()).await;1480
let mut events = engine.subscribe();1481
let people = [store::MemberRecord {1482
user_id: Some("user-bob".to_owned()),1483
display_name: "Bob".to_owned(),1484
}];1485
1486
engine1487
.add_chat_members(CHAT, &people, chatsvc::HistoryShare::Days(7))1488
.await1489
.unwrap();1490
assert_eq!(1491
fake.calls().last().unwrap(),1492
&format!("add members {CHAT} user-bob Days(7)")1493
);1494
let chats = engine.sidebar().unwrap().chats;1495
assert!(1496
chats[0]1497
.members1498
.iter()1499
.any(|member| member.user_id.as_deref() == Some("user-bob"))1500
);1501
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);1502
}1503
1463
#[tokio::test]1504
#[tokio::test]1464
async fn failing_channel_listing_is_reported_not_fatal() {1505
async fn failing_channel_listing_is_reported_not_fatal() {1465
let fake = Arc::new(Fake::default());1506
let fake = Arc::new(Fake::default());@@ -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
20
impl Graph {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 rendition22
/// 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> = photos26
.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> = missing35
.iter()36
.map(|index| user_ids[*index].clone())37
.collect();38
let originals = self39
.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> = chunk55
let requests: Vec<Request> = chunk27
.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(@@ -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,\
@@ -214,10 +220,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
214
220
}
215
221
216
222
pub fn shared_drive_item(share_id: &str) -> String {
217
format!(
218
"{GRAPH}/v1.0/shares/{}/driveItem",
219
segment(share_id)
220
)
223
format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
221
224
}
222
225
223
226
pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
@@ -355,6 +358,18 @@ mod tests {
355
358
356
359
use super::*;
357
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
358
373
#[test]
359
374
fn chat_ids_are_path_encoded() {
360
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
19
const PHOTO_SIZE: &str = "240x240";20
19
pub fn user_photo(user_id: &str) -> String {21
pub 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
28
pub fn user_photo_original(user_id: &str) -> String {29
format!("{GRAPH}/v1.0/users/{}/photo/$value", segment(user_id))30
}31
26
pub fn user_profile(user_id: &str) -> String {32
pub 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,\@@ -214,10 +220,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {214
}220
}215
221
216
pub fn shared_drive_item(share_id: &str) -> String {222
pub fn shared_drive_item(share_id: &str) -> String {217
format!(223
format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))218
"{GRAPH}/v1.0/shares/{}/driveItem",219
segment(share_id)220
)221
}224
}222
225
223
pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {226
pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {@@ -355,6 +358,18 @@ mod tests {355
358
356
use super::*;359
use super::*;357
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
358
#[test]373
#[test]359
fn chat_ids_are_path_encoded() {374
fn chat_ids_are_path_encoded() {360
assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");375
assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");