forge
Explore
Log in

Don't you dare go Hollow

Autosave sidecar with crash recovery

Browse files at this commit

0646de5ef69247b1ec7f76ac4e34b24b01b5cfb1Ahmet Kaan GümüşParent: 6dae2b45a30a67
  • feat
    • autosave sidecar with crash recovery
Show full message
✨ feat(app): autosave sidecar with crash recovery
crates/app/src/main.rsmodified+25 -0
@@ -385,6 +385,26 @@ struct Player {
385385 /// or the one derived beside the media it started as. Saving twice
386386 /// overwrites the same file rather than making a second one.
387387 project_path: PathBuf,
388+ /// Whether an edit has landed since the sidecar last caught up with it --
389+ /// set at every edit's own door ([`Player::mark_dirty`]) and cleared once
390+ /// [`Player::autosave_tick`] has written it out. `project_path` itself is
391+ /// never touched here: only [`Player::save_project`] writes the real file.
392+ autosave_dirty: bool,
393+ /// When the dirty flag above was last set, so a tick can debounce: a
394+ /// sidecar write waits until the hand has been off the timeline for a
395+ /// few seconds, rather than chasing every pointer sample of a drag.
396+ autosave_last_edit: Option<Instant>,
397+ /// When the sidecar was last actually written, so a long unbroken run of
398+ /// edits still gets caught by the periodic safety net rather than being
399+ /// debounced forever.
400+ autosave_last_run: Option<Instant>,
401+ /// A sidecar found newer than the project it sits beside, offered on the
402+ /// notice bar the moment that project opens ([`Player::install_project`]).
403+ /// The path is the sidecar's own, so accepting it needs nowhere else to
404+ /// look; declining or answering any other key just drops it here --
405+ /// `project_path` is never touched by either path, only a manual save
406+ /// writes the real file.
407+ recovery_sidecar: Option<PathBuf>,
388408 /// Which stroke means what, and what every shortcut on screen is called.
389409 /// The one place either question is answered.
390410 keymap: Keymap,
@@ -813,6 +833,10 @@ fn main() {
813833 // export beside the picture, a save beside it too.
814834 export_path: PathBuf::new(),
815835 project_path: PathBuf::new(),
836+ autosave_dirty: false,
837+ autosave_last_edit: None,
838+ autosave_last_run: None,
839+ recovery_sidecar: None,
816840 keymap: keymap.clone(),
817841 keys_open: false,
818842 keys_search: String::new(),
@@ -899,6 +923,7 @@ fn main() {
899923 // Nothing else takes focus, and without it the key listener
900924 // above is never reached.
901925 window.focus(&player.read(cx).focus);
926+ player.update(cx, |player, cx| player.start_autosave(cx));
902927 player
903928 },
904929 )
crates/app/src/player/actions.rsmodified+26 -0
@@ -29,6 +29,32 @@ impl Player {
2929 // answer with a line about exports.
3030 Enable::Hidden(_) => return,
3131 }
32+ // The one choke point for every action that changes what a save would
33+ // write: the timeline's clips, the tracks that hold them, the subtitle
34+ // tracks. Marked before the match rather than once per arm below --
35+ // an autosave a beat early over a refusal (nothing to regroup, say)
36+ // costs nothing a real edit would not have earned anyway, and one list
37+ // here is the whole answer instead of fifteen scattered calls.
38+ if matches!(
39+ action,
40+ ActionId::Paste
41+ | ActionId::Cut
42+ | ActionId::Regroup
43+ | ActionId::Detach
44+ | ActionId::Group
45+ | ActionId::Delete
46+ | ActionId::Lift
47+ | ActionId::Undo
48+ | ActionId::AddVideoLane
49+ | ActionId::RemoveVideoLane
50+ | ActionId::AddAudioLane
51+ | ActionId::RemoveAudioLane
52+ | ActionId::AddSubtitleLane
53+ | ActionId::RemoveSubtitleLane
54+ | ActionId::ImportSubtitles
55+ ) {
56+ self.mark_dirty();
57+ }
3258 match action {
3359 ActionId::Play => self.toggle_or_restart(cx),
3460 // No session touched at all: the pump reads the flag itself at
crates/app/src/player/cards.rsmodified+10 -1
@@ -330,6 +330,7 @@ impl Player {
330330 false => session.set_color(lane, idx, grade),
331331 };
332332 if took {
333+ self.mark_dirty();
333334 self.reset_after_reseek();
334335 }
335336 cx.notify();
@@ -482,7 +483,10 @@ impl Player {
482483 false => session.set_speed(lane, idx, speed),
483484 };
484485 match wrote {
485- Ok(()) => self.reset_after_reseek(),
486+ Ok(()) => {
487+ self.mark_dirty();
488+ self.reset_after_reseek();
489+ }
486490 Err(e) => self.notify_user(e.to_string().into()),
487491 }
488492 }
@@ -695,6 +699,10 @@ impl Player {
695699 /// ([`engine::PlaybackSession::set_lane_gain_db`]).
696700 pub(crate) fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) {
697701 let lanes = self.mix_lanes();
702+ if self.session.is_none() {
703+ return;
704+ }
705+ self.mark_dirty();
698706 let Some(session) = self.session.as_mut() else {
699707 return;
700708 };
@@ -1230,6 +1238,7 @@ impl Player {
12301238 let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone());
12311239 if let Some(session) = &mut self.session {
12321240 session.set_eq(lane, idx, params);
1241+ self.mark_dirty();
12331242 }
12341243 // `set_eq` reseeks inside the engine -- that is what makes the change
12351244 // audible at once -- and a reseek is what these flags are about.
crates/app/src/player/library.rsmodified+209 -2
@@ -3,6 +3,12 @@
33
44 use crate::*;
55
6+/// How long an edit must sit idle before the sidecar catches up with it.
7+const AUTOSAVE_DEBOUNCE: Duration = Duration::from_secs(5);
8+/// The longest a run of edits with no gap between them goes unsaved: the
9+/// periodic half of "debounced + periodic".
10+const AUTOSAVE_PERIOD: Duration = Duration::from_secs(60);
11+
612 impl Player {
713 /// The one way a library row reaches the timeline: the Add button and a row
814 /// dragged onto a lane both come here, so there is a single answer to what
@@ -1282,7 +1288,19 @@ impl Player {
12821288 // reaches the screen the way a seek's does. The old picture is
12831289 // released by the swap in `pump`, as after any other seek.
12841290 self.reset_after_reseek();
1285- format!("LOADED {}{}", file_name(path), silent.unwrap_or_default())
1291+ // Offered right after the load it is about, on top of the
1292+ // "LOADED" line rather than instead of it: a person deciding
1293+ // whether to recover still gets to see what they *did* open.
1294+ self.recovery_sidecar = Self::recovery_offer(path);
1295+ let recovery = self.recovery_sidecar.as_ref().map(|_| {
1296+ " — a newer autosave was found: enter recovers it, any other key keeps this"
1297+ });
1298+ format!(
1299+ "LOADED {}{}{}",
1300+ file_name(path),
1301+ silent.unwrap_or_default(),
1302+ recovery.unwrap_or_default()
1303+ )
12861304 }
12871305 Err(e) => format!("OPEN FAILED: {e}"),
12881306 };
@@ -1299,7 +1317,19 @@ impl Player {
12991317 .as_ref()
13001318 .map(|session| session.save_project(&self.project_path));
13011319 let text = match saved {
1302- Some(Ok(())) => format!("SAVED {}", file_name(&self.project_path)),
1320+ Some(Ok(())) => {
1321+ // The manual save is now the newest copy of the timeline, so
1322+ // the sidecar's job is done -- left behind it would outlive
1323+ // its use and, if it later grew younger than a *later* manual
1324+ // save through some clock oddity, could be offered as
1325+ // "recovery" over a file that already holds everything it did.
1326+ if let Some(sidecar) = Self::autosave_path(&self.project_path) {
1327+ let _ = std::fs::remove_file(sidecar);
1328+ }
1329+ self.autosave_dirty = false;
1330+ self.autosave_last_edit = None;
1331+ format!("SAVED {}", file_name(&self.project_path))
1332+ }
13031333 Some(Err(e)) => format!("SAVE FAILED: {e}"),
13041334 None => "NOTHING TO SAVE — open a file first".to_string(),
13051335 };
@@ -1308,6 +1338,122 @@ impl Player {
13081338 cx.notify();
13091339 }
13101340
1341+ /// Marks that an edit has landed since the sidecar last caught up, and
1342+ /// when: the door every edit that funnels through [`Player::act`] or a
1343+ /// timeline gesture calls on its way through. Cheap and safe to call on a
1344+ /// refusal too -- an autosave a beat early costs nothing a real edit
1345+ /// would not have earned anyway.
1346+ pub(crate) fn mark_dirty(&mut self) {
1347+ self.autosave_dirty = true;
1348+ self.autosave_last_edit = Some(Instant::now());
1349+ }
1350+
1351+ /// Where the autosave for `project_path` lives: beside it, named after it.
1352+ /// A project with no path yet (nothing saved, nothing opened) has nowhere
1353+ /// beside it to write to, so autosave sits out until the first manual
1354+ /// save gives it one -- the same file the recovery check on open reads.
1355+ fn autosave_path(project_path: &Path) -> Option<PathBuf> {
1356+ (!project_path.as_os_str().is_empty()).then(|| {
1357+ let mut name = project_path.as_os_str().to_owned();
1358+ name.push(".autosave");
1359+ PathBuf::from(name)
1360+ })
1361+ }
1362+
1363+ /// Answers the recovery notice with `enter`: opens the sidecar
1364+ /// [`recovery_sidecar`](Self::recovery_sidecar) named and installs it the
1365+ /// same way any other `.edith` lands, but naming the *real* project's
1366+ /// path -- so the sidecar's contents replace the timeline in memory while
1367+ /// `project_path` keeps pointing at the user's own file, exactly as it did
1368+ /// before this call. Nothing here ever writes that file: the next thing to
1369+ /// touch it is still only a manual save.
1370+ pub(crate) fn recover_from_sidecar(&mut self, cx: &mut Context<Self>) {
1371+ let Some(sidecar) = self.recovery_sidecar.take() else {
1372+ return;
1373+ };
1374+ let project_path = self.project_path.clone();
1375+ let opened = PlaybackSession::open_project(&sidecar).map_err(|e| e.to_string());
1376+ self.install_project(&project_path, opened, cx);
1377+ // `install_project` just re-ran the same mtime check on its way in and
1378+ // found the same sidecar still younger (recovering writes nothing to
1379+ // either file) -- offering the recovery it was just asked for right
1380+ // back would be the one loop in this feature.
1381+ self.recovery_sidecar = None;
1382+ }
1383+
1384+ /// Whether `project_path` has a sidecar beside it that outdates the file
1385+ /// itself: the sidecar exists, the project exists, and the sidecar's mtime
1386+ /// is strictly the younger of the two. Pure and file-system-only -- no
1387+ /// session, no `Player` -- so [`install_project`](Self::install_project)
1388+ /// asks it before anything is loaded and a test can ask it with nothing
1389+ /// but two paths on disk. A missing project file (a `.edith` opened for
1390+ /// the first time from somewhere else) or a missing/older sidecar both
1391+ /// answer `None`: there is nothing here a person did not just open on
1392+ /// their own.
1393+ fn recovery_offer(project_path: &Path) -> Option<PathBuf> {
1394+ let sidecar = Self::autosave_path(project_path)?;
1395+ let project_mtime = std::fs::metadata(project_path).and_then(|m| m.modified()).ok()?;
1396+ let sidecar_mtime = std::fs::metadata(&sidecar).and_then(|m| m.modified()).ok()?;
1397+ (sidecar_mtime > project_mtime).then_some(sidecar)
1398+ }
1399+
1400+ /// Starts the one background loop that ticks the autosave: every five
1401+ /// seconds, forever, for as long as the window is up. Cheap to run idle --
1402+ /// a tick with nothing dirty does nothing but reschedule itself -- so one
1403+ /// loop for the window's whole life is simpler than arming and disarming
1404+ /// a timer around every edit.
1405+ pub(crate) fn start_autosave(&mut self, cx: &mut Context<Self>) {
1406+ cx.spawn(async move |this, cx| {
1407+ loop {
1408+ cx.background_executor()
1409+ .timer(std::time::Duration::from_secs(5))
1410+ .await;
1411+ if this.update(cx, |this, cx| this.autosave_tick(cx)).is_err() {
1412+ return;
1413+ }
1414+ }
1415+ })
1416+ .detach();
1417+ }
1418+
1419+ /// One tick of the loop above. Writes the sidecar when an edit has been
1420+ /// idle for [`AUTOSAVE_DEBOUNCE`] (the debounce) or dirty edits have gone
1421+ /// unwritten for [`AUTOSAVE_PERIOD`] (the periodic safety net for a run
1422+ /// that never goes idle), and never while an export is running -- the two
1423+ /// would fight the same disk and the same worker for nothing an export
1424+ /// needs. Failure is a stderr line, never a notice: a sidecar losing a
1425+ /// write is not something a person can do anything about right now, and a
1426+ /// modal over it would be worse than the risk it is guarding against.
1427+ fn autosave_tick(&mut self, cx: &mut Context<Self>) {
1428+ if !self.autosave_dirty || self.exporting().is_some() {
1429+ return;
1430+ }
1431+ let now = Instant::now();
1432+ let idle = self
1433+ .autosave_last_edit
1434+ .map_or(true, |t| now.duration_since(t) >= AUTOSAVE_DEBOUNCE);
1435+ let overdue = self
1436+ .autosave_last_run
1437+ .map_or(true, |t| now.duration_since(t) >= AUTOSAVE_PERIOD);
1438+ if !idle && !overdue {
1439+ return;
1440+ }
1441+ let Some(sidecar) = Self::autosave_path(&self.project_path) else {
1442+ return;
1443+ };
1444+ let Some(session) = self.session.as_ref() else {
1445+ return;
1446+ };
1447+ match session.save_project(&sidecar) {
1448+ Ok(()) => {
1449+ self.autosave_dirty = false;
1450+ self.autosave_last_run = Some(now);
1451+ }
1452+ Err(e) => eprintln!("AUTOSAVE FAILED: {e}"),
1453+ }
1454+ cx.notify();
1455+ }
1456+
13111457 /// A new empty track under the ones already there. One undo step in the
13121458 /// engine, so the stroke that takes back an edit takes back a track too, and
13131459 /// no reseek: nothing plays differently until something is dropped on it.
@@ -1416,6 +1562,7 @@ impl Player {
14161562 cx.notify();
14171563 return;
14181564 };
1565+ self.mark_dirty();
14191566 if moved != lane {
14201567 self.selected.clear();
14211568 self.context_menu = None;
@@ -1477,3 +1624,63 @@ impl Player {
14771624 }
14781625 }
14791626 }
1627+
1628+#[cfg(test)]
1629+mod autosave_tests {
1630+ use super::*;
1631+
1632+ /// The three answers [`Player::recovery_offer`] gives, off nothing but a
1633+ /// project file and a sidecar's mtimes: younger sidecar offers it, an
1634+ /// older one or none at all offers nothing. Nowhere near a `Player` or a
1635+ /// `PlaybackSession` -- the helper reads only the filesystem, which is
1636+ /// what makes it askable from a test at all ([`Player`] needs a
1637+ /// `gpui::TestAppContext` this repo has no way to build).
1638+ #[test]
1639+ fn recovery_offer_reads_only_the_newer_sidecar() {
1640+ let dir = std::env::temp_dir().join(format!(
1641+ "edith-autosave-test-{}-{:?}",
1642+ std::process::id(),
1643+ std::thread::current().id()
1644+ ));
1645+ std::fs::create_dir_all(&dir).unwrap();
1646+ let project = dir.join("p.edith");
1647+ let sidecar = dir.join("p.edith.autosave");
1648+
1649+ // Neither file exists yet.
1650+ assert_eq!(Player::recovery_offer(&project), None);
1651+
1652+ std::fs::write(&project, b"project").unwrap();
1653+ // A project with no sidecar beside it: nothing to offer.
1654+ assert_eq!(Player::recovery_offer(&project), None);
1655+
1656+ std::fs::write(&sidecar, b"sidecar").unwrap();
1657+ let now = std::time::SystemTime::now();
1658+ // Sidecar written after the project (the ordinary case: an edit
1659+ // landed since the last manual save) -- offered.
1660+ std::fs::File::open(&project)
1661+ .unwrap()
1662+ .set_modified(now - Duration::from_secs(60))
1663+ .unwrap();
1664+ std::fs::File::open(&sidecar)
1665+ .unwrap()
1666+ .set_modified(now)
1667+ .unwrap();
1668+ assert_eq!(Player::recovery_offer(&project), Some(sidecar.clone()));
1669+
1670+ // The sidecar left over from *before* the last manual save (the save
1671+ // that answered it, per `Player::save_project`, deletes it -- but an
1672+ // older one left by some other means must not be offered as newer
1673+ // than a file it predates).
1674+ std::fs::File::open(&project)
1675+ .unwrap()
1676+ .set_modified(now)
1677+ .unwrap();
1678+ std::fs::File::open(&sidecar)
1679+ .unwrap()
1680+ .set_modified(now - Duration::from_secs(60))
1681+ .unwrap();
1682+ assert_eq!(Player::recovery_offer(&project), None);
1683+
1684+ std::fs::remove_dir_all(&dir).unwrap();
1685+ }
1686+}
crates/app/src/player/timeline_edit.rsmodified+5 -0
@@ -282,6 +282,7 @@ impl Player {
282282 if self.exporting().is_some() {
283283 return;
284284 }
285+ self.mark_dirty();
285286 let (Some((start, _)), Some(was)) = (
286287 self.drop_frame(from, idx, x),
287288 self.session
@@ -367,6 +368,7 @@ impl Player {
367368 if self.exporting().is_some() {
368369 return;
369370 }
371+ self.mark_dirty();
370372 self.snap_cue = None;
371373 self.ghost = None;
372374 let at = self.place_frame(x).0;
@@ -450,6 +452,7 @@ impl Player {
450452 if self.exporting().is_some() {
451453 return;
452454 }
455+ self.mark_dirty();
453456 self.snap_cue = None;
454457 self.ghost = None;
455458 let Some(idx) = self.dragged_sub(drag) else {
@@ -522,6 +525,7 @@ impl Player {
522525 if self.exporting().is_some() {
523526 return;
524527 }
528+ self.mark_dirty();
525529 let lifted = self
526530 .session
527531 .as_mut()
@@ -1130,6 +1134,7 @@ impl Player {
11301134 let Some(trim) = self.trim.take() else {
11311135 return;
11321136 };
1137+ self.mark_dirty();
11331138 // A caption's edge reaches the engine through its own door, at this
11341139 // timeline's rate. An `Ok` is *not* "something changed" -- an edge that
11351140 // stopped at a wall it already stood against is `Ok` with no undo step
crates/app/src/render.rsmodified+13 -0
@@ -207,6 +207,19 @@ impl Render for Player {
207207 {
208208 return;
209209 }
210+ // The recovery notice is the one bar that reads a key as more
211+ // than "answered": `enter` loads the sidecar it named, and
212+ // every other key declines it -- the way any other key
213+ // dismisses any other notice. Asked before the generic
214+ // dismiss below shares the same door with it, not instead of
215+ // it: this recovers or declines, that pops the bar.
216+ if this.recovery_sidecar.is_some() {
217+ if key == "enter" {
218+ this.recover_from_sidecar(cx);
219+ } else {
220+ this.recovery_sidecar = None;
221+ }
222+ }
210223 // Any key answers the message on the bar and brings the next of
211224 // them up, whatever it was -- and owes
212225 // the repaint itself: a notice no longer keeps the render loop