BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/share-layout

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
83799a2ef7a6586e88be95cd52d78a83f42aa7cd
9 files changed +391 −138
crates/app-base/src/avatar_image.rs +145 −47
@@ -1,45 +1,107 @@
1 1 use std::io::Cursor;
2 use std::sync::{Arc, Mutex};
2 3
4 use gpui_kit::RenderImage;
3 5 use image::imageops::FilterType;
4 use image::{ImageFormat, Rgba, RgbaImage};
6 use image::{Frame, ImageFormat, ImageReader, RgbaImage};
5 7
6 const TEXTURE_SIZE: u32 = 100;
7 const MARGIN: f32 = 2.;
8 const MAX_TEXTURES: usize = 8;
9 const SOURCE_SIDE: u32 = 240;
10 const SOURCE_LIMIT: u32 = 2 * SOURCE_SIDE;
8 11
9 pub fn circular_png(bytes: &[u8]) -> Option<Vec<u8>> {
10 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
11 let side = decoded.width().min(decoded.height());
12 let left = (decoded.width() - side) / 2;
13 let top = (decoded.height() - side) / 2;
14 let square = image::imageops::crop_imm(&decoded, left, top, side, side).to_image();
15 let mut resized =
16 image::imageops::resize(&square, TEXTURE_SIZE, TEXTURE_SIZE, FilterType::Lanczos3);
17 apply_circle_mask(&mut resized);
12 pub struct AvatarPhoto {
13 bytes: Vec<u8>,
14 textures: Mutex<Vec<(u32, Arc<RenderImage>)>>,
15 }
16
17 pub struct Texture {
18 pub image: Arc<RenderImage>,
19 pub evicted: Option<Arc<RenderImage>>,
20 }
21
22 impl AvatarPhoto {
23 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
24 let (width, height) = ImageReader::new(Cursor::new(&bytes))
25 .with_guessed_format()
26 .ok()?
27 .into_dimensions()
28 .ok()?;
29 if width == 0 || height == 0 {
30 return None;
31 }
32 let bytes = if width.max(height) > SOURCE_LIMIT {
33 shrunk_source(&bytes)?
34 } else {
35 bytes
36 };
37 Some(Self {
38 bytes,
39 textures: Mutex::new(Vec::new()),
40 })
41 }
42
43 pub fn texture(&self, side: u32) -> Option<Texture> {
44 let mut textures = self.textures.lock().ok()?;
45 if let Some(position) = textures.iter().position(|(cached, _)| *cached == side) {
46 let entry = textures.remove(position);
47 let image = entry.1.clone();
48 textures.push(entry);
49 return Some(Texture {
50 image,
51 evicted: None,
52 });
53 }
54 let pixels = square_texture(&self.bytes, side)?;
55 let image = Arc::new(RenderImage::new(vec![Frame::new(pixels)]));
56 let evicted = (textures.len() >= MAX_TEXTURES).then(|| textures.remove(0).1);
57 textures.push((side, image.clone()));
58 Some(Texture { image, evicted })
59 }
60 }
61
62 fn shrunk_source(bytes: &[u8]) -> Option<Vec<u8>> {
63 let mut source = square_texture(bytes, SOURCE_SIDE)?;
64 for pixel in source.pixels_mut() {
65 pixel.0.swap(0, 2);
66 }
18 67 let mut encoded = Vec::new();
19 resized
68 source
20 69 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
21 70 .ok()?;
22 71 Some(encoded)
23 72 }
24 73
25 fn apply_circle_mask(texture: &mut RgbaImage) {
26 let center = TEXTURE_SIZE as f32 / 2.;
27 let radius = center - MARGIN;
28 for (x, y, pixel) in texture.enumerate_pixels_mut() {
29 let distance =
30 ((x as f32 + 0.5 - center).powi(2) + (y as f32 + 0.5 - center).powi(2)).sqrt();
31 let coverage = (radius + 0.5 - distance).clamp(0., 1.);
32 let Rgba([red, green, blue, alpha]) = *pixel;
33 *pixel = Rgba([red, green, blue, (alpha as f32 * coverage).round() as u8]);
34 }
74 pub fn device_span(start: f32, end: f32, scale_factor: f32) -> u32 {
75 let snapped =
76 round_half_toward_zero(end * scale_factor) - round_half_toward_zero(start * scale_factor);
77 snapped.max(1.) as u32
78 }
79
80 fn round_half_toward_zero(value: f32) -> f32 {
81 value.signum() * (value.abs() - 0.5).ceil()
35 82 }
36 83
37 pub fn visible_fraction() -> f32 {
38 (TEXTURE_SIZE as f32 - 2. * MARGIN) / TEXTURE_SIZE as f32
84 pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {
85 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
86 let crop = decoded.width().min(decoded.height());
87 let left = (decoded.width() - crop) / 2;
88 let top = (decoded.height() - crop) / 2;
89 let square = image::imageops::crop_imm(&decoded, left, top, crop, crop).to_image();
90 let mut texture = if crop == side {
91 square
92 } else {
93 image::imageops::resize(&square, side, side, FilterType::Lanczos3)
94 };
95 for pixel in texture.pixels_mut() {
96 pixel.0.swap(0, 2);
97 }
98 Some(texture)
39 99 }
40 100
41 101 #[cfg(test)]
42 102 mod tests {
103 use image::Rgba;
104
43 105 use super::*;
44 106
45 107 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
@@ -53,35 +115,71 @@ mod tests {
53 115 }
54 116
55 117 #[test]
56 fn texture_edges_are_transparent_and_center_is_opaque() {
57 let masked = image::load_from_memory(&circular_png(&solid_jpeg(48, 48)).unwrap())
58 .unwrap()
59 .to_rgba8();
60 assert_eq!(masked.dimensions(), (TEXTURE_SIZE, TEXTURE_SIZE));
61 let middle = TEXTURE_SIZE / 2;
62 for (x, y) in [
63 (middle, 0),
64 (middle, TEXTURE_SIZE - 1),
65 (0, middle),
66 (TEXTURE_SIZE - 1, middle),
67 (0, 0),
68 ] {
69 assert_eq!(
70 masked.get_pixel(x, y)[3],
71 0,
72 "edge pixel {x},{y} must be transparent"
73 );
74 }
75 assert_eq!(masked.get_pixel(middle, middle)[3], 255);
118 fn texture_matches_the_device_pixels_and_is_bgra() {
119 let texture = square_texture(&solid_jpeg(240, 240), 39).unwrap();
120 assert_eq!(texture.dimensions(), (39, 39));
121 let Rgba([blue, _, red, alpha]) = *texture.get_pixel(19, 19);
122 assert!(
123 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
124 "{blue} {red}"
125 );
126 assert_eq!(alpha, 255);
76 127 }
77 128
78 129 #[test]
79 130 fn non_square_photos_are_center_cropped() {
80 assert!(circular_png(&solid_jpeg(64, 40)).is_some());
131 assert_eq!(
132 square_texture(&solid_jpeg(64, 40), 60)
133 .unwrap()
134 .dimensions(),
135 (60, 60)
136 );
137 }
138
139 #[test]
140 fn device_span_follows_the_snapped_bounds() {
141 assert_eq!(device_span(0., 26., 1.), 26);
142 assert_eq!(device_span(0., 28., 1.5), 42);
143 assert_eq!(device_span(10.5, 36.5, 1.5), 39);
144 assert_eq!(device_span(10.1, 36.1, 1.5), 39);
145 assert_eq!(device_span(0., 32., 1.25), 40);
146 assert_eq!(device_span(0., 0.1, 1.), 1);
147 assert_eq!(device_span(-3.5, 22.5, 1.), 25);
148 }
149
150 #[test]
151 fn textures_are_cached_per_side_and_evict_the_oldest() {
152 let photo = AvatarPhoto::from_bytes(solid_jpeg(48, 48)).unwrap();
153 let first = photo.texture(32).unwrap();
154 let again = photo.texture(32).unwrap();
155 assert_eq!(first.image.id, again.image.id);
156 assert!(again.evicted.is_none());
157 for side in 33..33 + MAX_TEXTURES as u32 - 1 {
158 assert!(photo.texture(side).unwrap().evicted.is_none());
159 }
160 let overflow = photo.texture(100).unwrap();
161 assert_eq!(overflow.evicted.map(|image| image.id), Some(first.image.id));
162 }
163
164 #[test]
165 fn large_originals_are_kept_at_the_source_side() {
166 let photo = AvatarPhoto::from_bytes(solid_jpeg(1200, 900)).unwrap();
167 let dimensions = image::load_from_memory(&photo.bytes)
168 .unwrap()
169 .to_rgba8()
170 .dimensions();
171 assert_eq!(dimensions, (SOURCE_SIDE, SOURCE_SIDE));
172 let texture = photo.texture(20).unwrap().image;
173 let raw = texture.as_bytes(0).unwrap().to_vec();
174 let Rgba([blue, _, red, _]) = *RgbaImage::from_raw(20, 20, raw).unwrap().get_pixel(10, 10);
175 assert!(
176 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
177 "{blue} {red}"
178 );
81 179 }
82 180
83 181 #[test]
84 182 fn garbage_bytes_fall_back() {
85 assert!(circular_png(b"not an image").is_none());
183 assert!(AvatarPhoto::from_bytes(b"not an image".to_vec()).is_none());
86 184 }
87 185 }
@@ -1,45 +1,107 @@
1use std::io::Cursor;
1use std::io::Cursor;
2use std::sync::{Arc, Mutex};
2
3
4use gpui_kit::RenderImage;
3use image::imageops::FilterType;
5use image::imageops::FilterType;
4use image::{ImageFormat, Rgba, RgbaImage};
6use image::{Frame, ImageFormat, ImageReader, RgbaImage};
5
7
6const TEXTURE_SIZE: u32 = 100;
8const MAX_TEXTURES: usize = 8;
7const MARGIN: f32 = 2.;
9const SOURCE_SIDE: u32 = 240;
10const SOURCE_LIMIT: u32 = 2 * SOURCE_SIDE;
8
11
9pub fn circular_png(bytes: &[u8]) -> Option<Vec<u8>> {
12pub struct AvatarPhoto {
10 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
13 bytes: Vec<u8>,
11 let side = decoded.width().min(decoded.height());
14 textures: Mutex<Vec<(u32, Arc<RenderImage>)>>,
12 let left = (decoded.width() - side) / 2;
15}
13 let top = (decoded.height() - side) / 2;
16
14 let square = image::imageops::crop_imm(&decoded, left, top, side, side).to_image();
17pub struct Texture {
15 let mut resized =
18 pub image: Arc<RenderImage>,
16 image::imageops::resize(&square, TEXTURE_SIZE, TEXTURE_SIZE, FilterType::Lanczos3);
19 pub evicted: Option<Arc<RenderImage>>,
17 apply_circle_mask(&mut resized);
20}
21
22impl AvatarPhoto {
23 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
24 let (width, height) = ImageReader::new(Cursor::new(&bytes))
25 .with_guessed_format()
26 .ok()?
27 .into_dimensions()
28 .ok()?;
29 if width == 0 || height == 0 {
30 return None;
31 }
32 let bytes = if width.max(height) > SOURCE_LIMIT {
33 shrunk_source(&bytes)?
34 } else {
35 bytes
36 };
37 Some(Self {
38 bytes,
39 textures: Mutex::new(Vec::new()),
40 })
41 }
42
43 pub fn texture(&self, side: u32) -> Option<Texture> {
44 let mut textures = self.textures.lock().ok()?;
45 if let Some(position) = textures.iter().position(|(cached, _)| *cached == side) {
46 let entry = textures.remove(position);
47 let image = entry.1.clone();
48 textures.push(entry);
49 return Some(Texture {
50 image,
51 evicted: None,
52 });
53 }
54 let pixels = square_texture(&self.bytes, side)?;
55 let image = Arc::new(RenderImage::new(vec![Frame::new(pixels)]));
56 let evicted = (textures.len() >= MAX_TEXTURES).then(|| textures.remove(0).1);
57 textures.push((side, image.clone()));
58 Some(Texture { image, evicted })
59 }
60}
61
62fn shrunk_source(bytes: &[u8]) -> Option<Vec<u8>> {
63 let mut source = square_texture(bytes, SOURCE_SIDE)?;
64 for pixel in source.pixels_mut() {
65 pixel.0.swap(0, 2);
66 }
18 let mut encoded = Vec::new();
67 let mut encoded = Vec::new();
19 resized
68 source
20 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
69 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
21 .ok()?;
70 .ok()?;
22 Some(encoded)
71 Some(encoded)
23}
72}
24
73
25fn apply_circle_mask(texture: &mut RgbaImage) {
74pub fn device_span(start: f32, end: f32, scale_factor: f32) -> u32 {
26 let center = TEXTURE_SIZE as f32 / 2.;
75 let snapped =
27 let radius = center - MARGIN;
76 round_half_toward_zero(end * scale_factor) - round_half_toward_zero(start * scale_factor);
28 for (x, y, pixel) in texture.enumerate_pixels_mut() {
77 snapped.max(1.) as u32
29 let distance =
78}
30 ((x as f32 + 0.5 - center).powi(2) + (y as f32 + 0.5 - center).powi(2)).sqrt();
79
31 let coverage = (radius + 0.5 - distance).clamp(0., 1.);
80fn round_half_toward_zero(value: f32) -> f32 {
32 let Rgba([red, green, blue, alpha]) = *pixel;
81 value.signum() * (value.abs() - 0.5).ceil()
33 *pixel = Rgba([red, green, blue, (alpha as f32 * coverage).round() as u8]);
34 }
35}
82}
36
83
37pub fn visible_fraction() -> f32 {
84pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {
38 (TEXTURE_SIZE as f32 - 2. * MARGIN) / TEXTURE_SIZE as f32
85 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
86 let crop = decoded.width().min(decoded.height());
87 let left = (decoded.width() - crop) / 2;
88 let top = (decoded.height() - crop) / 2;
89 let square = image::imageops::crop_imm(&decoded, left, top, crop, crop).to_image();
90 let mut texture = if crop == side {
91 square
92 } else {
93 image::imageops::resize(&square, side, side, FilterType::Lanczos3)
94 };
95 for pixel in texture.pixels_mut() {
96 pixel.0.swap(0, 2);
97 }
98 Some(texture)
39}
99}
40
100
41#[cfg(test)]
101#[cfg(test)]
42mod tests {
102mod tests {
103 use image::Rgba;
104
43 use super::*;
105 use super::*;
44
106
45 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
107 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
@@ -53,35 +115,71 @@ mod tests {
53 }
115 }
54
116
55 #[test]
117 #[test]
56 fn texture_edges_are_transparent_and_center_is_opaque() {
118 fn texture_matches_the_device_pixels_and_is_bgra() {
57 let masked = image::load_from_memory(&circular_png(&solid_jpeg(48, 48)).unwrap())
119 let texture = square_texture(&solid_jpeg(240, 240), 39).unwrap();
58 .unwrap()
120 assert_eq!(texture.dimensions(), (39, 39));
59 .to_rgba8();
121 let Rgba([blue, _, red, alpha]) = *texture.get_pixel(19, 19);
60 assert_eq!(masked.dimensions(), (TEXTURE_SIZE, TEXTURE_SIZE));
122 assert!(
61 let middle = TEXTURE_SIZE / 2;
123 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
62 for (x, y) in [
124 "{blue} {red}"
63 (middle, 0),
125 );
64 (middle, TEXTURE_SIZE - 1),
126 assert_eq!(alpha, 255);
65 (0, middle),
66 (TEXTURE_SIZE - 1, middle),
67 (0, 0),
68 ] {
69 assert_eq!(
70 masked.get_pixel(x, y)[3],
71 0,
72 "edge pixel {x},{y} must be transparent"
73 );
74 }
75 assert_eq!(masked.get_pixel(middle, middle)[3], 255);
76 }
127 }
77
128
78 #[test]
129 #[test]
79 fn non_square_photos_are_center_cropped() {
130 fn non_square_photos_are_center_cropped() {
80 assert!(circular_png(&solid_jpeg(64, 40)).is_some());
131 assert_eq!(
132 square_texture(&solid_jpeg(64, 40), 60)
133 .unwrap()
134 .dimensions(),
135 (60, 60)
136 );
137 }
138
139 #[test]
140 fn device_span_follows_the_snapped_bounds() {
141 assert_eq!(device_span(0., 26., 1.), 26);
142 assert_eq!(device_span(0., 28., 1.5), 42);
143 assert_eq!(device_span(10.5, 36.5, 1.5), 39);
144 assert_eq!(device_span(10.1, 36.1, 1.5), 39);
145 assert_eq!(device_span(0., 32., 1.25), 40);
146 assert_eq!(device_span(0., 0.1, 1.), 1);
147 assert_eq!(device_span(-3.5, 22.5, 1.), 25);
148 }
149
150 #[test]
151 fn textures_are_cached_per_side_and_evict_the_oldest() {
152 let photo = AvatarPhoto::from_bytes(solid_jpeg(48, 48)).unwrap();
153 let first = photo.texture(32).unwrap();
154 let again = photo.texture(32).unwrap();
155 assert_eq!(first.image.id, again.image.id);
156 assert!(again.evicted.is_none());
157 for side in 33..33 + MAX_TEXTURES as u32 - 1 {
158 assert!(photo.texture(side).unwrap().evicted.is_none());
159 }
160 let overflow = photo.texture(100).unwrap();
161 assert_eq!(overflow.evicted.map(|image| image.id), Some(first.image.id));
162 }
163
164 #[test]
165 fn large_originals_are_kept_at_the_source_side() {
166 let photo = AvatarPhoto::from_bytes(solid_jpeg(1200, 900)).unwrap();
167 let dimensions = image::load_from_memory(&photo.bytes)
168 .unwrap()
169 .to_rgba8()
170 .dimensions();
171 assert_eq!(dimensions, (SOURCE_SIDE, SOURCE_SIDE));
172 let texture = photo.texture(20).unwrap().image;
173 let raw = texture.as_bytes(0).unwrap().to_vec();
174 let Rgba([blue, _, red, _]) = *RgbaImage::from_raw(20, 20, raw).unwrap().get_pixel(10, 10);
175 assert!(
176 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
177 "{blue} {red}"
178 );
81 }
179 }
82
180
83 #[test]
181 #[test]
84 fn garbage_bytes_fall_back() {
182 fn garbage_bytes_fall_back() {
85 assert!(circular_png(b"not an image").is_none());
183 assert!(AvatarPhoto::from_bytes(b"not an image".to_vec()).is_none());
86 }
184 }
87}
185}
crates/app-state/src/data.rs +20 −16
@@ -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
@@ -539,21 +540,24 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
539 540 store.pinned_channel_ids().unwrap_or_default()
540 541 }
541 542
542 pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
543 pub fn cached_avatar(store: &Store, user_id: &str) -> Option<AvatarState> {
543 544 let record = store.avatar(user_id).ok().flatten()?;
544 Some(record.bytes.map(|bytes| {
545 if is_bot_id(user_id) {
546 Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
547 } else {
548 avatar_image_from(&record.content_type, bytes)
549 }
550 }))
545 Some(match record.bytes {
546 Some(bytes) => avatar_state_from(&record.content_type, bytes, is_bot_id(user_id)),
547 None => AvatarState::Missing,
548 })
551 549 }
552 550
553 pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
554 match crate::avatar_image::circular_png(&bytes) {
555 Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
556 None => Arc::new(Image::from_bytes(image_format(content_type), bytes)),
551 pub fn avatar_state_from(content_type: &str, bytes: Vec<u8>, is_bot: bool) -> AvatarState {
552 if image_format(content_type) == ImageFormat::Svg {
553 if is_bot {
554 return AvatarState::Icon(Arc::new(Image::from_bytes(ImageFormat::Svg, bytes)));
555 }
556 return AvatarState::Missing;
557 }
558 match AvatarPhoto::from_bytes(bytes) {
559 Some(photo) => AvatarState::Ready(Arc::new(photo)),
560 None => AvatarState::Missing,
557 561 }
558 562 }
559 563
@@ -821,7 +825,7 @@ mod tests {
821 825 #[test]
822 826 fn missing_avatars_skip_known_and_duplicates() {
823 827 let mut directory = Directory::default();
824 directory.set_avatar("known", None);
828 directory.set_avatar("known", AvatarState::Missing);
825 829 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
826 830 assert_eq!(wanted, vec!["x", "y"]);
827 831 directory.mark_avatars_pending(&wanted);
@@ -9,6 +9,7 @@ use store::{ChatRecord, Store, is_bot_id};
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10use tokio::sync::oneshot;
10use tokio::sync::oneshot;
11
11
12use crate::avatar_image::AvatarPhoto;
12use crate::backend::Engine;
13use crate::backend::Engine;
13use crate::runtime;
14use crate::runtime;
14
15
@@ -113,7 +114,8 @@ impl Presence {
113pub enum AvatarState {
114pub enum AvatarState {
114 Pending,
115 Pending,
115 Missing,
116 Missing,
116 Ready(Arc<Image>),
117 Ready(Arc<AvatarPhoto>),
118 Icon(Arc<Image>),
117}
119}
118
120
119#[derive(Debug, Clone)]
121#[derive(Debug, Clone)]
@@ -201,8 +203,7 @@ impl Directory {
201 }
203 }
202 }
204 }
203
205
204 pub fn set_avatar(&mut self, user_id: &str, image: Option<Arc<Image>>) {
206 pub fn set_avatar(&mut self, user_id: &str, state: AvatarState) {
205 let state = image.map_or(AvatarState::Missing, AvatarState::Ready);
206 self.avatars.insert(user_id.to_owned(), state);
207 self.avatars.insert(user_id.to_owned(), state);
207 }
208 }
208
209
@@ -539,21 +540,24 @@ pub fn pinned_channels(store: &Store) -> Vec<String> {
539 store.pinned_channel_ids().unwrap_or_default()
540 store.pinned_channel_ids().unwrap_or_default()
540}
541}
541
542
542pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
543pub fn cached_avatar(store: &Store, user_id: &str) -> Option<AvatarState> {
543 let record = store.avatar(user_id).ok().flatten()?;
544 let record = store.avatar(user_id).ok().flatten()?;
544 Some(record.bytes.map(|bytes| {
545 Some(match record.bytes {
545 if is_bot_id(user_id) {
546 Some(bytes) => avatar_state_from(&record.content_type, bytes, is_bot_id(user_id)),
546 Arc::new(Image::from_bytes(image_format(&record.content_type), bytes))
547 None => AvatarState::Missing,
547 } else {
548 })
548 avatar_image_from(&record.content_type, bytes)
549 }
550 }))
551}
549}
552
550
553pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
551pub fn avatar_state_from(content_type: &str, bytes: Vec<u8>, is_bot: bool) -> AvatarState {
554 match crate::avatar_image::circular_png(&bytes) {
552 if image_format(content_type) == ImageFormat::Svg {
555 Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
553 if is_bot {
556 None => Arc::new(Image::from_bytes(image_format(content_type), bytes)),
554 return AvatarState::Icon(Arc::new(Image::from_bytes(ImageFormat::Svg, bytes)));
555 }
556 return AvatarState::Missing;
557 }
558 match AvatarPhoto::from_bytes(bytes) {
559 Some(photo) => AvatarState::Ready(Arc::new(photo)),
560 None => AvatarState::Missing,
557 }
561 }
558}
562}
559
563
@@ -821,7 +825,7 @@ mod tests {
821 #[test]
825 #[test]
822 fn missing_avatars_skip_known_and_duplicates() {
826 fn missing_avatars_skip_known_and_duplicates() {
823 let mut directory = Directory::default();
827 let mut directory = Directory::default();
824 directory.set_avatar("known", None);
828 directory.set_avatar("known", AvatarState::Missing);
825 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
829 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
826 assert_eq!(wanted, vec!["x", "y"]);
830 assert_eq!(wanted, vec!["x", "y"]);
827 directory.mark_avatars_pending(&wanted);
831 directory.mark_avatars_pending(&wanted);
crates/app-state/src/demo.rs +12 −10
@@ -1,10 +1,10 @@
1 1 use std::collections::HashMap;
2 2 use std::path::PathBuf;
3 use std::sync::{Arc, OnceLock};
3 use std::sync::OnceLock;
4 4 use std::time::Instant;
5 5
6 6 use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7 use gpui_kit::{App, Entity, Image};
7 use gpui_kit::{App, Entity};
8 8 use store::{
9 9 ChannelLayoutRecord, 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),
@@ -2173,8 +2174,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2173 2174 }
2174 2175
2175 2176 fn encode_png(palette: &Palette) -> Vec<u8> {
2176 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
2177 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);
2178 2180 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2179 2181 palette.skin
2180 2182 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
@@ -1,10 +1,10 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::path::PathBuf;
2use std::path::PathBuf;
3use std::sync::{Arc, OnceLock};
3use std::sync::OnceLock;
4use std::time::Instant;
4use std::time::Instant;
5
5
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7use gpui_kit::{App, Entity, Image};
7use gpui_kit::{App, Entity};
8use store::{
8use store::{
9 ChannelLayoutRecord, 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::{
19use crate::activity::{Actor, Entry, Kind};
19use crate::activity::{Actor, Entry, Kind};
20use crate::app_state::{AppState, Selection};
20use crate::app_state::{AppState, Selection};
21use crate::card_actions::{CardAnswer, CardTask};
21use crate::card_actions::{CardAnswer, CardTask};
22use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
22use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
23use crate::demo_gifs;
23use crate::demo_gifs;
24use crate::message_actions::ForwardSource;
24use crate::message_actions::ForwardSource;
25
25
@@ -30,6 +30,7 @@ const DEMO_USER_NAME: &str = "Dana Demo";
30const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
30const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
31const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
31const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
32const PHOTO_SIZE: usize = 48;
32const PHOTO_SIZE: usize = 48;
33const DEMO_PHOTO_SIDE: usize = 240;
33const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
34const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
34const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
35const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
35const STAGING_SIZE: (usize, usize) = (960, 540);
36const STAGING_SIZE: (usize, usize) = (960, 540);
@@ -866,8 +867,8 @@ fn seed_agent_access(store: &Store) {
866 });
867 });
867}
868}
868
869
869fn photo(palette: &Palette) -> Arc<Image> {
870fn 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
873pub fn seed_directory(state: &mut AppState) {
874pub fn seed_directory(state: &mut AppState) {
@@ -932,9 +933,9 @@ pub fn seed_directory(state: &mut AppState) {
932 directory
933 directory
933 .unread_counts
934 .unread_counts
934 .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),
@@ -2173,8 +2174,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2173}
2174}
2174
2175
2175fn encode_png(palette: &Palette) -> Vec<u8> {
2176fn encode_png(palette: &Palette) -> Vec<u8> {
2176 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
2177 let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2177 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);
2178 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2180 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2179 palette.skin
2181 palette.skin
2180 } 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. {
crates/app/src/layout_guard.rs +36 −0
@@ -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",
@@ -963,6 +965,40 @@ mod frames {
963 965 .join("\n")
964 966 );
965 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
966 1002 const TITLE_SEARCH: &str = "shell/title-bar/search";
967 1003 const TITLE_NEIGHBOURS: &[&str] = &[
968 1004 "shell/title-bar/leading",
@@ -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",
@@ -963,6 +965,40 @@ mod frames {
963 .join("\n")
965 .join("\n")
964 );
966 );
965 }
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
966 const TITLE_SEARCH: &str = "shell/title-bar/search";
1002 const TITLE_SEARCH: &str = "shell/title-bar/search";
967 const TITLE_NEIGHBOURS: &[&str] = &[
1003 const TITLE_NEIGHBOURS: &[&str] = &[
968 "shell/title-bar/leading",
1004 "shell/title-bar/leading",
crates/app/src/views/avatar.rs +74 −27
@@ -1,10 +1,12 @@
1 1 use gpui_kit::prelude::FluentBuilder as _;
2 2 use gpui_kit::*;
3 3
4 use std::sync::Arc;
4 5 use std::time::Duration;
5 6
6 7 use gpui_kit::assets::IconName;
7 8
9 use crate::avatar_image::{AvatarPhoto, device_span};
8 10 use crate::card_state::BotIdentity;
9 11 use crate::data::{AvatarState, Directory, Presence, PresenceKind};
10 12 use crate::format;
@@ -55,22 +57,13 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
55 57 .as_deref()
56 58 .and_then(|user_id| directory.avatar(user_id));
57 59 match state {
58 Some(AvatarState::Ready(image)) => {
59 let texture_size = size / crate::avatar_image::visible_fraction();
60 let offset = (size - texture_size) / 2.;
61 div()
62 .relative()
63 .size(px(size))
64 .flex_none()
65 .child(
66 img(ImageSource::Image(image.clone()))
67 .absolute()
68 .left(px(offset))
69 .top(px(offset))
70 .size(px(texture_size)),
71 )
72 .into_any_element()
73 }
60 Some(AvatarState::Ready(photo)) => photo_disc(photo, size, size / 2.),
61 Some(AvatarState::Icon(image)) => img(ImageSource::Image(image.clone()))
62 .size(px(size))
63 .flex_none()
64 .rounded_full()
65 .object_fit(ObjectFit::Cover)
66 .into_any_element(),
74 67 Some(AvatarState::Pending) => {
75 68 initials_circle(&face.name, key, size, true, text_ratio).into_any_element()
76 69 }
@@ -78,6 +71,38 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
78 71 }
79 72 }
80 73
74 fn photo_disc(photo: &Arc<AvatarPhoto>, size: f32, radius: f32) -> AnyElement {
75 let photo = photo.clone();
76 canvas(
77 |_, _, _| {},
78 move |bounds, _, window, cx| {
79 let scale_factor = window.scale_factor();
80 let side = device_span(
81 f32::from(bounds.left()),
82 f32::from(bounds.right()),
83 scale_factor,
84 );
85 let Some(texture) = photo.texture(side) else {
86 return;
87 };
88 if let Some(evicted) = texture.evicted {
89 cx.drop_image(evicted, Some(window));
90 }
91 let _ = window.paint_image(
92 bounds,
93 bounds,
94 Corners::all(px(radius)),
95 texture.image,
96 0,
97 false,
98 );
99 },
100 )
101 .size(px(size))
102 .flex_none()
103 .into_any_element()
104 }
105
81 106 pub fn person_avatar(
82 107 directory: &Directory,
83 108 user_id: Option<&str>,
@@ -105,6 +130,7 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
105 130 .child(
106 131 img(url.clone())
107 132 .size_full()
133 .rounded_full()
108 134 .object_fit(ObjectFit::Cover)
109 135 .with_loading(initials.clone())
110 136 .with_fallback(initials),
@@ -122,7 +148,10 @@ pub fn bot_tile(directory: &Directory, face: &Face, size: f32) -> AnyElement {
122 148 .and_then(|user_id| directory.avatar(user_id));
123 149 let tile = div().size(px(size)).flex_none().rounded(px(radius));
124 150 match image {
125 Some(AvatarState::Ready(image)) => tile
151 Some(AvatarState::Ready(photo)) => tile
152 .child(photo_disc(photo, size, radius))
153 .into_any_element(),
154 Some(AvatarState::Icon(image)) => tile
126 155 .child(
127 156 img(ImageSource::Image(image.clone()))
128 157 .size_full()
@@ -143,8 +172,7 @@ pub fn presence_size(avatar_size: f32) -> f32 {
143 172 .clamp(PRESENCE_MIN, PRESENCE_MAX)
144 173 }
145 174
146 pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<Div> {
147 let outer = presence_size(avatar_size);
175 fn presence_badge(kind: PresenceKind, ring: Hsla, outer: f32) -> Option<Div> {
148 176 let inner = outer - 2. * PRESENCE_RING;
149 177 let fill = match kind {
150 178 PresenceKind::Available => theme::green(),
@@ -166,7 +194,9 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
166 194 center.child(div().w(px(inner - 4.)).h(px(2.)).rounded(px(1.)).bg(ring))
167 195 }
168 196 PresenceKind::Offline => center.border(px(1.5)).border_color(theme::text_muted()),
169 PresenceKind::OutOfOffice => center.child(icon(IconName::ArrowLeft, inner - 2., theme::white())),
197 PresenceKind::OutOfOffice => {
198 center.child(icon(IconName::ArrowLeft, inner - 2., theme::white()))
199 }
170 200 _ => center,
171 201 };
172 202 Some(
@@ -181,8 +211,7 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
181 211 )
182 212 }
183 213
184 fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
185 let outer = presence_size(avatar_size);
214 fn presence_spinner(ring: Hsla, outer: f32) -> Div {
186 215 let spinner = icon(IconName::Loader, outer - PRESENCE_RING, theme::text_muted())
187 216 .with_animation(
188 217 "presence-spinner",
@@ -200,12 +229,22 @@ fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
200 229 }
201 230
202 231 pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {
232 with_presence_badge(avatar, presence, size, presence_size(size), ring)
233 }
234
235 pub fn with_presence_badge(
236 avatar: AnyElement,
237 presence: Presence,
238 size: f32,
239 badge: f32,
240 ring: Hsla,
241 ) -> Div {
203 242 let wrapper = div().relative().size(px(size)).flex_none().child(avatar);
204 243 match presence {
205 Presence::Loading => wrapper.child(presence_spinner(ring, size)),
206 Presence::Live(kind) => wrapper.children(presence_dot(kind, ring, size)),
244 Presence::Loading => wrapper.child(presence_spinner(ring, badge)),
245 Presence::Live(kind) => wrapper.children(presence_badge(kind, ring, badge)),
207 246 Presence::Cached(kind) => wrapper.children(
208 presence_dot(kind, ring, size).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
247 presence_badge(kind, ring, badge).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
209 248 ),
210 249 }
211 250 }
@@ -222,7 +261,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
222 261 .flex()
223 262 .items_center()
224 263 .justify_center()
225 .child(icon(IconName::Calendar, (size * MEETING_ICON_RATIO).round(), theme::white()))
264 .child(icon(
265 IconName::Calendar,
266 (size * MEETING_ICON_RATIO).round(),
267 theme::white(),
268 ))
226 269 .into_any_element(),
227 270 AvatarSpec::Muted => div()
228 271 .size(px(size))
@@ -232,7 +275,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
232 275 .flex()
233 276 .items_center()
234 277 .justify_center()
235 .child(icon(IconName::BellOff, (size * MEETING_ICON_RATIO).round(), theme::text_muted()))
278 .child(icon(
279 IconName::BellOff,
280 (size * MEETING_ICON_RATIO).round(),
281 theme::text_muted(),
282 ))
236 283 .into_any_element(),
237 284 AvatarSpec::Pair(first, second) => {
238 285 let small = (size * PAIR_RATIO).round();
@@ -1,10 +1,12 @@
1use gpui_kit::prelude::FluentBuilder as _;
1use gpui_kit::prelude::FluentBuilder as _;
2use gpui_kit::*;
2use gpui_kit::*;
3
3
4use std::sync::Arc;
4use std::time::Duration;
5use std::time::Duration;
5
6
6use gpui_kit::assets::IconName;
7use gpui_kit::assets::IconName;
7
8
9use crate::avatar_image::{AvatarPhoto, device_span};
8use crate::card_state::BotIdentity;
10use crate::card_state::BotIdentity;
9use crate::data::{AvatarState, Directory, Presence, PresenceKind};
11use crate::data::{AvatarState, Directory, Presence, PresenceKind};
10use crate::format;
12use crate::format;
@@ -55,22 +57,13 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
55 .as_deref()
57 .as_deref()
56 .and_then(|user_id| directory.avatar(user_id));
58 .and_then(|user_id| directory.avatar(user_id));
57 match state {
59 match state {
58 Some(AvatarState::Ready(image)) => {
60 Some(AvatarState::Ready(photo)) => photo_disc(photo, size, size / 2.),
59 let texture_size = size / crate::avatar_image::visible_fraction();
61 Some(AvatarState::Icon(image)) => img(ImageSource::Image(image.clone()))
60 let offset = (size - texture_size) / 2.;
62 .size(px(size))
61 div()
63 .flex_none()
62 .relative()
64 .rounded_full()
63 .size(px(size))
65 .object_fit(ObjectFit::Cover)
64 .flex_none()
66 .into_any_element(),
65 .child(
66 img(ImageSource::Image(image.clone()))
67 .absolute()
68 .left(px(offset))
69 .top(px(offset))
70 .size(px(texture_size)),
71 )
72 .into_any_element()
73 }
74 Some(AvatarState::Pending) => {
67 Some(AvatarState::Pending) => {
75 initials_circle(&face.name, key, size, true, text_ratio).into_any_element()
68 initials_circle(&face.name, key, size, true, text_ratio).into_any_element()
76 }
69 }
@@ -78,6 +71,38 @@ fn face_circle(directory: &Directory, face: &Face, size: f32, text_ratio: f32) -
78 }
71 }
79}
72}
80
73
74fn photo_disc(photo: &Arc<AvatarPhoto>, size: f32, radius: f32) -> AnyElement {
75 let photo = photo.clone();
76 canvas(
77 |_, _, _| {},
78 move |bounds, _, window, cx| {
79 let scale_factor = window.scale_factor();
80 let side = device_span(
81 f32::from(bounds.left()),
82 f32::from(bounds.right()),
83 scale_factor,
84 );
85 let Some(texture) = photo.texture(side) else {
86 return;
87 };
88 if let Some(evicted) = texture.evicted {
89 cx.drop_image(evicted, Some(window));
90 }
91 let _ = window.paint_image(
92 bounds,
93 bounds,
94 Corners::all(px(radius)),
95 texture.image,
96 0,
97 false,
98 );
99 },
100 )
101 .size(px(size))
102 .flex_none()
103 .into_any_element()
104}
105
81pub fn person_avatar(
106pub fn person_avatar(
82 directory: &Directory,
107 directory: &Directory,
83 user_id: Option<&str>,
108 user_id: Option<&str>,
@@ -105,6 +130,7 @@ pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
105 .child(
130 .child(
106 img(url.clone())
131 img(url.clone())
107 .size_full()
132 .size_full()
133 .rounded_full()
108 .object_fit(ObjectFit::Cover)
134 .object_fit(ObjectFit::Cover)
109 .with_loading(initials.clone())
135 .with_loading(initials.clone())
110 .with_fallback(initials),
136 .with_fallback(initials),
@@ -122,7 +148,10 @@ pub fn bot_tile(directory: &Directory, face: &Face, size: f32) -> AnyElement {
122 .and_then(|user_id| directory.avatar(user_id));
148 .and_then(|user_id| directory.avatar(user_id));
123 let tile = div().size(px(size)).flex_none().rounded(px(radius));
149 let tile = div().size(px(size)).flex_none().rounded(px(radius));
124 match image {
150 match image {
125 Some(AvatarState::Ready(image)) => tile
151 Some(AvatarState::Ready(photo)) => tile
152 .child(photo_disc(photo, size, radius))
153 .into_any_element(),
154 Some(AvatarState::Icon(image)) => tile
126 .child(
155 .child(
127 img(ImageSource::Image(image.clone()))
156 img(ImageSource::Image(image.clone()))
128 .size_full()
157 .size_full()
@@ -143,8 +172,7 @@ pub fn presence_size(avatar_size: f32) -> f32 {
143 .clamp(PRESENCE_MIN, PRESENCE_MAX)
172 .clamp(PRESENCE_MIN, PRESENCE_MAX)
144}
173}
145
174
146pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<Div> {
175fn presence_badge(kind: PresenceKind, ring: Hsla, outer: f32) -> Option<Div> {
147 let outer = presence_size(avatar_size);
148 let inner = outer - 2. * PRESENCE_RING;
176 let inner = outer - 2. * PRESENCE_RING;
149 let fill = match kind {
177 let fill = match kind {
150 PresenceKind::Available => theme::green(),
178 PresenceKind::Available => theme::green(),
@@ -166,7 +194,9 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
166 center.child(div().w(px(inner - 4.)).h(px(2.)).rounded(px(1.)).bg(ring))
194 center.child(div().w(px(inner - 4.)).h(px(2.)).rounded(px(1.)).bg(ring))
167 }
195 }
168 PresenceKind::Offline => center.border(px(1.5)).border_color(theme::text_muted()),
196 PresenceKind::Offline => center.border(px(1.5)).border_color(theme::text_muted()),
169 PresenceKind::OutOfOffice => center.child(icon(IconName::ArrowLeft, inner - 2., theme::white())),
197 PresenceKind::OutOfOffice => {
198 center.child(icon(IconName::ArrowLeft, inner - 2., theme::white()))
199 }
170 _ => center,
200 _ => center,
171 };
201 };
172 Some(
202 Some(
@@ -181,8 +211,7 @@ pub fn presence_dot(kind: PresenceKind, ring: Hsla, avatar_size: f32) -> Option<
181 )
211 )
182}
212}
183
213
184fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
214fn presence_spinner(ring: Hsla, outer: f32) -> Div {
185 let outer = presence_size(avatar_size);
186 let spinner = icon(IconName::Loader, outer - PRESENCE_RING, theme::text_muted())
215 let spinner = icon(IconName::Loader, outer - PRESENCE_RING, theme::text_muted())
187 .with_animation(
216 .with_animation(
188 "presence-spinner",
217 "presence-spinner",
@@ -200,12 +229,22 @@ fn presence_spinner(ring: Hsla, avatar_size: f32) -> Div {
200}
229}
201
230
202pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {
231pub fn with_presence(avatar: AnyElement, presence: Presence, size: f32, ring: Hsla) -> Div {
232 with_presence_badge(avatar, presence, size, presence_size(size), ring)
233}
234
235pub fn with_presence_badge(
236 avatar: AnyElement,
237 presence: Presence,
238 size: f32,
239 badge: f32,
240 ring: Hsla,
241) -> Div {
203 let wrapper = div().relative().size(px(size)).flex_none().child(avatar);
242 let wrapper = div().relative().size(px(size)).flex_none().child(avatar);
204 match presence {
243 match presence {
205 Presence::Loading => wrapper.child(presence_spinner(ring, size)),
244 Presence::Loading => wrapper.child(presence_spinner(ring, badge)),
206 Presence::Live(kind) => wrapper.children(presence_dot(kind, ring, size)),
245 Presence::Live(kind) => wrapper.children(presence_badge(kind, ring, badge)),
207 Presence::Cached(kind) => wrapper.children(
246 Presence::Cached(kind) => wrapper.children(
208 presence_dot(kind, ring, size).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
247 presence_badge(kind, ring, badge).map(|dot| dot.opacity(CACHED_PRESENCE_OPACITY)),
209 ),
248 ),
210 }
249 }
211}
250}
@@ -222,7 +261,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
222 .flex()
261 .flex()
223 .items_center()
262 .items_center()
224 .justify_center()
263 .justify_center()
225 .child(icon(IconName::Calendar, (size * MEETING_ICON_RATIO).round(), theme::white()))
264 .child(icon(
265 IconName::Calendar,
266 (size * MEETING_ICON_RATIO).round(),
267 theme::white(),
268 ))
226 .into_any_element(),
269 .into_any_element(),
227 AvatarSpec::Muted => div()
270 AvatarSpec::Muted => div()
228 .size(px(size))
271 .size(px(size))
@@ -232,7 +275,11 @@ pub fn spec_avatar(directory: &Directory, spec: &AvatarSpec, size: f32, ring: Hs
232 .flex()
275 .flex()
233 .items_center()
276 .items_center()
234 .justify_center()
277 .justify_center()
235 .child(icon(IconName::BellOff, (size * MEETING_ICON_RATIO).round(), theme::text_muted()))
278 .child(icon(
279 IconName::BellOff,
280 (size * MEETING_ICON_RATIO).round(),
281 theme::text_muted(),
282 ))
236 .into_any_element(),
283 .into_any_element(),
237 AvatarSpec::Pair(first, second) => {
284 AvatarSpec::Pair(first, second) => {
238 let small = (size * PAIR_RATIO).round();
285 let small = (size * PAIR_RATIO).round();
crates/app/src/views/status_menu.rs +25 −29
@@ -10,23 +10,26 @@ use gpui_kit::component::{
10 10 use gpui_kit::*;
11 11 use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12 12
13 use super::avatar::{person_avatar, with_presence};
13 use super::avatar::{person_avatar, with_presence, with_presence_badge};
14 14 use super::widgets::{icon, symbol};
15 15 use crate::app_state::AppState;
16 16 use crate::data::{Person, PresenceKind};
17 use crate::settings_section::SettingsSection;
18 17 use crate::own_status::{
19 18 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 19 presence_kind_for, state_summary, work_location_label,
21 20 };
21 use crate::settings_section::SettingsSection;
22 22 use crate::theme;
23 23
24 24 pub const MENU_WIDTH: f32 = 250.;
25 const TITLE_AVATAR_SIZE: f32 = 26.;
25 pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
26 pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
27 const TITLE_PRESENCE_SIZE: f32 = 14.;
26 28 const HEADER_AVATAR_SIZE: f32 = 40.;
27 const RING_WIDTH: f32 = 2.;
28 29 const PRESENCE_OVERHANG: f32 = 2.;
29 const OWN_STATUS_BUTTON_SIZE: f32 = TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH + PRESENCE_OVERHANG);
30 const TITLE_BUTTON_INSET: f32 = 2.;
31 const OWN_STATUS_BUTTON_SIZE: f32 =
32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
30 33 const MENU_ICON_SIZE: f32 = 14.;
31 34 const ICON_COLUMN: f32 = 16.;
32 35 const HEADER_INSET: f32 = 24.;
@@ -44,7 +47,6 @@ struct MenuContext {
44 47 pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
45 48 let person = state.directory.me.clone()?;
46 49 let presence = state.directory.presence_of(&person.user_id);
47 let open = state.status_menu_open;
48 50 let summary = state_summary(&state.own_status, state.own_presence_kind(), &Local::now());
49 51 let context = MenuContext {
50 52 app: app.clone(),
@@ -54,28 +56,19 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
54 56 summary,
55 57 person: person.clone(),
56 58 };
57 let ringed = div()
58 .p(px(1.))
59 .rounded_full()
60 .border(px(RING_WIDTH))
61 .border_color(if open {
62 theme::accent()
63 } else {
64 transparent_black()
65 })
66 .child(person_avatar(
59 let avatar = with_presence_badge(
60 person_avatar(
67 61 &state.directory,
68 62 Some(&person.user_id),
69 63 &person.display_name,
70 64 TITLE_AVATAR_SIZE,
71 ))
72 .into_any_element();
73 let ringed = with_presence(
74 ringed,
65 ),
75 66 presence,
76 TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH),
67 TITLE_AVATAR_SIZE,
68 TITLE_PRESENCE_SIZE,
77 69 theme::background(),
78 );
70 )
71 .debug_selector(|| OWN_AVATAR_DISC.into());
79 72 let toggle = app.clone();
80 73 Some(
81 74 div()
@@ -92,7 +85,7 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
92 85 div()
93 86 .debug_selector(|| "shell/title-bar/own-status/avatar".into())
94 87 .p(px(PRESENCE_OVERHANG))
95 .child(ringed),
88 .child(avatar),
96 89 )
97 90 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
98 91 status_menu(popup, window, cx, &context)
@@ -231,16 +224,18 @@ fn status_menu(
231 224 PopupMenuItem::new("Chat list")
232 225 .icon(menu_icon(IconName::LayoutList))
233 226 .on_click(move |_, _, cx| {
234 chat_list_app
235 .update(cx, |state, cx| state.open_settings(SettingsSection::Chats, cx));
227 chat_list_app.update(cx, |state, cx| {
228 state.open_settings(SettingsSection::Chats, cx)
229 });
236 230 }),
237 231 )
238 232 .item(
239 233 PopupMenuItem::new("Translation")
240 234 .icon(menu_icon(IconName::Languages))
241 235 .on_click(move |_, _, cx| {
242 translation_app
243 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
236 translation_app.update(cx, |state, cx| {
237 state.open_settings(SettingsSection::General, cx)
238 });
244 239 }),
245 240 )
246 241 .item(
@@ -263,8 +258,9 @@ fn status_menu(
263 258 PopupMenuItem::new("Settings")
264 259 .icon(menu_icon(IconName::Settings))
265 260 .on_click(move |_, _, cx| {
266 general_app
267 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
261 general_app.update(cx, |state, cx| {
262 state.open_settings(SettingsSection::General, cx)
263 });
268 264 }),
269 265 )
270 266 .item(PopupMenuItem::element(move |_, cx| {
@@ -10,23 +10,26 @@ use gpui_kit::component::{
10use gpui_kit::*;
10use gpui_kit::*;
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12
12
13use super::avatar::{person_avatar, with_presence};
13use super::avatar::{person_avatar, with_presence, with_presence_badge};
14use super::widgets::{icon, symbol};
14use super::widgets::{icon, symbol};
15use crate::app_state::AppState;
15use crate::app_state::AppState;
16use crate::data::{Person, PresenceKind};
16use crate::data::{Person, PresenceKind};
17use crate::settings_section::SettingsSection;
18use crate::own_status::{
17use crate::own_status::{
19 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
18 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 presence_kind_for, state_summary, work_location_label,
19 presence_kind_for, state_summary, work_location_label,
21};
20};
21use crate::settings_section::SettingsSection;
22use crate::theme;
22use crate::theme;
23
23
24pub const MENU_WIDTH: f32 = 250.;
24pub const MENU_WIDTH: f32 = 250.;
25const TITLE_AVATAR_SIZE: f32 = 26.;
25pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
26pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
27const TITLE_PRESENCE_SIZE: f32 = 14.;
26const HEADER_AVATAR_SIZE: f32 = 40.;
28const HEADER_AVATAR_SIZE: f32 = 40.;
27const RING_WIDTH: f32 = 2.;
28const PRESENCE_OVERHANG: f32 = 2.;
29const PRESENCE_OVERHANG: f32 = 2.;
29const OWN_STATUS_BUTTON_SIZE: f32 = TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH + PRESENCE_OVERHANG);
30const TITLE_BUTTON_INSET: f32 = 2.;
31const OWN_STATUS_BUTTON_SIZE: f32 =
32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
30const MENU_ICON_SIZE: f32 = 14.;
33const MENU_ICON_SIZE: f32 = 14.;
31const ICON_COLUMN: f32 = 16.;
34const ICON_COLUMN: f32 = 16.;
32const HEADER_INSET: f32 = 24.;
35const HEADER_INSET: f32 = 24.;
@@ -44,7 +47,6 @@ struct MenuContext {
44pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
47pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
45 let person = state.directory.me.clone()?;
48 let person = state.directory.me.clone()?;
46 let presence = state.directory.presence_of(&person.user_id);
49 let presence = state.directory.presence_of(&person.user_id);
47 let open = state.status_menu_open;
48 let summary = state_summary(&state.own_status, state.own_presence_kind(), &Local::now());
50 let summary = state_summary(&state.own_status, state.own_presence_kind(), &Local::now());
49 let context = MenuContext {
51 let context = MenuContext {
50 app: app.clone(),
52 app: app.clone(),
@@ -54,28 +56,19 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
54 summary,
56 summary,
55 person: person.clone(),
57 person: person.clone(),
56 };
58 };
57 let ringed = div()
59 let avatar = with_presence_badge(
58 .p(px(1.))
60 person_avatar(
59 .rounded_full()
60 .border(px(RING_WIDTH))
61 .border_color(if open {
62 theme::accent()
63 } else {
64 transparent_black()
65 })
66 .child(person_avatar(
67 &state.directory,
61 &state.directory,
68 Some(&person.user_id),
62 Some(&person.user_id),
69 &person.display_name,
63 &person.display_name,
70 TITLE_AVATAR_SIZE,
64 TITLE_AVATAR_SIZE,
71 ))
65 ),
72 .into_any_element();
73 let ringed = with_presence(
74 ringed,
75 presence,
66 presence,
76 TITLE_AVATAR_SIZE + 2. * (1. + RING_WIDTH),
67 TITLE_AVATAR_SIZE,
68 TITLE_PRESENCE_SIZE,
77 theme::background(),
69 theme::background(),
78 );
70 )
71 .debug_selector(|| OWN_AVATAR_DISC.into());
79 let toggle = app.clone();
72 let toggle = app.clone();
80 Some(
73 Some(
81 div()
74 div()
@@ -92,7 +85,7 @@ pub fn own_status_button(app: &Entity<AppState>, state: &AppState) -> Option<Any
92 div()
85 div()
93 .debug_selector(|| "shell/title-bar/own-status/avatar".into())
86 .debug_selector(|| "shell/title-bar/own-status/avatar".into())
94 .p(px(PRESENCE_OVERHANG))
87 .p(px(PRESENCE_OVERHANG))
95 .child(ringed),
88 .child(avatar),
96 )
89 )
97 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
90 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
98 status_menu(popup, window, cx, &context)
91 status_menu(popup, window, cx, &context)
@@ -231,16 +224,18 @@ fn status_menu(
231 PopupMenuItem::new("Chat list")
224 PopupMenuItem::new("Chat list")
232 .icon(menu_icon(IconName::LayoutList))
225 .icon(menu_icon(IconName::LayoutList))
233 .on_click(move |_, _, cx| {
226 .on_click(move |_, _, cx| {
234 chat_list_app
227 chat_list_app.update(cx, |state, cx| {
235 .update(cx, |state, cx| state.open_settings(SettingsSection::Chats, cx));
228 state.open_settings(SettingsSection::Chats, cx)
229 });
236 }),
230 }),
237 )
231 )
238 .item(
232 .item(
239 PopupMenuItem::new("Translation")
233 PopupMenuItem::new("Translation")
240 .icon(menu_icon(IconName::Languages))
234 .icon(menu_icon(IconName::Languages))
241 .on_click(move |_, _, cx| {
235 .on_click(move |_, _, cx| {
242 translation_app
236 translation_app.update(cx, |state, cx| {
243 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
237 state.open_settings(SettingsSection::General, cx)
238 });
244 }),
239 }),
245 )
240 )
246 .item(
241 .item(
@@ -263,8 +258,9 @@ fn status_menu(
263 PopupMenuItem::new("Settings")
258 PopupMenuItem::new("Settings")
264 .icon(menu_icon(IconName::Settings))
259 .icon(menu_icon(IconName::Settings))
265 .on_click(move |_, _, cx| {
260 .on_click(move |_, _, cx| {
266 general_app
261 general_app.update(cx, |state, cx| {
267 .update(cx, |state, cx| state.open_settings(SettingsSection::General, cx));
262 state.open_settings(SettingsSection::General, cx)
263 });
268 }),
264 }),
269 )
265 )
270 .item(PopupMenuItem::element(move |_, cx| {
266 .item(PopupMenuItem::element(move |_, cx| {
crates/core/src/avatars.rs +28 −2
@@ -1,4 +1,4 @@
1 use chrono::{Duration, Utc};
1 use chrono::{DateTime, Duration, Utc};
2 2 use store::{AvatarRecord, is_bot_id};
3 3
4 4 use crate::engine::SyncEngine;
@@ -8,6 +8,14 @@ use crate::remote::Remote;
8 8
9 9 const AVATAR_MAX_AGE_DAYS: i64 = 7;
10 10 const AVATAR_BATCH: usize = 60;
11 const PHOTO_RENDITION_SINCE: &str = "2026-10-17T17:00:00Z";
12
13 fn avatar_cutoff(now: DateTime<Utc>) -> DateTime<Utc> {
14 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
15 .map(|since| since.with_timezone(&Utc))
16 .unwrap_or(DateTime::UNIX_EPOCH);
17 (now - Duration::days(AVATAR_MAX_AGE_DAYS)).max(since)
18 }
11 19
12 20 #[derive(Debug, Clone, PartialEq, Eq)]
13 21 pub struct Avatar {
@@ -25,7 +33,7 @@ impl<R: Remote> SyncEngine<R> {
25 33 }
26 34
27 35 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
28 let cutoff = Utc::now() - Duration::days(AVATAR_MAX_AGE_DAYS);
36 let cutoff = avatar_cutoff(Utc::now());
29 37 let mut unique = user_ids.to_vec();
30 38 unique.sort();
31 39 unique.dedup();
@@ -124,3 +132,21 @@ impl<R: Remote> SyncEngine<R> {
124 132 }
125 133 }
126 134 }
135
136 #[cfg(test)]
137 mod tests {
138 use super::*;
139
140 #[test]
141 fn photos_fetched_before_the_larger_rendition_count_as_stale() {
142 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
143 .unwrap()
144 .with_timezone(&Utc);
145 assert_eq!(avatar_cutoff(since + Duration::days(1)), since);
146 let later = since + Duration::days(30);
147 assert_eq!(
148 avatar_cutoff(later),
149 later - Duration::days(AVATAR_MAX_AGE_DAYS)
150 );
151 }
152 }
@@ -1,4 +1,4 @@
1use chrono::{Duration, Utc};
1use chrono::{DateTime, Duration, Utc};
2use store::{AvatarRecord, is_bot_id};
2use store::{AvatarRecord, is_bot_id};
3
3
4use crate::engine::SyncEngine;
4use crate::engine::SyncEngine;
@@ -8,6 +8,14 @@ use crate::remote::Remote;
8
8
9const AVATAR_MAX_AGE_DAYS: i64 = 7;
9const AVATAR_MAX_AGE_DAYS: i64 = 7;
10const AVATAR_BATCH: usize = 60;
10const AVATAR_BATCH: usize = 60;
11const PHOTO_RENDITION_SINCE: &str = "2026-10-17T17:00:00Z";
12
13fn avatar_cutoff(now: DateTime<Utc>) -> DateTime<Utc> {
14 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
15 .map(|since| since.with_timezone(&Utc))
16 .unwrap_or(DateTime::UNIX_EPOCH);
17 (now - Duration::days(AVATAR_MAX_AGE_DAYS)).max(since)
18}
11
19
12#[derive(Debug, Clone, PartialEq, Eq)]
20#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Avatar {
21pub struct Avatar {
@@ -25,7 +33,7 @@ impl<R: Remote> SyncEngine<R> {
25 }
33 }
26
34
27 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
35 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
28 let cutoff = Utc::now() - Duration::days(AVATAR_MAX_AGE_DAYS);
36 let cutoff = avatar_cutoff(Utc::now());
29 let mut unique = user_ids.to_vec();
37 let mut unique = user_ids.to_vec();
30 unique.sort();
38 unique.sort();
31 unique.dedup();
39 unique.dedup();
@@ -124,3 +132,21 @@ impl<R: Remote> SyncEngine<R> {
124 }
132 }
125 }
133 }
126}
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[test]
141 fn photos_fetched_before_the_larger_rendition_count_as_stale() {
142 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
143 .unwrap()
144 .with_timezone(&Utc);
145 assert_eq!(avatar_cutoff(since + Duration::days(1)), since);
146 let later = since + Duration::days(30);
147 assert_eq!(
148 avatar_cutoff(later),
149 later - Duration::days(AVATAR_MAX_AGE_DAYS)
150 );
151 }
152}
crates/graph/src/people.rs +31 −2
@@ -18,14 +18,43 @@ struct BinaryBody {
18 18 }
19 19
20 20 impl Graph {
21 /// `Ok(None)` for users without a photo (404).
21 /// `Ok(None)` for users without a photo. A 404 on the sized rendition
22 /// also comes back for photos stored smaller in Entra ID, so those ask for the original.
22 23 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
24 let mut photos = self.photo_batch(user_ids, urls::user_photo).await?;
25 let missing: Vec<usize> = photos
26 .iter()
27 .enumerate()
28 .filter(|(_, photo)| matches!(photo, Ok(None)))
29 .map(|(index, _)| index)
30 .collect();
31 if missing.is_empty() {
32 return Ok(photos);
33 }
34 let missing_ids: Vec<String> = missing
35 .iter()
36 .map(|index| user_ids[*index].clone())
37 .collect();
38 let originals = self
39 .photo_batch(&missing_ids, urls::user_photo_original)
40 .await?;
41 for (index, original) in missing.into_iter().zip(originals) {
42 photos[index] = original;
43 }
44 Ok(photos)
45 }
46
47 async fn photo_batch(
48 &self,
49 user_ids: &[String],
50 url: fn(&str) -> String,
51 ) -> Result<Vec<Result<Option<Photo>>>> {
23 52 let scope = Scope::graph(PHOTO_SCOPE);
24 53 let mut photos = Vec::with_capacity(user_ids.len());
25 54 for chunk in user_ids.chunks(BATCH_SIZE) {
26 55 let requests: Vec<Request> = chunk
27 56 .iter()
28 .map(|user_id| Request::binary_get(urls::user_photo(user_id)))
57 .map(|user_id| Request::binary_get(url(user_id)))
29 58 .collect();
30 59 let answers = self.session().batch(&requests, &scope).await?;
31 60 photos.extend(
@@ -18,14 +18,43 @@ struct BinaryBody {
18}
18}
19
19
20impl Graph {
20impl Graph {
21 /// `Ok(None)` for users without a photo (404).
21 /// `Ok(None)` for users without a photo. A 404 on the sized rendition
22 /// also comes back for photos stored smaller in Entra ID, so those ask for the original.
22 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
23 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
24 let mut photos = self.photo_batch(user_ids, urls::user_photo).await?;
25 let missing: Vec<usize> = photos
26 .iter()
27 .enumerate()
28 .filter(|(_, photo)| matches!(photo, Ok(None)))
29 .map(|(index, _)| index)
30 .collect();
31 if missing.is_empty() {
32 return Ok(photos);
33 }
34 let missing_ids: Vec<String> = missing
35 .iter()
36 .map(|index| user_ids[*index].clone())
37 .collect();
38 let originals = self
39 .photo_batch(&missing_ids, urls::user_photo_original)
40 .await?;
41 for (index, original) in missing.into_iter().zip(originals) {
42 photos[index] = original;
43 }
44 Ok(photos)
45 }
46
47 async fn photo_batch(
48 &self,
49 user_ids: &[String],
50 url: fn(&str) -> String,
51 ) -> Result<Vec<Result<Option<Photo>>>> {
23 let scope = Scope::graph(PHOTO_SCOPE);
52 let scope = Scope::graph(PHOTO_SCOPE);
24 let mut photos = Vec::with_capacity(user_ids.len());
53 let mut photos = Vec::with_capacity(user_ids.len());
25 for chunk in user_ids.chunks(BATCH_SIZE) {
54 for chunk in user_ids.chunks(BATCH_SIZE) {
26 let requests: Vec<Request> = chunk
55 let requests: Vec<Request> = chunk
27 .iter()
56 .iter()
28 .map(|user_id| Request::binary_get(urls::user_photo(user_id)))
57 .map(|user_id| Request::binary_get(url(user_id)))
29 .collect();
58 .collect();
30 let answers = self.session().batch(&requests, &scope).await?;
59 let answers = self.session().batch(&requests, &scope).await?;
31 photos.extend(
60 photos.extend(
crates/graph/src/urls.rs +20 −5
@@ -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,\
@@ -201,10 +207,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
201 207 }
202 208
203 209 pub fn shared_drive_item(share_id: &str) -> String {
204 format!(
205 "{GRAPH}/v1.0/shares/{}/driveItem",
206 segment(share_id)
207 )
210 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
208 211 }
209 212
210 213 pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
@@ -342,6 +345,18 @@ mod tests {
342 345
343 346 use super::*;
344 347
348 #[test]
349 fn photos_ask_for_the_240_rendition_then_the_original() {
350 assert_eq!(
351 user_photo("a b"),
352 format!("{GRAPH}/v1.0/users/a%20b/photos/240x240/$value")
353 );
354 assert_eq!(
355 user_photo_original("a b"),
356 format!("{GRAPH}/v1.0/users/a%20b/photo/$value")
357 );
358 }
359
345 360 #[test]
346 361 fn chat_ids_are_path_encoded() {
347 362 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
@@ -16,13 +16,19 @@ pub fn me() -> String {
16 format!("{GRAPH}/v1.0/me?$select=id,displayName,mail,userPrincipalName")
16 format!("{GRAPH}/v1.0/me?$select=id,displayName,mail,userPrincipalName")
17}
17}
18
18
19const PHOTO_SIZE: &str = "240x240";
20
19pub fn user_photo(user_id: &str) -> String {
21pub fn user_photo(user_id: &str) -> String {
20 format!(
22 format!(
21 "{GRAPH}/v1.0/users/{}/photos/48x48/$value",
23 "{GRAPH}/v1.0/users/{}/photos/{PHOTO_SIZE}/$value",
22 segment(user_id)
24 segment(user_id)
23 )
25 )
24}
26}
25
27
28pub fn user_photo_original(user_id: &str) -> String {
29 format!("{GRAPH}/v1.0/users/{}/photo/$value", segment(user_id))
30}
31
26pub fn user_profile(user_id: &str) -> String {
32pub fn user_profile(user_id: &str) -> String {
27 format!(
33 format!(
28 "{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\
34 "{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\
@@ -201,10 +207,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
201}
207}
202
208
203pub fn shared_drive_item(share_id: &str) -> String {
209pub fn shared_drive_item(share_id: &str) -> String {
204 format!(
210 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
205 "{GRAPH}/v1.0/shares/{}/driveItem",
206 segment(share_id)
207 )
208}
211}
209
212
210pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
213pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
@@ -342,6 +345,18 @@ mod tests {
342
345
343 use super::*;
346 use super::*;
344
347
348 #[test]
349 fn photos_ask_for_the_240_rendition_then_the_original() {
350 assert_eq!(
351 user_photo("a b"),
352 format!("{GRAPH}/v1.0/users/a%20b/photos/240x240/$value")
353 );
354 assert_eq!(
355 user_photo_original("a b"),
356 format!("{GRAPH}/v1.0/users/a%20b/photo/$value")
357 );
358 }
359
345 #[test]
360 #[test]
346 fn chat_ids_are_path_encoded() {
361 fn chat_ids_are_path_encoded() {
347 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
362 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");