BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / background.rs

background.rs

background.rs 10.0 KiB Download Raw
1use std::path::{Path, PathBuf};
2
3use calling::{BackgroundCache, BackgroundChoice, DefaultBackground};
4
5pub const BACKGROUND_META_KEY: &str = "call_background";
6pub const CUSTOM_BACKGROUNDS_META_KEY: &str = "call_background_custom";
7pub const SHOWN_IMAGES: usize = 12;
8const DEFAULT_PREFIX: &str = "default:";
9const FILE_PREFIX: &str = "file:";
10const CACHE_DIR: &str = "call-backgrounds";
11const MAX_CUSTOM: usize = 6;
12
13#[derive(Debug, Clone, PartialEq, Eq, Default)]
14pub enum BackgroundPick {
15 #[default]
16 None,
17 Blur,
18 Default(String),
19 Custom(PathBuf),
20}
21
22impl BackgroundPick {
23 pub fn to_meta(&self) -> String {
24 match self {
25 BackgroundPick::None => "none".to_owned(),
26 BackgroundPick::Blur => "blur".to_owned(),
27 BackgroundPick::Default(id) => format!("{DEFAULT_PREFIX}{id}"),
28 BackgroundPick::Custom(path) => format!("{FILE_PREFIX}{}", path.display()),
29 }
30 }
31
32 pub fn from_meta(value: &str) -> Self {
33 match value {
34 "blur" | "1" => BackgroundPick::Blur,
35 other => match (
36 other.strip_prefix(DEFAULT_PREFIX),
37 other.strip_prefix(FILE_PREFIX),
38 ) {
39 (Some(id), _) if !id.is_empty() => BackgroundPick::Default(id.to_owned()),
40 (_, Some(path)) if !path.is_empty() => BackgroundPick::Custom(PathBuf::from(path)),
41 _ => BackgroundPick::None,
42 },
43 }
44 }
45
46 pub fn is_blur(&self) -> bool {
47 *self == BackgroundPick::Blur
48 }
49}
50
51pub fn load_background(store: &store::Store) -> BackgroundPick {
52 store
53 .meta(BACKGROUND_META_KEY)
54 .ok()
55 .flatten()
56 .or_else(|| store.meta("call_background_blur").ok().flatten())
57 .map_or(BackgroundPick::None, |value| {
58 BackgroundPick::from_meta(&value)
59 })
60}
61
62pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {
63 store
64 .meta(CUSTOM_BACKGROUNDS_META_KEY)
65 .ok()
66 .flatten()
67 .map(|value| {
68 value
69 .lines()
70 .filter(|line| !line.is_empty())
71 .map(PathBuf::from)
72 .collect()
73 })
74 .unwrap_or_default()
75}
76
77pub fn save_custom_backgrounds(store: &store::Store, customs: &[PathBuf]) {
78 let joined: Vec<String> = customs
79 .iter()
80 .map(|path| path.display().to_string())
81 .collect();
82 let _ = store.set_meta(CUSTOM_BACKGROUNDS_META_KEY, &joined.join("\n"));
83}
84
85pub fn default_cache_directory() -> PathBuf {
86 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
87 .map(|directories| directories.data_local_dir().join(CACHE_DIR))
88 .unwrap_or_else(|| PathBuf::from(CACHE_DIR))
89}
90
91pub struct BackgroundLibrary {
92 pub cache: BackgroundCache,
93 pub images: Vec<DefaultBackground>,
94 pub customs: Vec<PathBuf>,
95 pub refreshing: bool,
96}
97
98impl BackgroundLibrary {
99 pub fn new(directory: PathBuf) -> Self {
100 let cache = BackgroundCache::new(directory);
101 let images = cache.cached_catalog();
102 BackgroundLibrary {
103 cache,
104 images,
105 customs: Vec::new(),
106 refreshing: false,
107 }
108 }
109
110 pub fn shown(&self) -> &[DefaultBackground] {
111 &self.images[..self.images.len().min(SHOWN_IMAGES)]
112 }
113
114 pub fn thumbnail(&self, image: &DefaultBackground) -> Option<PathBuf> {
115 Some(self.cache.thumbnail_path(image)).filter(|path| path.exists())
116 }
117
118 pub fn cached_image(&self, id: &str) -> Option<PathBuf> {
119 let image = self.images.iter().find(|image| image.id == id)?;
120 Some(self.cache.image_path(image)).filter(|path| path.exists())
121 }
122
123 pub fn find(&self, id: &str) -> Option<&DefaultBackground> {
124 self.images.iter().find(|image| image.id == id)
125 }
126
127 pub fn add_custom(&mut self, path: PathBuf) {
128 self.customs.retain(|known| *known != path);
129 self.customs.insert(0, path);
130 self.customs.truncate(MAX_CUSTOM);
131 }
132
133 pub fn needs_refresh(&self) -> bool {
134 !self.refreshing
135 && (self.images.is_empty()
136 || self
137 .shown()
138 .iter()
139 .any(|image| self.thumbnail(image).is_none()))
140 }
141
142 pub fn choice_for(&self, pick: &BackgroundPick) -> Option<BackgroundChoice> {
143 match pick {
144 BackgroundPick::None => Some(BackgroundChoice::None),
145 BackgroundPick::Blur => Some(BackgroundChoice::Blur),
146 BackgroundPick::Custom(path) => Some(BackgroundChoice::Image(path.clone())),
147 BackgroundPick::Default(id) => self.cached_image(id).map(BackgroundChoice::Image),
148 }
149 }
150}
151
152const DEMO_NAMES: [&str; SHOWN_IMAGES] = [
153 "Office",
154 "Loft",
155 "Library",
156 "Beach",
157 "Forest",
158 "Sunset",
159 "Studio",
160 "Garden",
161 "Cafe",
162 "Mountains",
163 "Cabin",
164 "City",
165];
166const DEMO_THUMBNAIL: (u32, u32) = (96, 54);
167const DEMO_IMAGE: (u32, u32) = (640, 360);
168
169fn demo_gradient(index: usize, (width, height): (u32, u32)) -> image::RgbaImage {
170 let hue = index as f32 / SHOWN_IMAGES as f32;
171 let channel = |offset: f32, row: f32| {
172 (((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8
173 };
174 image::RgbaImage::from_fn(width, height, |_, row| {
175 let row = row as f32 / height as f32;
176 image::Rgba([
177 channel(0., row),
178 channel(0.33, row),
179 channel(0.66, 1. - row),
180 255,
181 ])
182 })
183}
184
185pub fn demo_library() -> BackgroundLibrary {
186 let directory =
187 std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));
188 let mut library = BackgroundLibrary::new(directory);
189 library.images = DEMO_NAMES
190 .iter()
191 .enumerate()
192 .map(|(index, name)| DefaultBackground {
193 id: format!("demo_{index}"),
194 name: (*name).to_owned(),
195 image_url: format!("https://demo.invalid/images/demo_{index}.png"),
196 thumbnail_url: format!("https://demo.invalid/thumbnails/demo_{index}.png"),
197 })
198 .collect();
199 for (index, image) in library.images.iter().enumerate() {
200 for (path, size) in [
201 (library.cache.thumbnail_path(image), DEMO_THUMBNAIL),
202 (library.cache.image_path(image), DEMO_IMAGE),
203 ] {
204 if let Some(parent) = path.parent() {
205 let _ = std::fs::create_dir_all(parent);
206 }
207 let _ = demo_gradient(index, size).save(path);
208 }
209 }
210 library
211}
212
213pub fn is_image_file(path: &Path) -> bool {
214 path.extension()
215 .and_then(|extension| extension.to_str())
216 .is_some_and(|extension| {
217 ["jpg", "jpeg", "png"]
218 .iter()
219 .any(|known| extension.eq_ignore_ascii_case(known))
220 })
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 #[test]
228 fn a_choice_survives_the_round_trip_through_the_store_value() {
229 for pick in [
230 BackgroundPick::None,
231 BackgroundPick::Blur,
232 BackgroundPick::Default("office_01".into()),
233 BackgroundPick::Custom(PathBuf::from("/home/me/pictures/wall.jpg")),
234 ] {
235 assert_eq!(BackgroundPick::from_meta(&pick.to_meta()), pick);
236 }
237 }
238
239 #[test]
240 fn the_old_blur_switch_and_unknown_values_still_read() {
241 assert_eq!(BackgroundPick::from_meta("1"), BackgroundPick::Blur);
242 assert_eq!(BackgroundPick::from_meta("0"), BackgroundPick::None);
243 assert_eq!(BackgroundPick::from_meta("default:"), BackgroundPick::None);
244 assert_eq!(BackgroundPick::from_meta("nonsense"), BackgroundPick::None);
245 }
246
247 #[test]
248 fn the_store_keeps_the_choice_and_the_own_images() {
249 let store = store::Store::open_in_memory().unwrap();
250 assert_eq!(load_background(&store), BackgroundPick::None);
251 store
252 .set_meta(
253 BACKGROUND_META_KEY,
254 &BackgroundPick::Default("beach".into()).to_meta(),
255 )
256 .unwrap();
257 assert_eq!(
258 load_background(&store),
259 BackgroundPick::Default("beach".into())
260 );
261 save_custom_backgrounds(&store, &[PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);
262 assert_eq!(
263 load_custom_backgrounds(&store),
264 vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]
265 );
266 }
267
268 #[test]
269 fn the_legacy_blur_key_is_read_until_a_new_choice_is_saved() {
270 let store = store::Store::open_in_memory().unwrap();
271 store.set_meta("call_background_blur", "1").unwrap();
272 assert_eq!(load_background(&store), BackgroundPick::Blur);
273 }
274
275 #[test]
276 fn own_images_come_first_without_duplicates_and_stay_few() {
277 let mut library =
278 BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
279 for index in 0..8 {
280 library.add_custom(PathBuf::from(format!("/pictures/{index}.png")));
281 }
282 library.add_custom(PathBuf::from("/pictures/3.png"));
283 assert_eq!(library.customs.len(), MAX_CUSTOM);
284 assert_eq!(library.customs[0], PathBuf::from("/pictures/3.png"));
285 assert_eq!(
286 library
287 .customs
288 .iter()
289 .filter(|path| path.as_path() == Path::new("/pictures/3.png"))
290 .count(),
291 1
292 );
293 }
294
295 #[test]
296 fn a_default_image_is_only_usable_once_it_is_cached() {
297 let library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
298 assert_eq!(
299 library.choice_for(&BackgroundPick::Default("office_01".into())),
300 None
301 );
302 assert_eq!(
303 library.choice_for(&BackgroundPick::Blur),
304 Some(BackgroundChoice::Blur)
305 );
306 assert!(library.needs_refresh());
307 }
308
309 #[test]
310 fn only_pictures_are_accepted_as_own_backgrounds() {
311 assert!(is_image_file(Path::new("/a/b.JPG")));
312 assert!(is_image_file(Path::new("c.png")));
313 assert!(!is_image_file(Path::new("d.gif")));
314 assert!(!is_image_file(Path::new("noextension")));
315 }
316}