Merge remote-tracking branch 'origin/main' into feat/share-layout
@@ -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
}@@ -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};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
@@ -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
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
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
553
pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {551
pub 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);@@ -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 @@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),@@ -2173,8 +2174,9 @@ fn staging_pixel(column: usize, row: usize) -> [u8; 3] {2173
}2174
}2174
2175
2175
fn encode_png(palette: &Palette) -> Vec<u8> {2176
fn 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.skin2181
palette.skin2180
} 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. {@@ -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 = 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
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",@@ -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();@@ -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
}@@ -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,\
@@ -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
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,\@@ -201,10 +207,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {201
}207
}202
208
203
pub fn shared_drive_item(share_id: &str) -> String {209
pub 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
210
pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {213
pub 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");