Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(editor): keep long-project autosaves from blocking the UI

Akshar Patel540bd205bed0
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index 086f10a0f..39d315249 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -70,6 +70,7 @@ use crate::{
editor_audio::{AudioImportRequest, probe_audio_duration, replace_audio_asset},
editor_edits::{self as edits, DragBounds, Hit, ProjectHistory, SPLIT_SNAP_PX, Selection},
editor_export::ExportUi,
+ project_save::PendingProjectSave,
store::SettingsEnum,
theme::Theme,
ui,
@@ -1226,45 +1227,6 @@ enum Scrub {
/// `PROJECT_SAVE_DEBOUNCE_MS` (`ED/context.ts:185`).
const PROJECT_SAVE_DEBOUNCE: Duration = Duration::from_millis(250);
-/// The debounced `project-config.json` write.
-///
-/// The Tauri editor's `scheduleProjectConfigSave` restarts a 250ms timer on
-/// every store change and `flushProjectConfig` serialises the whole config
-/// through `commands.setProjectConfig` (`ED/context.ts:1186-1252`), which is
-/// `config.write(&project_path)` on the Rust side (`lib.rs:3346-3360`). The
-/// pending value lives behind an `Rc<RefCell<..>>` so the close path -- which
-/// only ever gets an `&mut App` -- can force it out, the same shape the
-/// teleprompter's `onCloseRequested` save uses.
-#[derive(Default)]
-pub struct PendingProjectSave {
- path: Option<PathBuf>,
- config: Option<ProjectConfiguration>,
-}
-
-impl PendingProjectSave {
- /// Drop a scheduled write without performing it -- the reload path after
- /// an import, where the config on disk is newer than the editor's copy.
- pub fn discard(&mut self) {
- self.config = None;
- }
-
- pub fn flush(&mut self) {
- if let Err(error) = self.try_flush() {
- tracing::error!(path = ?self.path, "failed to persist project config: {error}");
- }
- }
-
- pub fn try_flush(&mut self) -> std::io::Result<()> {
- let (Some(path), Some(config)) = (&self.path, &self.config) else {
- return Ok(());
- };
- config.write(path)?;
- tracing::debug!(path = %path.display(), "project config written");
- self.config = None;
- Ok(())
- }
-}
-
/// Which edge -- or the whole box -- a live drag is moving.
#[derive(Clone, Copy, Debug, PartialEq)]
enum DragKind {
@@ -2053,6 +2015,7 @@ impl EditorWindow {
sharing: RecordingMeta::load_for_project(&project_path)
.ok()
.and_then(|meta| meta.sharing),
+ pending_save: Rc::new(RefCell::new(PendingProjectSave::new(project_path.clone()))),
project_path,
state: LoadState::Loading,
preparing_consumer: None,
@@ -2122,7 +2085,6 @@ impl EditorWindow {
has_camera: false,
multiple_clips: false,
recorded_cursor_family: None,
- pending_save: Rc::new(RefCell::new(PendingProjectSave::default())),
save_task: None,
name_input,
hex_inputs,
@@ -2196,7 +2158,7 @@ impl EditorWindow {
/// Hand the close path the pending write, so a `.cap` closed inside the
/// 250ms debounce still lands on disk -- `onCleanup(() => { ...
/// flushProjectConfig() })` (`ED/context.ts:1246-1252`).
- pub fn pending_save(&self) -> Rc<RefCell<PendingProjectSave>> {
+ pub(crate) fn pending_save(&self) -> Rc<RefCell<PendingProjectSave>> {
self.pending_save.clone()
}
@@ -2238,7 +2200,6 @@ impl EditorWindow {
self.has_camera = summary.has_camera;
self.multiple_clips = summary.multiple_clips;
self.recorded_cursor_family = summary.recorded_cursor_family;
- self.pending_save.borrow_mut().path = Some(self.project_path.clone());
// `zoom: zoomOutLimit()` is the store's *initial* value
// (`ED/context.ts:1455`), so it is set the moment a duration exists --
// the on-mount 80px fit then narrows it on the first render that knows
@@ -2525,11 +2486,18 @@ impl EditorWindow {
if !self.project_ready() {
return;
}
- self.pending_save.borrow_mut().config = Some(self.project.clone());
+ self.pending_save.borrow_mut().queue(self.project.clone());
let pending = self.pending_save.clone();
self.save_task = Some(cx.spawn_in(window, async move |_, cx| {
cx.background_executor().timer(PROJECT_SAVE_DEBOUNCE).await;
- pending.borrow_mut().flush();
+ let Some(save) = pending.borrow().snapshot() else {
+ return;
+ };
+ let result = cx
+ .background_executor()
+ .spawn(async move { save.write() })
+ .await;
+ pending.borrow_mut().complete(result);
}));
}
@@ -12479,39 +12447,6 @@ mod tests {
assert!(menu.is_none());
}
- #[test]
- fn failed_predelete_save_keeps_the_pending_edit_for_retry() {
- let root = std::env::temp_dir().join(format!(
- "cap-editor-save-delete-{}",
- crate::store::new_uuid_v4()
- ));
- std::fs::create_dir(&root).unwrap();
- let source = root.join("source.mp4");
- std::fs::write(&source, b"original recording").unwrap();
- let config = ProjectConfiguration {
- aspect_ratio: Some(cap_project::AspectRatio::Square),
- ..Default::default()
- };
- let mut pending = PendingProjectSave {
- path: Some(source.clone()),
- config: Some(config),
- };
- assert!(pending.try_flush().is_err());
- assert!(pending.config.is_some());
- assert_eq!(std::fs::read(&source).unwrap(), b"original recording");
- pending.path = Some(root.clone());
- pending.try_flush().unwrap();
- assert!(pending.config.is_none());
- let saved: ProjectConfiguration =
- serde_json::from_slice(&std::fs::read(root.join("project-config.json")).unwrap())
- .unwrap();
- assert!(matches!(
- saved.aspect_ratio,
- Some(cap_project::AspectRatio::Square)
- ));
- std::fs::remove_dir_all(root).unwrap();
- }
-
#[test]
fn playback_shortcut_is_reserved_for_bare_space_outside_text_fields_and_menus() {
let space = gpui::Keystroke::parse("space").unwrap();
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index 066acdd74..0ee48948c 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -57,6 +57,7 @@ mod picker_benchmark;
mod picker_ui_benchmark;
mod platform;
mod presets;
+mod project_save;
mod recording;
mod screenshot;
mod screenshot_annotations;
diff --git a/apps/desktop-gpui/src/project_save.rs b/apps/desktop-gpui/src/project_save.rs
new file mode 100644
index 000000000..4f41c3d0b
--- /dev/null
+++ b/apps/desktop-gpui/src/project_save.rs
@@ -0,0 +1,201 @@
+use cap_project::ProjectConfiguration;
+use std::{
+ io,
+ path::PathBuf,
+ sync::{Arc, Mutex},
+};
+
+pub(crate) struct PendingProjectSave {
+ path: PathBuf,
+ config: Option<Arc<ProjectConfiguration>>,
+ revision: u64,
+ retired: Arc<Mutex<u64>>,
+}
+
+pub(crate) struct ProjectSave {
+ path: PathBuf,
+ config: Arc<ProjectConfiguration>,
+ revision: u64,
+ retired: Arc<Mutex<u64>>,
+}
+
+impl PendingProjectSave {
+ pub(crate) fn new(path: PathBuf) -> Self {
+ Self {
+ path,
+ config: None,
+ revision: 0,
+ retired: Arc::default(),
+ }
+ }
+
+ pub(crate) fn queue(&mut self, config: ProjectConfiguration) {
+ self.revision += 1;
+ self.config = Some(Arc::new(config));
+ }
+
+ pub(crate) fn snapshot(&self) -> Option<ProjectSave> {
+ Some(ProjectSave {
+ path: self.path.clone(),
+ config: self.config.clone()?,
+ revision: self.revision,
+ retired: self.retired.clone(),
+ })
+ }
+
+ pub(crate) fn complete(&mut self, result: io::Result<u64>) {
+ match result {
+ Ok(revision) if revision == self.revision => self.config = None,
+ Ok(_) => {}
+ Err(error) => {
+ tracing::error!(path = %self.path.display(), "failed to persist project config: {error}");
+ }
+ }
+ }
+
+ pub(crate) fn discard(&mut self) {
+ let mut retired = self.retired.lock().unwrap();
+ self.revision += 1;
+ *retired = self.revision;
+ self.config = None;
+ }
+
+ pub(crate) fn flush(&mut self) {
+ if let Err(error) = self.try_flush() {
+ tracing::error!(path = %self.path.display(), "failed to persist project config: {error}");
+ }
+ }
+
+ pub(crate) fn try_flush(&mut self) -> io::Result<()> {
+ let Some(config) = &self.config else {
+ return Ok(());
+ };
+ let mut retired = self.retired.lock().unwrap();
+ if self.revision > *retired {
+ // Retire queued jobs even if this flush fails before an import.
+ *retired = self.revision;
+ self.revision += 1;
+ config.write(&self.path)?;
+ *retired = self.revision;
+ tracing::debug!(path = %self.path.display(), "project config written");
+ }
+ self.config = None;
+ Ok(())
+ }
+}
+
+impl ProjectSave {
+ pub(crate) fn write(self) -> io::Result<u64> {
+ let mut retired = self.retired.lock().unwrap();
+ // A close or import can flush while this job is queued on the executor.
+ if self.revision <= *retired {
+ return Ok(self.revision);
+ }
+ self.config.write(&self.path)?;
+ *retired = self.revision;
+ tracing::debug!(path = %self.path.display(), "project config written");
+ Ok(self.revision)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::Path;
+
+ fn config(padding: f64) -> ProjectConfiguration {
+ let mut config = ProjectConfiguration::default();
+ config.background.padding = padding;
+ config
+ }
+
+ fn assert_saved(path: &Path, expected: &ProjectConfiguration) {
+ assert_eq!(
+ std::fs::read(path.join("project-config.json")).unwrap(),
+ serde_json::to_vec_pretty(expected).unwrap()
+ );
+ }
+
+ #[test]
+ fn older_completion_keeps_the_new_edit_pending_and_cannot_overwrite_it() {
+ let root = tempfile::tempdir().unwrap();
+ let mut pending = PendingProjectSave::new(root.path().to_owned());
+ pending.queue(config(1.));
+ let older = pending.snapshot().unwrap();
+ let delayed = pending.snapshot().unwrap();
+ pending.queue(config(2.));
+ pending.complete(older.write());
+ assert!(pending.snapshot().is_some());
+ pending.complete(pending.snapshot().unwrap().write());
+ assert!(pending.snapshot().is_none());
+ delayed.write().unwrap();
+ assert_saved(root.path(), &config(2.));
+ }
+
+ #[test]
+ fn flushed_jobs_cannot_overwrite_an_import_committed_before_reload() {
+ let root = tempfile::tempdir().unwrap();
+ let mut pending = PendingProjectSave::new(root.path().to_owned());
+ pending.queue(config(1.));
+ let delayed = pending.snapshot().unwrap();
+ pending.try_flush().unwrap();
+ assert!(pending.snapshot().is_none());
+ config(2.).write(root.path()).unwrap();
+ delayed.write().unwrap();
+ assert_saved(root.path(), &config(2.));
+ }
+
+ #[test]
+ fn discard_invalidates_queued_jobs_and_allows_new_edits() {
+ let root = tempfile::tempdir().unwrap();
+ let mut pending = PendingProjectSave::new(root.path().to_owned());
+ pending.queue(config(1.));
+ let delayed = pending.snapshot().unwrap();
+ pending.discard();
+ config(2.).write(root.path()).unwrap();
+ pending.complete(delayed.write());
+ assert!(pending.snapshot().is_none());
+ assert_saved(root.path(), &config(2.));
+ pending.queue(config(3.));
+ pending.flush();
+ assert_saved(root.path(), &config(3.));
+ }
+
+ #[test]
+ fn failed_save_keeps_the_pending_edit_for_retry() {
+ let root = tempfile::tempdir().unwrap();
+ let source = root.path().join("source.mp4");
+ std::fs::write(&source, b"original recording").unwrap();
+ let mut pending = PendingProjectSave::new(source.clone());
+ pending.queue(config(1.));
+ let result = pending.snapshot().unwrap().write();
+ assert!(result.is_err());
+ pending.complete(result);
+ assert!(pending.try_flush().is_err());
+ assert!(pending.snapshot().is_some());
+ assert_eq!(std::fs::read(&source).unwrap(), b"original recording");
+ pending.path = root.path().to_owned();
+ pending.try_flush().unwrap();
+ assert!(pending.snapshot().is_none());
+ assert_saved(root.path(), &config(1.));
+ }
+
+ #[test]
+ fn failed_flush_retires_queued_jobs_before_an_external_commit() {
+ let root = tempfile::tempdir().unwrap();
+ let bundle = root.path().join("recording.cap");
+ std::fs::write(&bundle, b"not a directory").unwrap();
+ let mut pending = PendingProjectSave::new(bundle.clone());
+ pending.queue(config(1.));
+ let delayed = pending.snapshot().unwrap();
+ assert!(pending.try_flush().is_err());
+ std::fs::remove_file(&bundle).unwrap();
+ std::fs::create_dir(&bundle).unwrap();
+ config(2.).write(&bundle).unwrap();
+ pending.complete(delayed.write());
+ assert_saved(&bundle, &config(2.));
+ assert!(pending.snapshot().is_some());
+ pending.discard();
+ assert!(pending.snapshot().is_none());
+ }
+}