Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(desktop-gpui): build tray thumbnails from the Recents thumbnail cache
Aditya Garud7672f36c52e6
diff --git a/apps/desktop-gpui/src/library.rs b/apps/desktop-gpui/src/library.rsindex cbf1037e3..921cc185f 100644--- a/apps/desktop-gpui/src/library.rs+++ b/apps/desktop-gpui/src/library.rs@@ -978,9 +978,13 @@ impl CacheSlot {}pub fn load(&self) -> Option<Arc<RenderImage>> {+ self.load_rgba().map(rgba_to_render_image)+ }++ fn load_rgba(&self) -> Option<image::RgbaImage> {let bytes = std::fs::read(self.file()).ok()?;let decoded = image::load_from_memory_with_format(&bytes, image::ImageFormat::Jpeg).ok()?;- Some(rgba_to_render_image(decoded.into_rgba8()))+ Some(decoded.into_rgba8())}/// Best effort throughout: a cache that cannot be written (read-only@@ -1060,11 +1064,14 @@ pub fn rgba_to_render_image(mut rgba: image::RgbaImage) -> Arc<RenderImage> {/// smaller than the card is handed over as-is and the element stretches it,/// same as the browser would.pub fn decode_thumbnail(path: &Path) -> Option<Arc<RenderImage>> {+ thumbnail_rgba(path).map(rgba_to_render_image)+}++/// [`decode_thumbnail`]'s pixels before the BGRA swap, through the same cache.+pub fn thumbnail_rgba(path: &Path) -> Option<image::RgbaImage> {let cache = CacheSlot::for_source(path);- if let Some(cache) = &cache- && let Some(image) = cache.load()- {- return Some(image);+ if let Some(rgba) = cache.as_ref().and_then(CacheSlot::load_rgba) {+ return Some(rgba);}let bytes = std::fs::read(path).ok()?;@@ -1102,7 +1109,7 @@ pub fn decode_thumbnail(path: &Path) -> Option<Arc<RenderImage>> {if let Some(cache) = &cache {cache.store(&rgba);}- Some(rgba_to_render_image(rgba))+ Some(rgba)}// ---------------------------------------------------------------------------diff --git a/apps/desktop-gpui/src/tray.rs b/apps/desktop-gpui/src/tray.rsindex 5cff0be65..fe12cd685 100644--- a/apps/desktop-gpui/src/tray.rs+++ b/apps/desktop-gpui/src/tray.rs@@ -173,12 +173,12 @@ pub fn cover_crop_geometry(orig_w: u32, orig_h: u32, size: u32) -> (u32, u32, u3/// `load_thumbnail_data`, ending in a PNG rather than raw RGBA -- muda hands/// its icon to AppKit as a PNG too (`PlatformIcon::to_nsimage`), so this is the-/// same conversion one step earlier.+/// same conversion one step earlier. It starts from the Recents card thumbnail+/// cache instead of decoding the native-resolution original for a 32px icon.fn load_thumbnail_png(path: &Path) -> Option<Vec<u8>> {use image::{GenericImageView, ImageEncoder, RgbaImage, imageops::FilterType};- let bytes = std::fs::read(path).ok()?;- let img = image::load_from_memory(&bytes).ok()?;+ let img = image::DynamicImage::ImageRgba8(library::thumbnail_rgba(path)?);let (orig_w, orig_h) = img.dimensions();if orig_w == 0 || orig_h == 0 {return None;@@ -1160,6 +1160,116 @@ mod tests {assert_eq!(cover_crop_geometry(16, 8, 32), (64, 32, 16, 0));}+ fn temp_root(tag: &str) -> PathBuf {+ let root = std::env::temp_dir().join(format!("cap-tray-{tag}-{}", std::process::id()));+ std::fs::remove_dir_all(&root).ok();+ root+ }++ fn bundle_display_jpg(bundle: &Path, width: u32, height: u32) -> PathBuf {+ let screenshots = bundle.join("screenshots");+ std::fs::create_dir_all(&screenshots).unwrap();+ let display = screenshots.join("display.jpg");+ image::RgbImage::from_fn(width, height, |x, y| {+ let noise = (x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) % 48;+ image::Rgb([+ (x * 255 / width) as u8 ^ noise as u8,+ (y * 255 / height) as u8,+ ((x + y) % 256) as u8,+ ])+ })+ .save_with_format(&display, image::ImageFormat::Jpeg)+ .unwrap();+ display+ }++ fn cached_thumbnails(display: &Path) -> Vec<PathBuf> {+ std::fs::read_dir(display.parent().unwrap())+ .unwrap()+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("thumbnail-"))+ })+ .collect()+ }++ #[test]+ fn previous_thumbnails_reuse_the_recents_cache() {+ let root = temp_root("cache");+ let display = bundle_display_jpg(&root.join("bundle.cap"), 1512, 982);++ let cold = load_thumbnail_png(&display).expect("a thumbnail from the original");+ let cached = cached_thumbnails(&display);+ assert_eq!(cached.len(), 1, "the first scan fills the Recents cache");+ assert_eq!(image::image_dimensions(&cached[0]).unwrap(), (392, 255));++ let warm = load_thumbnail_png(&display).expect("a thumbnail from the cache");+ assert_eq!(+ cached_thumbnails(&display),+ cached,+ "a hit rewrites nothing"+ );+ let [cold, warm] =+ [cold, warm].map(|png| image::load_from_memory(&png).unwrap().into_rgba8());+ assert_eq!(cold.dimensions(), (THUMBNAIL_SIZE, THUMBNAIL_SIZE));+ assert_eq!(warm.dimensions(), cold.dimensions());+ let mean_difference = cold+ .as_raw()+ .iter()+ .zip(warm.as_raw())+ .map(|(cold, warm)| u32::from(cold.abs_diff(*warm)))+ .sum::<u32>()+ / cold.as_raw().len() as u32;+ assert!(+ mean_difference <= 4,+ "warm icon drifted by {mean_difference}"+ );+ std::fs::remove_dir_all(&root).ok();+ }++ #[test]+ #[ignore]+ fn benchmark_previous_thumbnails() {+ use std::time::Instant;++ let root = temp_root("bench");+ let displays: Vec<_> = (0..MAX_PREVIOUS_ITEMS)+ .map(|index| bundle_display_jpg(&root.join(format!("{index}.cap")), 3024, 1964))+ .collect();+ let scan = || {+ let start = Instant::now();+ for display in &displays {+ let png = load_thumbnail_png(display).unwrap();+ assert_eq!(+ image::load_from_memory(&png).unwrap().width(),+ THUMBNAIL_SIZE+ );+ }+ start.elapsed().as_secs_f64() * 1000.0+ };+ let mut cold = Vec::new();+ let mut warm = Vec::new();+ for _ in 0..5 {+ for display in &displays {+ for path in cached_thumbnails(display) {+ std::fs::remove_file(path).unwrap();+ }+ }+ cold.push(scan());+ warm.push(scan());+ }+ cold.sort_by(f64::total_cmp);+ warm.sort_by(f64::total_cmp);+ println!(+ "{{\"items\":{MAX_PREVIOUS_ITEMS},\"source\":\"3024x1964 jpeg\",\"cold_scan_median_ms\":{:.1},\"warm_scan_median_ms\":{:.1}}}",+ cold[2], warm[2]+ );+ std::fs::remove_dir_all(&root).ok();+ }+fn titles(entries: &[Entry]) -> Vec<String> {entries.iter()