From 5a30a676ee7b20e0bc4a546ef58100843096daf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 01:37:11 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(app):=20the=20project=20autosa?= =?UTF-8?q?ves=20to=20a=20sidecar=20and=20offers=20recovery?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dirty timeline autosaves to .edith.autosave (5s debounce, 60s period, paused during export) via the engine's atomic save. Manual save deletes the sidecar. On open, a newer sidecar appends a recovery offer to the LOADED notice: enter recovers, any other key keeps the file. The real project file is only ever written by manual save. --- crates/app/src/main.rs | 25 +++ crates/app/src/player/actions.rs | 26 +++ crates/app/src/player/cards.rs | 11 +- crates/app/src/player/library.rs | 211 ++++++++++++++++++++++++- crates/app/src/player/timeline_edit.rs | 5 + crates/app/src/render.rs | 13 ++ 6 files changed, 288 insertions(+), 3 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a595d46..e0c6a9e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -385,6 +385,26 @@ struct Player { /// or the one derived beside the media it started as. Saving twice /// overwrites the same file rather than making a second one. project_path: PathBuf, + /// Whether an edit has landed since the sidecar last caught up with it -- + /// set at every edit's own door ([`Player::mark_dirty`]) and cleared once + /// [`Player::autosave_tick`] has written it out. `project_path` itself is + /// never touched here: only [`Player::save_project`] writes the real file. + autosave_dirty: bool, + /// When the dirty flag above was last set, so a tick can debounce: a + /// sidecar write waits until the hand has been off the timeline for a + /// few seconds, rather than chasing every pointer sample of a drag. + autosave_last_edit: Option, + /// When the sidecar was last actually written, so a long unbroken run of + /// edits still gets caught by the periodic safety net rather than being + /// debounced forever. + autosave_last_run: Option, + /// A sidecar found newer than the project it sits beside, offered on the + /// notice bar the moment that project opens ([`Player::install_project`]). + /// The path is the sidecar's own, so accepting it needs nowhere else to + /// look; declining or answering any other key just drops it here -- + /// `project_path` is never touched by either path, only a manual save + /// writes the real file. + recovery_sidecar: Option, /// Which stroke means what, and what every shortcut on screen is called. /// The one place either question is answered. keymap: Keymap, @@ -813,6 +833,10 @@ fn main() { // export beside the picture, a save beside it too. export_path: PathBuf::new(), project_path: PathBuf::new(), + autosave_dirty: false, + autosave_last_edit: None, + autosave_last_run: None, + recovery_sidecar: None, keymap: keymap.clone(), keys_open: false, keys_search: String::new(), @@ -899,6 +923,7 @@ fn main() { // Nothing else takes focus, and without it the key listener // above is never reached. window.focus(&player.read(cx).focus); + player.update(cx, |player, cx| player.start_autosave(cx)); player }, ) diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 78f817b..cf9de91 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -29,6 +29,32 @@ impl Player { // answer with a line about exports. Enable::Hidden(_) => return, } + // The one choke point for every action that changes what a save would + // write: the timeline's clips, the tracks that hold them, the subtitle + // tracks. Marked before the match rather than once per arm below -- + // an autosave a beat early over a refusal (nothing to regroup, say) + // costs nothing a real edit would not have earned anyway, and one list + // here is the whole answer instead of fifteen scattered calls. + if matches!( + action, + ActionId::Paste + | ActionId::Cut + | ActionId::Regroup + | ActionId::Detach + | ActionId::Group + | ActionId::Delete + | ActionId::Lift + | ActionId::Undo + | ActionId::AddVideoLane + | ActionId::RemoveVideoLane + | ActionId::AddAudioLane + | ActionId::RemoveAudioLane + | ActionId::AddSubtitleLane + | ActionId::RemoveSubtitleLane + | ActionId::ImportSubtitles + ) { + self.mark_dirty(); + } match action { ActionId::Play => self.toggle_or_restart(cx), // No session touched at all: the pump reads the flag itself at diff --git a/crates/app/src/player/cards.rs b/crates/app/src/player/cards.rs index 0cc9571..167d598 100644 --- a/crates/app/src/player/cards.rs +++ b/crates/app/src/player/cards.rs @@ -330,6 +330,7 @@ impl Player { false => session.set_color(lane, idx, grade), }; if took { + self.mark_dirty(); self.reset_after_reseek(); } cx.notify(); @@ -482,7 +483,10 @@ impl Player { false => session.set_speed(lane, idx, speed), }; match wrote { - Ok(()) => self.reset_after_reseek(), + Ok(()) => { + self.mark_dirty(); + self.reset_after_reseek(); + } Err(e) => self.notify_user(e.to_string().into()), } } @@ -695,6 +699,10 @@ impl Player { /// ([`engine::PlaybackSession::set_lane_gain_db`]). pub(crate) fn nudge_mix(&mut self, steps: i32, cx: &mut Context) { let lanes = self.mix_lanes(); + if self.session.is_none() { + return; + } + self.mark_dirty(); let Some(session) = self.session.as_mut() else { return; }; @@ -1230,6 +1238,7 @@ impl Player { let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone()); if let Some(session) = &mut self.session { session.set_eq(lane, idx, params); + self.mark_dirty(); } // `set_eq` reseeks inside the engine -- that is what makes the change // audible at once -- and a reseek is what these flags are about. diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 3126edf..6dbaa71 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -3,6 +3,12 @@ use crate::*; +/// How long an edit must sit idle before the sidecar catches up with it. +const AUTOSAVE_DEBOUNCE: Duration = Duration::from_secs(5); +/// The longest a run of edits with no gap between them goes unsaved: the +/// periodic half of "debounced + periodic". +const AUTOSAVE_PERIOD: Duration = Duration::from_secs(60); + impl Player { /// The one way a library row reaches the timeline: the Add button and a row /// dragged onto a lane both come here, so there is a single answer to what @@ -1282,7 +1288,19 @@ impl Player { // reaches the screen the way a seek's does. The old picture is // released by the swap in `pump`, as after any other seek. self.reset_after_reseek(); - format!("LOADED {}{}", file_name(path), silent.unwrap_or_default()) + // Offered right after the load it is about, on top of the + // "LOADED" line rather than instead of it: a person deciding + // whether to recover still gets to see what they *did* open. + self.recovery_sidecar = Self::recovery_offer(path); + let recovery = self.recovery_sidecar.as_ref().map(|_| { + " — a newer autosave was found: enter recovers it, any other key keeps this" + }); + format!( + "LOADED {}{}{}", + file_name(path), + silent.unwrap_or_default(), + recovery.unwrap_or_default() + ) } Err(e) => format!("OPEN FAILED: {e}"), }; @@ -1299,7 +1317,19 @@ impl Player { .as_ref() .map(|session| session.save_project(&self.project_path)); let text = match saved { - Some(Ok(())) => format!("SAVED {}", file_name(&self.project_path)), + Some(Ok(())) => { + // The manual save is now the newest copy of the timeline, so + // the sidecar's job is done -- left behind it would outlive + // its use and, if it later grew younger than a *later* manual + // save through some clock oddity, could be offered as + // "recovery" over a file that already holds everything it did. + if let Some(sidecar) = Self::autosave_path(&self.project_path) { + let _ = std::fs::remove_file(sidecar); + } + self.autosave_dirty = false; + self.autosave_last_edit = None; + format!("SAVED {}", file_name(&self.project_path)) + } Some(Err(e)) => format!("SAVE FAILED: {e}"), None => "NOTHING TO SAVE — open a file first".to_string(), }; @@ -1308,6 +1338,122 @@ impl Player { cx.notify(); } + /// Marks that an edit has landed since the sidecar last caught up, and + /// when: the door every edit that funnels through [`Player::act`] or a + /// timeline gesture calls on its way through. Cheap and safe to call on a + /// refusal too -- an autosave a beat early costs nothing a real edit + /// would not have earned anyway. + pub(crate) fn mark_dirty(&mut self) { + self.autosave_dirty = true; + self.autosave_last_edit = Some(Instant::now()); + } + + /// Where the autosave for `project_path` lives: beside it, named after it. + /// A project with no path yet (nothing saved, nothing opened) has nowhere + /// beside it to write to, so autosave sits out until the first manual + /// save gives it one -- the same file the recovery check on open reads. + fn autosave_path(project_path: &Path) -> Option { + (!project_path.as_os_str().is_empty()).then(|| { + let mut name = project_path.as_os_str().to_owned(); + name.push(".autosave"); + PathBuf::from(name) + }) + } + + /// Answers the recovery notice with `enter`: opens the sidecar + /// [`recovery_sidecar`](Self::recovery_sidecar) named and installs it the + /// same way any other `.edith` lands, but naming the *real* project's + /// path -- so the sidecar's contents replace the timeline in memory while + /// `project_path` keeps pointing at the user's own file, exactly as it did + /// before this call. Nothing here ever writes that file: the next thing to + /// touch it is still only a manual save. + pub(crate) fn recover_from_sidecar(&mut self, cx: &mut Context) { + let Some(sidecar) = self.recovery_sidecar.take() else { + return; + }; + let project_path = self.project_path.clone(); + let opened = PlaybackSession::open_project(&sidecar).map_err(|e| e.to_string()); + self.install_project(&project_path, opened, cx); + // `install_project` just re-ran the same mtime check on its way in and + // found the same sidecar still younger (recovering writes nothing to + // either file) -- offering the recovery it was just asked for right + // back would be the one loop in this feature. + self.recovery_sidecar = None; + } + + /// Whether `project_path` has a sidecar beside it that outdates the file + /// itself: the sidecar exists, the project exists, and the sidecar's mtime + /// is strictly the younger of the two. Pure and file-system-only -- no + /// session, no `Player` -- so [`install_project`](Self::install_project) + /// asks it before anything is loaded and a test can ask it with nothing + /// but two paths on disk. A missing project file (a `.edith` opened for + /// the first time from somewhere else) or a missing/older sidecar both + /// answer `None`: there is nothing here a person did not just open on + /// their own. + fn recovery_offer(project_path: &Path) -> Option { + let sidecar = Self::autosave_path(project_path)?; + let project_mtime = std::fs::metadata(project_path).and_then(|m| m.modified()).ok()?; + let sidecar_mtime = std::fs::metadata(&sidecar).and_then(|m| m.modified()).ok()?; + (sidecar_mtime > project_mtime).then_some(sidecar) + } + + /// Starts the one background loop that ticks the autosave: every five + /// seconds, forever, for as long as the window is up. Cheap to run idle -- + /// a tick with nothing dirty does nothing but reschedule itself -- so one + /// loop for the window's whole life is simpler than arming and disarming + /// a timer around every edit. + pub(crate) fn start_autosave(&mut self, cx: &mut Context) { + cx.spawn(async move |this, cx| { + loop { + cx.background_executor() + .timer(std::time::Duration::from_secs(5)) + .await; + if this.update(cx, |this, cx| this.autosave_tick(cx)).is_err() { + return; + } + } + }) + .detach(); + } + + /// One tick of the loop above. Writes the sidecar when an edit has been + /// idle for [`AUTOSAVE_DEBOUNCE`] (the debounce) or dirty edits have gone + /// unwritten for [`AUTOSAVE_PERIOD`] (the periodic safety net for a run + /// that never goes idle), and never while an export is running -- the two + /// would fight the same disk and the same worker for nothing an export + /// needs. Failure is a stderr line, never a notice: a sidecar losing a + /// write is not something a person can do anything about right now, and a + /// modal over it would be worse than the risk it is guarding against. + fn autosave_tick(&mut self, cx: &mut Context) { + if !self.autosave_dirty || self.exporting().is_some() { + return; + } + let now = Instant::now(); + let idle = self + .autosave_last_edit + .map_or(true, |t| now.duration_since(t) >= AUTOSAVE_DEBOUNCE); + let overdue = self + .autosave_last_run + .map_or(true, |t| now.duration_since(t) >= AUTOSAVE_PERIOD); + if !idle && !overdue { + return; + } + let Some(sidecar) = Self::autosave_path(&self.project_path) else { + return; + }; + let Some(session) = self.session.as_ref() else { + return; + }; + match session.save_project(&sidecar) { + Ok(()) => { + self.autosave_dirty = false; + self.autosave_last_run = Some(now); + } + Err(e) => eprintln!("AUTOSAVE FAILED: {e}"), + } + cx.notify(); + } + /// A new empty track under the ones already there. One undo step in the /// engine, so the stroke that takes back an edit takes back a track too, and /// no reseek: nothing plays differently until something is dropped on it. @@ -1416,6 +1562,7 @@ impl Player { cx.notify(); return; }; + self.mark_dirty(); if moved != lane { self.selected.clear(); self.context_menu = None; @@ -1477,3 +1624,63 @@ impl Player { } } } + +#[cfg(test)] +mod autosave_tests { + use super::*; + + /// The three answers [`Player::recovery_offer`] gives, off nothing but a + /// project file and a sidecar's mtimes: younger sidecar offers it, an + /// older one or none at all offers nothing. Nowhere near a `Player` or a + /// `PlaybackSession` -- the helper reads only the filesystem, which is + /// what makes it askable from a test at all ([`Player`] needs a + /// `gpui::TestAppContext` this repo has no way to build). + #[test] + fn recovery_offer_reads_only_the_newer_sidecar() { + let dir = std::env::temp_dir().join(format!( + "edith-autosave-test-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let project = dir.join("p.edith"); + let sidecar = dir.join("p.edith.autosave"); + + // Neither file exists yet. + assert_eq!(Player::recovery_offer(&project), None); + + std::fs::write(&project, b"project").unwrap(); + // A project with no sidecar beside it: nothing to offer. + assert_eq!(Player::recovery_offer(&project), None); + + std::fs::write(&sidecar, b"sidecar").unwrap(); + let now = std::time::SystemTime::now(); + // Sidecar written after the project (the ordinary case: an edit + // landed since the last manual save) -- offered. + std::fs::File::open(&project) + .unwrap() + .set_modified(now - Duration::from_secs(60)) + .unwrap(); + std::fs::File::open(&sidecar) + .unwrap() + .set_modified(now) + .unwrap(); + assert_eq!(Player::recovery_offer(&project), Some(sidecar.clone())); + + // The sidecar left over from *before* the last manual save (the save + // that answered it, per `Player::save_project`, deletes it -- but an + // older one left by some other means must not be offered as newer + // than a file it predates). + std::fs::File::open(&project) + .unwrap() + .set_modified(now) + .unwrap(); + std::fs::File::open(&sidecar) + .unwrap() + .set_modified(now - Duration::from_secs(60)) + .unwrap(); + assert_eq!(Player::recovery_offer(&project), None); + + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index d82bfd0..4455d02 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -282,6 +282,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); let (Some((start, _)), Some(was)) = ( self.drop_frame(from, idx, x), self.session @@ -367,6 +368,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); self.snap_cue = None; self.ghost = None; let at = self.place_frame(x).0; @@ -450,6 +452,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); self.snap_cue = None; self.ghost = None; let Some(idx) = self.dragged_sub(drag) else { @@ -522,6 +525,7 @@ impl Player { if self.exporting().is_some() { return; } + self.mark_dirty(); let lifted = self .session .as_mut() @@ -1130,6 +1134,7 @@ impl Player { let Some(trim) = self.trim.take() else { return; }; + self.mark_dirty(); // A caption's edge reaches the engine through its own door, at this // timeline's rate. An `Ok` is *not* "something changed" -- an edge that // stopped at a wall it already stood against is `Ok` with no undo step diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index b466311..21bba5c 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -207,6 +207,19 @@ impl Render for Player { { return; } + // The recovery notice is the one bar that reads a key as more + // than "answered": `enter` loads the sidecar it named, and + // every other key declines it -- the way any other key + // dismisses any other notice. Asked before the generic + // dismiss below shares the same door with it, not instead of + // it: this recovers or declines, that pops the bar. + if this.recovery_sidecar.is_some() { + if key == "enter" { + this.recover_from_sidecar(cx); + } else { + this.recovery_sidecar = None; + } + } // Any key answers the message on the bar and brings the next of // them up, whatever it was -- and owes // the repaint itself: a notice no longer keeps the render loop