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