Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(gpui): prefer edited thumbnails and invalidate their caches

Richie McIlroyd4c54b212520
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 4b2e43048..ff49ca754 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -5681,7 +5681,19 @@ pub fn editor_closed(project_path: &Path, window_id: gpui::WindowId, cx: &mut Ap
.ok()
.flatten();
if let Some(instance) = instance {
- gpui_tokio::Tokio::spawn(cx, async move { instance.dispose().await }).detach();
+ let refresh =
+ gpui_tokio::Tokio::spawn(cx, async move { instance.dispose_with_thumbnail().await });
+ cx.spawn(async move |cx| {
+ if refresh.await.unwrap_or(false) {
+ cx.update(|cx| {
+ refresh_library_after_delete(cx);
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, window, cx| view.refresh_open_library(window, cx))
+ .ok();
+ });
+ }
+ })
+ .detach();
}
restore_after_editor_close(&key, cx);
diff --git a/apps/desktop-gpui/src/library.rs b/apps/desktop-gpui/src/library.rs
index ca5dcd2c3..c45249723 100644
--- a/apps/desktop-gpui/src/library.rs
+++ b/apps/desktop-gpui/src/library.rs
@@ -11,12 +11,6 @@
//! first `RECENT_MEDIA_LIMIT` of each list, merges them, re-sorts by the same
//! key and re-slices.
//!
-//! Thumbnails are pre-baked files inside the bundle, so nothing here decodes
-//! video: a recording's card draws `<bundle>/screenshots/display.jpg` (written
-//! once at recording finish, `recording.rs:3424-3429`), a screenshot's card
-//! draws the bundle's own PNG. All of it is ordinary `std::fs` work, so it is
-//! transcribed here rather than reached for through a Tauri command.
-//!
//! Everything in this module runs on the background executor --
//! [`spawn_decode_pool`] is the one function called from the foreground, and
//! all it does is fan jobs out to that executor. Nothing here touches gpui
@@ -101,6 +95,7 @@ pub struct RecentItem {
/// existence check happens here instead, on the same background pass that
/// already stat'd the directory.
pub thumbnail: Option<PathBuf>,
+ pub thumbnail_version: Option<u128>,
/// `meta.sharing.link` -- Instant Mode cards open this in the browser.
pub sharing: Option<String>,
}
@@ -192,6 +187,7 @@ fn scan_recordings(dir: &Path, out: &mut Vec<RecentItem>) {
clip_count: item.clip_count,
sort_time_millis: item.sort_time_millis,
thumbnail: item.thumbnail,
+ thumbnail_version: item.thumbnail_version,
sharing: item.sharing,
bundle: item.path,
}),
@@ -286,6 +282,7 @@ pub struct RecordingItem {
/// `${path}/screenshots/display.jpg`, existence-checked here rather than
/// left to an `<img onError>`.
pub thumbnail: Option<PathBuf>,
+ pub thumbnail_version: Option<u128>,
}
#[derive(Debug, Clone, PartialEq)]
@@ -354,7 +351,12 @@ fn recording_item(path: PathBuf, meta: RecordingMeta, sort_time_millis: f64) ->
}
};
- let thumbnail = bundle_thumbnail_path(&path);
+ let preview = path.join("screenshots/preview.jpg");
+ let thumbnail = if preview.is_file() {
+ preview
+ } else {
+ bundle_thumbnail_path(&path)
+ };
let upload = crate::upload::queue::status(&path, &meta);
RecordingItem {
upload,
@@ -364,6 +366,7 @@ fn recording_item(path: PathBuf, meta: RecordingMeta, sort_time_millis: f64) ->
pretty_name: meta.pretty_name,
sharing: meta.sharing.map(|sharing| sharing.link),
sort_time_millis,
+ thumbnail_version: source_mtime_nanos(&thumbnail),
thumbnail: thumbnail.is_file().then_some(thumbnail),
path,
}
@@ -774,6 +777,7 @@ fn scan_screenshots(dir: &Path, out: &mut Vec<RecentItem>) {
pretty_name: item.pretty_name,
clip_count: 1,
sort_time_millis: item.sort_time_millis,
+ thumbnail_version: item.thumbnail.as_deref().and_then(source_mtime_nanos),
thumbnail: item.thumbnail,
sharing: None,
}));
@@ -939,7 +943,8 @@ fn fnv1a64(bytes: &[u8]) -> u64 {
/// it -- the extension scans in both apps are over the *screenshot* bundle
/// root and the app-data screenshots dir, neither of which is this.
fn is_bundle_display(path: &Path) -> bool {
- path.file_name().is_some_and(|name| name == "display.jpg")
+ path.file_name()
+ .is_some_and(|name| name == "display.jpg" || name == "preview.jpg")
&& path
.parent()
.and_then(Path::file_name)
@@ -968,7 +973,11 @@ impl CacheSlot {
if is_bundle_display(source) {
return Some(Self {
dir: source.parent()?.to_path_buf(),
- prefix: "thumbnail".to_string(),
+ prefix: if source.file_name().is_some_and(|name| name == "preview.jpg") {
+ "preview-thumbnail".to_string()
+ } else {
+ "thumbnail".to_string()
+ },
mtime,
});
}
@@ -1219,8 +1228,6 @@ pub fn create_screenshot(
Err("Failed to create screenshot".to_string())
}
-/// `<bundle>/screenshots/display.jpg` -- the one path both apps' Recents look
-/// for.
pub fn bundle_thumbnail_path(project_dir: &Path) -> PathBuf {
project_dir.join("screenshots").join("display.jpg")
}
@@ -1389,6 +1396,27 @@ mod tests {
std::fs::remove_dir_all(&root).ok();
}
+ #[test]
+ fn edited_thumbnails_take_precedence_and_change_the_library_revision() {
+ let root = temp_dir("edited-thumbnail");
+ let bundle = write_studio_bundle(&root, "edited", 1);
+ let original = bundle_thumbnail_path(&bundle);
+ std::fs::create_dir_all(original.parent().unwrap()).unwrap();
+ std::fs::write(&original, b"original").unwrap();
+ let before = list_recordings_in(std::slice::from_ref(&root)).remove(0);
+ let preview = bundle.join("screenshots/preview.jpg");
+ std::fs::write(&preview, b"edited preview").unwrap();
+ let after = list_recordings_in(std::slice::from_ref(&root)).remove(0);
+ assert_eq!(before.thumbnail.as_ref(), Some(&original));
+ assert_eq!(after.thumbnail.as_ref(), Some(&preview));
+ assert!(after.thumbnail_version.is_some());
+ assert_ne!(before, after);
+ let recent = recent_media_in(std::slice::from_ref(&root), &root.join("missing"));
+ assert_eq!(recent[0].thumbnail.as_ref(), Some(&preview));
+ assert_eq!(recent[0].thumbnail_version, after.thumbnail_version);
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
// -- The settings page's listing ------------------------------------
/// A bundle with a hand-written meta, so a test can spell out exactly the
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index ee1e3bec1..0ae8bfb5f 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -649,6 +649,7 @@ enum LibraryItems {
struct LibraryRow<T> {
item: T,
thumbnail: Option<std::sync::Arc<gpui::RenderImage>>,
+ thumbnail_stale: bool,
}
#[derive(Clone)]
@@ -814,6 +815,7 @@ impl PlanBadge {
struct RecentEntry {
item: RecentItem,
thumbnail: Option<std::sync::Arc<gpui::RenderImage>>,
+ thumbnail_stale: bool,
}
impl MainWindow {
@@ -1512,18 +1514,11 @@ impl MainWindow {
.await;
tracing::info!(count = items.len(), "scanned the recordings library");
- let thumbnails: Vec<(usize, std::path::PathBuf)> = items
- .iter()
- .enumerate()
- .filter_map(|(index, item)| item.thumbnail.clone().map(|path| (index, path)))
- .collect();
-
- if this
- .update_in(cx, |this, window, cx| this.set_recents(items, window, cx))
- .is_err()
- {
+ let Ok(thumbnails) =
+ this.update_in(cx, |this, window, cx| this.set_recents(items, window, cx))
+ else {
return;
- }
+ };
let (_decodes, results) = library::spawn_decode_pool(
cx.background_executor(),
@@ -1544,6 +1539,7 @@ impl MainWindow {
if let Some(old) = entry.thumbnail.replace(image) {
let _ = window.drop_image(old);
}
+ entry.thumbnail_stale = false;
}
cx.notify();
// The main window is not necessarily the active one
@@ -1682,23 +1678,51 @@ impl MainWindow {
/// Install a fresh scan result, releasing the previous thumbnails from the
/// sprite atlas -- the same explicit drop the camera preview does with
/// every frame it replaces.
- fn set_recents(&mut self, items: Vec<RecentItem>, window: &mut Window, cx: &mut Context<Self>) {
- for entry in self.recents.take().into_iter().flatten() {
- if let Some(image) = entry.thumbnail {
- let _ = window.drop_image(image);
- }
- }
+ fn set_recents(
+ &mut self,
+ items: Vec<RecentItem>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Vec<(usize, std::path::PathBuf)> {
+ let mut cached: std::collections::HashMap<_, _> = self
+ .recents
+ .take()
+ .into_iter()
+ .flatten()
+ .map(|entry| (entry.item.bundle.clone(), entry))
+ .collect();
+ let mut pending = Vec::new();
self.recents = Some(
items
.into_iter()
- .map(|item| RecentEntry {
- item,
- thumbnail: None,
+ .enumerate()
+ .map(|(index, item)| {
+ let previous = cached.remove(&item.bundle);
+ let changed = previous.as_ref().is_none_or(|entry| {
+ entry.item.thumbnail != item.thumbnail
+ || entry.item.thumbnail_version != item.thumbnail_version
+ || entry.thumbnail_stale
+ || entry.thumbnail.is_none()
+ });
+ if changed && let Some(path) = item.thumbnail.clone() {
+ pending.push((index, path));
+ }
+ RecentEntry {
+ item,
+ thumbnail: previous.and_then(|entry| entry.thumbnail),
+ thumbnail_stale: changed,
+ }
})
.collect(),
);
+ for (_, entry) in cached {
+ if let Some(image) = entry.thumbnail {
+ let _ = window.drop_image(image);
+ }
+ }
cx.notify();
window.refresh();
+ pending
}
fn toggle_expanded(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -4005,7 +4029,18 @@ impl MainWindow {
window: &mut Window,
cx: &mut Context<Self>,
) -> Vec<(usize, std::path::PathBuf)> {
- self.drop_library_images(window);
+ let mut cached_recordings: std::collections::HashMap<_, _> =
+ match (kind, self.library.take()) {
+ (LibraryKind::Recordings, Some(LibraryItems::Recordings(rows))) => rows
+ .into_iter()
+ .map(|row| (row.item.path.clone(), row))
+ .collect(),
+ (_, previous) => {
+ self.library = previous;
+ self.drop_library_images(window);
+ std::collections::HashMap::new()
+ }
+ };
let mut pending = Vec::new();
self.library = Some(match kind {
LibraryKind::Recordings => LibraryItems::Recordings(
@@ -4014,12 +4049,20 @@ impl MainWindow {
.into_iter()
.enumerate()
.map(|(index, item)| {
- if let Some(path) = item.thumbnail.clone() {
+ let previous = cached_recordings.remove(&item.path);
+ let changed = previous.as_ref().is_none_or(|row| {
+ row.item.thumbnail != item.thumbnail
+ || row.item.thumbnail_version != item.thumbnail_version
+ || row.thumbnail_stale
+ || row.thumbnail.is_none()
+ });
+ if changed && let Some(path) = item.thumbnail.clone() {
pending.push((index, path));
}
LibraryRow {
item,
- thumbnail: None,
+ thumbnail: previous.and_then(|row| row.thumbnail),
+ thumbnail_stale: changed,
}
})
.collect(),
@@ -4036,11 +4079,17 @@ impl MainWindow {
LibraryRow {
item,
thumbnail: None,
+ thumbnail_stale: false,
}
})
.collect(),
),
});
+ for (_, row) in cached_recordings {
+ if let Some(image) = row.thumbnail {
+ let _ = window.drop_image(image);
+ }
+ }
cx.notify();
window.refresh();
pending
@@ -4059,7 +4108,10 @@ impl MainWindow {
(Some(LibraryItems::Recordings(rows)), LibraryKind::Recordings) => rows
.get_mut(index)
.filter(|row| row.item.thumbnail.as_deref() == Some(path.as_path()))
- .and_then(|row| row.thumbnail.replace(image)),
+ .and_then(|row| {
+ row.thumbnail_stale = false;
+ row.thumbnail.replace(image)
+ }),
(Some(LibraryItems::Screenshots(rows)), LibraryKind::Screenshots) => rows
.get_mut(index)
.filter(|row| row.item.thumbnail.as_deref() == Some(path.as_path()))
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index 62a136eba..6772d3a8a 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -368,6 +368,7 @@ impl RecordingsTab {
struct RecordingRow {
item: RecordingItem,
thumbnail: Option<Arc<RenderImage>>,
+ thumbnail_stale: bool,
}
/// Everything the page owns. The Solid route keeps this in a `createQuery` plus
@@ -923,6 +924,7 @@ impl SettingsWindow {
if let Some(old) = row.thumbnail.replace(image) {
let _ = window.drop_image(old);
}
+ row.thumbnail_stale = false;
cx.notify();
// An unfocused window only repaints when asked.
window.refresh();
@@ -948,22 +950,19 @@ impl SettingsWindow {
/// (found on the first fixture run). A row that has gone away releases its
/// image from the sprite atlas, the same explicit drop `set_recents` does.
///
- /// A bundle's `display.jpg` is written once, when the recording finishes,
- /// so keying the cache on the bundle path cannot serve a stale image: the
- /// row that gains a thumbnail mid-poll has none cached and decodes.
fn set_recordings(
&mut self,
items: Vec<RecordingItem>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Vec<(usize, PathBuf)> {
- let mut cached: std::collections::HashMap<PathBuf, Arc<RenderImage>> = self
+ let mut cached: std::collections::HashMap<_, _> = self
.recordings
.items
.take()
.into_iter()
.flatten()
- .filter_map(|row| row.thumbnail.map(|image| (row.item.path, image)))
+ .map(|row| (row.item.path.clone(), row))
.collect();
let mut pending = Vec::new();
@@ -971,18 +970,29 @@ impl SettingsWindow {
.into_iter()
.enumerate()
.map(|(index, item)| {
- let thumbnail = cached.remove(&item.path);
- if thumbnail.is_none()
- && let Some(path) = item.thumbnail.clone()
- {
+ let previous = cached.remove(&item.path);
+ let changed = previous.as_ref().is_none_or(|row| {
+ row.item.thumbnail != item.thumbnail
+ || row.item.thumbnail_version != item.thumbnail_version
+ || row.thumbnail_stale
+ || row.thumbnail.is_none()
+ });
+ let thumbnail = previous.and_then(|row| row.thumbnail);
+ if changed && let Some(path) = item.thumbnail.clone() {
pending.push((index, path));
}
- RecordingRow { item, thumbnail }
+ RecordingRow {
+ item,
+ thumbnail,
+ thumbnail_stale: changed,
+ }
})
.collect();
- for (_, image) in cached {
- let _ = window.drop_image(image);
+ for (_, row) in cached {
+ if let Some(image) = row.thumbnail {
+ let _ = window.drop_image(image);
+ }
}
self.recordings.items = Some(rows);
@@ -4615,6 +4625,7 @@ mod tests {
fn recording(name: &str, mode: RecordingMode) -> RecordingItem {
RecordingItem {
+ thumbnail_version: None,
path: std::path::PathBuf::from(format!("/tmp/{name}.cap")),
mode,
status: crate::library::RecordingStatus::Complete,