BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / notify / badge.rs

badge.rs

badge.rs 3.9 KiB Download Raw
1use std::sync::{Arc, OnceLock};
2
3use resvg::{tiny_skia, usvg};
4
5const FILL: &str = "#C42B1C";
6const INK: &str = "#FFFFFF";
7const FONT: &[u8] = include_bytes!("../../../app/assets/fonts/GoogleSansFlex-Bold.ttf");
8const FONT_FAMILY: &str = "Google Sans Flex";
9const SINGLE_GLYPH_SCALE: f32 = 0.68;
10const WIDE_TEXT_SCALE: f32 = 0.58;
11const BASELINE_SHIFT: f32 = 0.36;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Badge {
15 pub text: String,
16}
17
18pub fn badge_for(unread_chats: usize) -> Option<Badge> {
19 if unread_chats == 0 {
20 return None;
21 }
22 let text = if unread_chats >= 10 {
23 "9+".to_owned()
24 } else {
25 unread_chats.to_string()
26 };
27 Some(Badge { text })
28}
29
30fn options() -> &'static usvg::Options<'static> {
31 static OPTIONS: OnceLock<usvg::Options<'static>> = OnceLock::new();
32 OPTIONS.get_or_init(|| {
33 let mut fonts = usvg::fontdb::Database::new();
34 fonts.load_font_data(FONT.to_vec());
35 usvg::Options {
36 font_family: FONT_FAMILY.to_owned(),
37 fontdb: Arc::new(fonts),
38 ..usvg::Options::default()
39 }
40 })
41}
42
43fn badge_svg(text: &str, size: u32) -> String {
44 let size = size as f32;
45 let radius = size / 2.;
46 let font_size = size
47 * if text.chars().count() > 1 {
48 WIDE_TEXT_SCALE
49 } else {
50 SINGLE_GLYPH_SCALE
51 };
52 let baseline = radius + font_size * BASELINE_SHIFT;
53 format!(
54 r#"<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}"><circle cx="{radius}" cy="{radius}" r="{radius}" fill="{FILL}"/><text x="{radius}" y="{baseline}" text-anchor="middle" font-family="{FONT_FAMILY}" font-weight="700" font-size="{font_size}" fill="{INK}">{text}</text></svg>"#
55 )
56}
57
58/// BGRA, premultiplied, top-down, `size` square.
59pub fn render_badge(badge: &Badge, size: u32) -> Vec<u8> {
60 let size = size.max(1);
61 let mut pixmap = tiny_skia::Pixmap::new(size, size).expect("badge size is not zero");
62 if let Ok(tree) = usvg::Tree::from_str(&badge_svg(&badge.text, size), options()) {
63 resvg::render(&tree, tiny_skia::Transform::identity(), &mut pixmap.as_mut());
64 }
65 let mut pixels = pixmap.take();
66 for pixel in pixels.chunks_exact_mut(4) {
67 pixel.swap(0, 2);
68 }
69 pixels
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 #[test]
77 fn no_unread_means_no_badge() {
78 assert_eq!(badge_for(0), None);
79 }
80
81 #[test]
82 fn counts_chats_and_caps_at_nine_plus() {
83 assert_eq!(badge_for(3).unwrap().text, "3");
84 assert_eq!(badge_for(9).unwrap().text, "9");
85 assert_eq!(badge_for(10).unwrap().text, "9+");
86 assert_eq!(badge_for(250).unwrap().text, "9+");
87 }
88
89 fn rendered(text: &str, size: u32) -> Vec<u8> {
90 render_badge(
91 &Badge {
92 text: text.to_owned(),
93 },
94 size,
95 )
96 }
97
98 #[test]
99 fn rendered_badge_has_fill_ink_and_transparent_corner() {
100 let pixels = rendered("3", 32);
101 assert_eq!(pixels.len(), 32 * 32 * 4);
102 assert_eq!(pixels[3], 0);
103 let has = |blue: u8, green: u8, red: u8| {
104 pixels
105 .chunks(4)
106 .any(|pixel| pixel == [blue, green, red, 0xff])
107 };
108 assert!(has(0x1c, 0x2b, 0xc4));
109 assert!(has(0xff, 0xff, 0xff));
110 }
111
112 #[test]
113 fn nine_plus_stays_inside_the_circle() {
114 let size = 32;
115 let pixels = rendered("9+", size);
116 let ink_columns: Vec<u32> = (0..size)
117 .filter(|column| {
118 (0..size).any(|row| {
119 let offset = ((row * size + column) * 4) as usize;
120 pixels[offset..offset + 3] == [0xff, 0xff, 0xff]
121 })
122 })
123 .collect();
124 assert!(ink_columns.len() > 8);
125 assert!(ink_columns.first().is_some_and(|column| *column >= 4));
126 assert!(ink_columns.last().is_some_and(|column| *column <= size - 5));
127 }
128}