diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index 17d77e6..c079658 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -18,10 +18,15 @@ pub(crate) enum Wave { Loading, /// The file has no audio track. An answer, not a miss. Silent, - /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]: - /// "this file's sound could not be read" and "this file has no sound" look - /// the same on a lane, and the first is a bug report waiting to happen. - Failed, + /// The decode failed, at the moment it did. Drawn as its own mark rather + /// than as [`Self::Silent`]: "this file's sound could not be read" and + /// "this file has no sound" look the same on a lane, and the first is a + /// bug report waiting to happen. It is *not* an answer, though: a failure + /// may have had a reason that has since gone away (a file still being + /// copied when it arrived), so [`crate::subs::unseen_sources`] asks again + /// once the stamp is older than its cooldown -- which is what the stamp is + /// for. + Failed(std::time::Instant), Peaks(Arc>), } diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 8f2ad31..3edc3d9 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -685,20 +685,141 @@ impl Player { } pub(crate) fn undo(&mut self, cx: &mut Context) { - if self.session.as_mut().is_some_and(PlaybackSession::undo) { - self.reset_after_reseek(); - } + self.step_history(PlaybackSession::undo); self.selected.clear(); cx.notify(); } pub(crate) fn redo(&mut self, cx: &mut Context) { - if self.session.as_mut().is_some_and(PlaybackSession::redo) { - self.reset_after_reseek(); - } + self.step_history(PlaybackSession::redo); self.selected.clear(); cx.notify(); } + + /// One step of the session's own history through the door both `^z` and + /// `^y` go through, and the window-side state it moves taken back up + /// afterwards ([`history_step`]). + /// + /// The plate the pick drew goes with the pick + /// ([`Player::remove_subtitle_track`]'s own drop, for its own reason) and + /// the frame owed to the screen is cleared + /// ([`Player::reset_after_reseek`]): an undo reseeks inside the engine, and + /// a picture left where it was is the frame before the step. + fn step_history(&mut self, step: fn(&mut PlaybackSession) -> bool) { + let mut caches = SessionCaches { + fps: self.fps, + proxies_on: self.proxies_on, + auto_proxies_on: self.auto_proxies_on, + }; + let before = HistoryBefore::of( + self.session.as_ref().map_or(&[][..], |s| s.subtitles()), + self.sub_track, + ); + let Some(outcome) = self + .session + .as_mut() + .and_then(|session| history_step(&before, &mut caches, session, step)) + else { + return; + }; + self.fps = caches.fps; + self.proxies_on = caches.proxies_on; + self.auto_proxies_on = caches.auto_proxies_on; + self.sub_track = outcome.sub_track; + if outcome.drop_sub_image { + // corner-cut: its atlas tile is not released -- `close_session`'s + // note, for its reason and with its upgrade path. + self.sub_image = None; + } + self.reset_after_reseek(); + } +} + +/// The three session settings a window keeps its own copy of, as a value so +/// that [`history_step`] can re-read them in place: the rate every +/// frame↔second conversion in the window counts in (`Player::timeline_at`, +/// `Scale::snap_frames`) and the two switches a project carries and the +/// Settings rows *show* (`settings_stance`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SessionCaches { + pub(crate) fps: f64, + pub(crate) proxies_on: bool, + pub(crate) auto_proxies_on: bool, +} + +/// The window-side state of the palette as a history step finds it: the pick, +/// how many rows there are, and which row the pick names. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct HistoryBefore { + pub(crate) sub_track: usize, + pub(crate) sub_rows: usize, + pub(crate) sub_row: Option, +} + +impl HistoryBefore { + /// `tracks` as they stand and the index picked there -- an empty palette + /// for a window with no session, which is the state a step cannot happen in + /// anyway. + pub(crate) fn of(tracks: &[engine::subtitle::SubtitleTrack], sub_track: usize) -> Self { + Self { + sub_track, + sub_rows: tracks.len(), + sub_row: SubPickKey::of(tracks, sub_track), + } + } +} + +/// What a history step leaves this window to take up beside the session's own +/// lanes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct HistoryOutcome { + pub(crate) sub_track: usize, + /// The plate over the picture (`Player::sub_image`) has to go. Its tile is + /// keyed by *where* a cue sits ([`Player::sub_picture`]'s `(lane, + /// start_us)`) and carries no track, so a step that moves captions, takes + /// one off, or renumbers the track a placement names + /// ([`engine::Project::remove_subtitles`] walks `SubClip::track` down) + /// cannot be asked of that cache -- the tile at a key can be served for a + /// cue it was not drawn from. Conservative on purpose: at most one plate is + /// redrawn by the next repaint. + pub(crate) drop_sub_image: bool, +} + +/// One step of the session's own history ([`PlaybackSession::undo`], +/// [`PlaybackSession::redo`]) with everything this window caches re-read after +/// it. `None` when the step did not happen -- nothing to undo, nothing to redo +/// -- and then nothing here moves either. +/// +/// A free function over the session and the caches rather than a [`Player`] +/// method: this test binary has no `TestAppContext` to build a `Player` in, so +/// what `^z` does to the session *and* to the caches beside it is pinned here, +/// and [`Player::step_history`] is this call plus the repaint. +/// +/// The rate and the two switches are read off the *session*, exactly as the +/// doors that own them do ([`Player::apply_frame_rate`], the `.edith` load): a +/// history entry carries the project's settings beside its lanes +/// (`Project::snapshot`), so a step puts them back -- and a window that kept +/// its old copies counts a cut at the rate just undone, keeps reporting a +/// switch the session no longer has, and pushes that switch at the next session +/// it makes. +pub(crate) fn history_step( + before: &HistoryBefore, + caches: &mut SessionCaches, + session: &mut PlaybackSession, + step: fn(&mut PlaybackSession) -> bool, +) -> Option { + if !step(session) { + return None; + } + caches.fps = session.meta().frame_rate; + caches.proxies_on = session.proxies(); + caches.auto_proxies_on = session.auto_proxies(); + let tracks = session.subtitles(); + let sub_track = sub_pick_after_restore(before.sub_track, before.sub_row.as_ref(), tracks); + Some(HistoryOutcome { + sub_track, + drop_sub_image: tracks.len() != before.sub_rows || sub_track != before.sub_track, + }) } /// The half-open range a mark and a mark make, in either order: a person's two diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index 389661d..75423f3 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -2,6 +2,7 @@ //! two of them decide. use crate::*; +use std::time::Instant; impl Player { /// What [`timeline_math::lane_refuses`] asks to decide a video lane's @@ -231,7 +232,7 @@ impl Player { } starting.push(path); } - for key in unseen_sources(session.sources(), &self.waves) { + for key in unseen_sources(session.sources(), &self.waves, Instant::now()) { self.waves.insert(key.clone(), Wave::Loading); let decoded = cx.background_executor().spawn({ let (path, stream) = key.clone(); @@ -254,7 +255,11 @@ impl Player { // A file whose sound we could not read is not a // silent one, and a lane that drew it as silent is // how a broken decode passes for a design choice. - Err(_) => Wave::Failed, + // Stamped, and not an answer: a repaint past + // [`WAVE_RETRY`] asks again, so a failure whose + // cause went away (a file still being copied when + // it arrived) draws its envelope without a reopen. + Err(_) => Wave::Failed(Instant::now()), }, ); cx.notify(); diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index b0d0290..16efa54 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -1711,11 +1711,13 @@ impl Player { /// would name a *different* track -- and the pick is what an export writes /// into the file. /// - /// Not an undo step: subtitles are not on the history's snapshots, so the - /// way back is putting the file's subtitles on again -- which is a door of - /// its own ([`Player::pick_and_add_subtitles`]) and reads the subtitles - /// alone, never the media. The notice says that rather than promising a - /// ctrl+z that would do nothing. + /// One undo step, and the palette comes back with the reindex + /// ([`engine::Project::remove_subtitles`]), so `^z` is a way back that + /// works -- [`Player::step_history`] moves the pick back with it and drops + /// the plate the old index drew. The second way back, for a caller that + /// wants the *file's* tracks again, is putting them on + /// ([`Player::pick_and_add_subtitles`]): a door of its own that reads the + /// subtitles alone, never the media, which is what the notice names. pub(crate) fn remove_subtitle_track(&mut self, track: usize, cx: &mut Context) { // The one availability oracle, for the same reason the × on a row and // the stroke are one call: an empty list is not a failure, it is an @@ -1749,8 +1751,12 @@ impl Player { .as_ref() .map_or(0, |session| session.subtitles().len()); self.sub_track = sub_pick_after_removal(self.sub_track, track, left); - // The drawn cue is keyed by that index ([`Player::sub_picture`]) - // and the index now stands for another track. + // The cue over the picture goes with the pick: its tile is + // keyed by *where* the cue sits ([`Player::sub_picture`]'s + // `(lane, start_us)`) and never by the track it shows, so the + // index that moved here is not something that cache can be + // asked about. Conservative, and the same drop a history step + // makes for the same reason ([`Player::step_history`]). // // corner-cut: its atlas tile is not released -- `close_session`'s // note, for its reason and with its upgrade path. diff --git a/crates/app/src/subs.rs b/crates/app/src/subs.rs index c35bfad..10e42b6 100644 --- a/crates/app/src/subs.rs +++ b/crates/app/src/subs.rs @@ -333,9 +333,7 @@ pub(crate) fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option match subs { Ok(tracks) => match session.add_subtitle_tracks(tracks) { 0 => None, - n => Some(format!( - " · {n} subtitle track(s)" - )), + n => Some(format!(" · {n} subtitle track(s)")), }, Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")), } @@ -625,11 +623,15 @@ pub(crate) fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec usize { let picked = match removed < picked { true => picked - 1, @@ -638,6 +640,65 @@ pub(crate) fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) picked.min(left.saturating_sub(1)) } +/// What a palette row *is*, apart from where it sits: the file it came out of, +/// which track of it, and the two words a row shows. Cloned out of the palette +/// once per history step -- a path and three short strings, against a palette +/// whose cues are the whole film's subtitles. Not [`SubRow`], which is a row as +/// the column *draws* it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SubPickKey { + path: PathBuf, + track: Option, + language: String, + label: String, +} + +impl SubPickKey { + /// The row `track` of this palette names, `None` for an index no track + /// answers to -- the same silence [`sub_pick_name`] gives. + pub(crate) fn of(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option { + let track = tracks.get(track)?; + Some(Self { + path: track.path.clone(), + track: track.track, + language: track.language.clone(), + label: track.label.clone(), + }) + } + + /// Whether `track` is this row: the four fields a palette would have had to + /// change for a pick left where it was to name a different track. + fn is(&self, track: &engine::subtitle::SubtitleTrack) -> bool { + track.path == self.path + && track.track == self.track + && track.language == self.language + && track.label == self.label + } +} + +/// Where the pick lands once a *restored* palette is back in place: the row +/// that was picked, found by what it is rather than by where it sat. +/// +/// A history step moves rows without saying which one moved -- an undo of a +/// removal puts a column back above the pick as often as below it -- so an +/// index left where it was names a different track, which is the desync +/// [`sub_pick_after_removal`] prevents at the door where the row that moved is +/// known. That door's arithmetic is this map's one-row-moved case. +/// +/// A row the restored palette does not have (it went again, or the pick named +/// nothing) falls back to the old index clamped into the new list -- that same +/// door's own fallback, and the zero the section is not drawn at all for an +/// emptied palette. +pub(crate) fn sub_pick_after_restore( + picked: usize, + before: Option<&SubPickKey>, + after: &[engine::subtitle::SubtitleTrack], +) -> usize { + before + .and_then(|was| after.iter().position(|track| was.is(track))) + .unwrap_or_else(|| picked.min(after.len().saturating_sub(1))) +} + pub(crate) fn sub_pick_name( tracks: &[engine::subtitle::SubtitleTrack], track: usize, @@ -705,17 +766,33 @@ pub(crate) fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::s .collect() } -/// The sources a repaint has not asked about yet. A key that is already there -/// means "asked", whatever state it is in, which is what stops a decode already -/// running from being started again by the next of sixty repaints a second. +/// How long a failed waveform decode is left alone before the next repaint asks +/// again: long enough that sixty repaints a second do not become sixty decodes, +/// short enough that a file which arrived mid-copy has its envelope a moment +/// after it lands. The engine memoizes no failure for the same reason +/// ([`engine::waveform`]): the reason one failed may have gone away. +pub(crate) const WAVE_RETRY: std::time::Duration = std::time::Duration::from_secs(5); + +/// The sources a repaint has not asked about yet, as of `now`. A key that is +/// already there means "asked", whatever state it is in -- which is what stops +/// a decode already running from being started again by the next of sixty +/// repaints a second -- with one exception: a [`Wave::Failed`] older than +/// [`WAVE_RETRY`] is asked again, because a decode that failed once is not an +/// answer about the file, only about the moment it was tried. A file with no +/// audio (`Wave::Silent`) is an answer like any other and is never re-asked. pub(crate) fn unseen_sources( sources: &[Source], waves: &HashMap<(PathBuf, usize), Wave>, + now: std::time::Instant, ) -> Vec<(PathBuf, usize)> { sources .iter() .map(|s| (s.path.clone(), s.audio_stream)) - .filter(|key| !waves.contains_key(key)) + .filter(|key| match waves.get(key) { + None => true, + Some(Wave::Failed(at)) => now.duration_since(*at) >= WAVE_RETRY, + Some(_) => false, + }) .collect() } diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs index e7da37e..9772a0e 100644 --- a/crates/app/src/tests/cards.rs +++ b/crates/app/src/tests/cards.rs @@ -914,7 +914,10 @@ fn the_budget_is_the_one_number_the_engine_gets() { // put on screen. assert_eq!(auto_bps(1920, 1080, 30.), 6_220_800); assert_eq!(auto_bps(160, 120, 15.), BPS_MIN, "a tiny picture floors"); - assert!(auto_bps(7680, 4320, 60.) <= 20_000_000, "and a huge one caps"); + assert!( + auto_bps(7680, 4320, 60.) <= 20_000_000, + "and a huge one caps" + ); for bps in [auto_bps(1920, 1080, 30.), auto_bps(320, 240, 24.)] { assert!((BPS_MIN..=BPS_MAX).contains(&bps)); } @@ -1067,11 +1070,25 @@ fn a_chord_the_export_moment_answers_never_reaches_the_room() { let (typing, closed) = rest .split_once("return true;") .expect("the typing branch returns before the chords below it"); - assert!(typing.contains("self.budget_edit = None"), "esc leaves the field"); - assert!(closed.contains("self.close_card()"), "then esc closes the moment"); + assert!( + typing.contains("self.budget_edit = None"), + "esc leaves the field" + ); + assert!( + closed.contains("self.close_card()"), + "then esc closes the moment" + ); // Its chords, all of them consumed here rather than by the keymap. for chord in [ - "\"d\"", "\"n\"", "\"e\"", "\"enter\"", "\"up\"", "\"down\"", "\"c\"", "\"b\"", "\"g\"", + "\"d\"", + "\"n\"", + "\"e\"", + "\"enter\"", + "\"up\"", + "\"down\"", + "\"c\"", + "\"b\"", + "\"g\"", "\",\"", ] { assert!(closed.contains(chord), "{chord} is not the moment's own"); @@ -1086,7 +1103,11 @@ fn a_chord_the_export_moment_answers_never_reaches_the_room() { fn row_three_wears_the_encode_options_and_the_door_to_the_rest() { let cards = src_text("ui/cards.rs"); let start = cards.find("fn export_card(").expect("the moment"); - let body = &cards[start..start + cards[start..].find("\n /// ").unwrap_or(cards.len() - start)]; + let body = &cards[start + ..start + + cards[start..] + .find("\n /// ") + .unwrap_or(cards.len() - start)]; // A segment is the setter it names, not a readout of it. for (id, chord, setter) in [ ("moment-picture", "\"c\"", "cycle_export_picture"), @@ -1098,7 +1119,10 @@ fn row_three_wears_the_encode_options_and_the_door_to_the_rest() { assert!(body.contains(setter), "the {id} segment changes nothing"); } // The door, wearing the room's own chord rather than a hand-typed one. - assert!(body.contains("moment-settings"), "row 3 has no settings door"); + assert!( + body.contains("moment-settings"), + "row 3 has no settings door" + ); assert!( body.contains("self.keymap.chord(ActionId::Settings)"), "the door's chord is not read from the keymap" @@ -1113,7 +1137,10 @@ fn row_three_wears_the_encode_options_and_the_door_to_the_rest() { .map(|at| &cards[at..at + 1900]) .expect("the segment atom"); assert!(seg.contains("INK3()") && seg.contains("INK4()")); - assert!(seg.contains("DARK_RAISED()"), "a segment does not answer hover"); + assert!( + seg.contains("DARK_RAISED()"), + "a segment does not answer hover" + ); // The readouts worth seeing: the project's picture size and rate, and // a sound rate that is on the line whether or not it is pressable. assert!( @@ -1126,13 +1153,18 @@ fn row_three_wears_the_encode_options_and_the_door_to_the_rest() { ); // The picture segment is a child, not a `has_video` maybe: hidden on the // sound-only formats it left `c` pressing nothing and no way back. - let at = body.find("\"moment-picture\"").expect("the picture segment"); + let at = body + .find("\"moment-picture\"") + .expect("the picture segment"); assert!( !body[at - 240..at].contains("has_video"), "the picture segment is gated on has_video again -- the dead end" ); // Wrapped, never cut: the readouts made row 3 longer than 1280 wide. - assert!(body.contains(".flex_wrap()"), "row 3 truncates instead of wrapping"); + assert!( + body.contains(".flex_wrap()"), + "row 3 truncates instead of wrapping" + ); } /// The dead end the user hit: the cycle walked into the sound-only formats @@ -1140,15 +1172,22 @@ fn row_three_wears_the_encode_options_and_the_door_to_the_rest() { /// and can't turn it back to video"). One cycle, and it wraps. #[test] fn the_picture_cycle_wraps_out_of_the_sound_only_formats() { - use crate::ui::settings_stance::{PICTURE_CYCLE, next_picture}; + use crate::ui::settings_stance::{next_picture, PICTURE_CYCLE}; // Nothing refused: every stop is the next one, and the last wraps to the // first -- OGG, the tail of the list, back to MP4. let mut at = PICTURE_CYCLE[0]; - for &want in PICTURE_CYCLE.iter().skip(1).chain(std::iter::once(&PICTURE_CYCLE[0])) { + for &want in PICTURE_CYCLE + .iter() + .skip(1) + .chain(std::iter::once(&PICTURE_CYCLE[0])) + { at = next_picture(at, |_| false); assert_eq!(at, want, "the cycle stopped walking"); } - assert_eq!(at, PICTURE_CYCLE[0], "a full walk is a wrap, not a dead end"); + assert_eq!( + at, PICTURE_CYCLE[0], + "a full walk is a wrap, not a dead end" + ); assert_eq!(next_picture(Format::Ogg, |_| false), Format::Mp4); // A timeline with no picture refuses every video format, and the cycle // still moves: the sound-only stops are what is left of it. @@ -1278,12 +1317,33 @@ fn the_moment_and_the_settings_room_wear_the_same_export_chords() { assert!(settings.contains(chord), "the EXPORT rows lost {chord}"); assert!(moment.contains(chord), "row 3 lost {chord}"); assert!(handler.contains(chord), "the moment answers no {chord}"); - assert!(player.contains(chord), "the settings page answers no {chord}"); + assert!( + player.contains(chord), + "the settings page answers no {chord}" + ); } + // The Encoder row is the picture's own -- the engine opens no seat for a + // song -- so the settings room gates it on the format exactly as the + // moment does, and neither mounts a row for an audio-only format. + assert_eq!(Format::Mp4.has_video(), true); + for audio_only in [Format::Wav, Format::Flac, Format::Mp3, Format::Ogg] { + assert_eq!(audio_only.has_video(), false, "{audio_only:?}"); + } + let at = settings + .find("settings-export-encoder") + .expect("the Encoder row"); + let mount = &settings[at.saturating_sub(260)..at]; + assert!( + mount.contains("has_video()"), + "the Encoder row is mounted for a song, where pressing it does nothing" + ); // `e` stays the Export press: the encoder seat took `g` rather than a // shifted letter, which no ghost wears. assert!(handler.contains("\"e\" | \"enter\" => self.start_export")); - assert!(!settings.contains("\n \"e\","), "the Encoder row took `e` back"); + assert!( + !settings.contains("\n \"e\","), + "the Encoder row took `e` back" + ); } /// The Sound row: what it offers, and that the pick travels to the engine @@ -1401,9 +1461,15 @@ fn a_typed_colour_is_read_in_every_spelling_and_anything_else_is_refused() { edit.typed('z'); assert_eq!(edit.commit(), None); let why = edit.refusal.clone().expect("a refusal, not a silence"); - assert!(why.contains("#RRGGBB"), "the refusal says what a colour is: {why}"); + assert!( + why.contains("#RRGGBB"), + "the refusal says what a colour is: {why}" + ); assert_eq!(edit.text, "zz", "the refusal keeps the text it refused"); - assert!(edit.detail().contains("zz▏"), "the caret stays in the buffer"); + assert!( + edit.detail().contains("zz▏"), + "the caret stays in the buffer" + ); // ...and the next stroke clears it: that reason described the text that is // no longer there. edit.typed('0'); @@ -1780,11 +1846,9 @@ fn a_choice_list_offers_every_value_and_fits_the_smallest_window() { assert!(native_detail.ends_with(" source"), "{native_detail}"); // A project at a size nobody listed still gets the whole list, with // nothing marked rather than a wrong row marked. - assert!( - resolution_choices((1000, 1000), native) - .iter() - .all(|(.., picked)| !picked) - ); + assert!(resolution_choices((1000, 1000), native) + .iter() + .all(|(.., picked)| !picked)); // Picking a row means that row, and stepping means the next one: the // list and the stroke read the same ladder. assert_eq!(next_resolution(ladder[1], native), ladder[2]); @@ -1883,7 +1947,10 @@ fn a_choice_list_offers_every_value_and_fits_the_smallest_window() { assert!(tall <= 360., "the list is taller than the floor"); assert_eq!( menu_at(point(px(600.), px(340.)), size(px(640.), px(360.)), tall), - (640. - crate::layout::MENU_EDGE - MENU_W, 360. - crate::layout::MENU_EDGE - tall), + ( + 640. - crate::layout::MENU_EDGE - MENU_W, + 360. - crate::layout::MENU_EDGE - tall + ), "the list would hang off the smallest window" ); } @@ -2238,8 +2305,8 @@ fn maximizing_a_card_grows_its_box_without_moving_where_a_value_sits_in_it() { /// inside the dock, or hands it the dock's width again, fails this. #[test] fn a_maximized_cards_room_is_bigger_than_the_docked_rooms_not_smaller() { + use crate::layout::{split_size, Split}; use crate::SPLIT_W; - use crate::layout::{Split, split_size}; // `layout::SPLIT_W` is the one divider between `stance-centre` and the // dock; the 56px rail that used to eat the centre's left edge is gone @@ -2286,7 +2353,7 @@ fn a_maximized_cards_room_is_bigger_than_the_docked_rooms_not_smaller() { /// assumption. #[test] fn a_maximized_card_can_never_rise_above_the_picture_no_matter_the_bench_height() { - use crate::ui::stance::{LEDGER_H, TIME_BAND_H, below_picture_floor}; + use crate::ui::stance::{below_picture_floor, LEDGER_H, TIME_BAND_H}; let viewport_h = 1080.; for bench_h in [140., 200., 400.] { assert_eq!( @@ -2531,3 +2598,58 @@ fn picker_row_tails_are_state_words_and_settings_values_carry_no_ellipsis() { ); } } + +/// D1: the project's own settings are the project's -- the resolution, the +/// rate, the encoder seat, the mix rate and the two proxy switches ride in +/// the same history entry the lanes do, so every one of those picks is a +/// single `ctrl+z`. Before this, pressing `z` after any of them did nothing. +#[test] +fn a_settings_pick_undoes_and_redoes_like_a_cut() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let (w, h) = session.resolution(); + + assert!(session.set_resolution(w / 2, h / 2)); + assert_eq!(session.resolution(), (w / 2, h / 2)); + assert!(session.undo(), "the resolution pick is one step"); + assert_eq!(session.resolution(), (w, h), "and the canvas comes back"); + assert!(session.redo(), "redo walks the same branch"); + assert_eq!(session.resolution(), (w / 2, h / 2)); + assert!(session.undo(), "back to where the test started"); + + // The encoder seat, which nothing reseeks and nothing shows until an + // export starts. + let seat = session.encoder_seat(); + assert_ne!(seat, EncoderSeat::Software); + session.set_encoder_seat(EncoderSeat::Software); + assert_eq!(session.encoder_seat(), EncoderSeat::Software); + assert!(session.undo(), "the encoder pick is one step"); + assert_eq!(session.encoder_seat(), seat, "and the seat comes back"); + assert!(session.redo()); + assert_eq!(session.encoder_seat(), EncoderSeat::Software); + assert!(session.undo()); + + // The mix rate, and the switches beside it. + session.set_sample_rate(Some(44_100)); + assert_eq!(session.sample_rate(), Some(44_100)); + assert!(session.undo(), "the mix rate is one step"); + assert_eq!(session.sample_rate(), None, "back to the derived rate"); + let proxies = session.proxies(); + session.set_proxies(!proxies); + assert_eq!(session.proxies(), !proxies); + assert!(session.undo(), "the proxy switch is one step"); + assert_eq!(session.proxies(), proxies, "and the switch comes back"); + let auto = session.auto_proxies(); + session.set_auto_proxies(!auto); + assert_eq!(session.auto_proxies(), !auto); + assert!(session.undo(), "and so is the auto switch"); + assert_eq!(session.auto_proxies(), auto, "which comes back too"); + + // ...and a lane edit still undoes the way it always did, settings and all + // in the same stack. + let clips = session.lane_clips(Lane::V1).len(); + assert_eq!(clips, 1, "one take to start with"); + assert!(session.delete_clip(Lane::V1, 0)); + assert_eq!(session.lane_clips(Lane::V1).len(), 0); + assert!(session.undo(), "the delete is one step"); + assert_eq!(session.lane_clips(Lane::V1).len(), clips); +} diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index 04ed625..e3dcec0 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -109,11 +109,9 @@ fn a_song_opens_the_window_by_itself() { // ...and it places, on the audio lane, through the door `insert_source` // uses: a second copy of the song at the playhead. session.seek(1.0); - assert!( - session - .place_stream_at(1.0, &path, 0, Some(Lane::A1)) - .expect("its own file is on this timeline") - ); + assert!(session + .place_stream_at(1.0, &path, 0, Some(Lane::A1)) + .expect("its own file is on this timeline")); assert_eq!(session.lane_clips(Lane::A1).len(), 2); assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); @@ -345,13 +343,11 @@ fn a_caption_is_deleted_by_the_same_row_and_stroke_every_box_is() { ); // ...and the same reading with a clip under it is the clip menu, untouched: // the flag is off wherever a `Clip` was clicked. - assert!( - menu_items(Ctx { - timeline: true, - ..Ctx::default() - }) - .contains(&ActionId::Cut) - ); + assert!(menu_items(Ctx { + timeline: true, + ..Ctx::default() + }) + .contains(&ActionId::Cut)); } /// A timeline with a subtitle palette and an empty subtitle lane: what a @@ -939,16 +935,14 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { } assert!(!whole(ActionId::Delete, live).yes()); assert!(!whole(ActionId::Paste, live).yes()); - assert!( - whole( - ActionId::Paste, - Ctx { - clipboard: true, - ..live - } - ) - .yes() - ); + assert!(whole( + ActionId::Paste, + Ctx { + clipboard: true, + ..live + } + ) + .yes()); assert!(!whole(ActionId::CancelExport, live).yes()); let busy = Ctx { exporting: true, @@ -988,7 +982,10 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.)); assert_eq!( menu_at(point(px(700.), px(380.)), viewport, 150.), - (800. - crate::layout::MENU_EDGE - MENU_W, 400. - crate::layout::MENU_EDGE - 150.) + ( + 800. - crate::layout::MENU_EDGE - MENU_W, + 400. - crate::layout::MENU_EDGE - 150. + ) ); // A window smaller than the menu loses its bottom, never its top: the // top-left margin wins over the bottom-right one, because the items are @@ -1165,16 +1162,14 @@ fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() { assert!(row_enable(RowItem::RemoveWithClips, placed).yes()); let unplaced = row_items(live); assert!(unplaced.contains(&RowItem::Remove) && !unplaced.contains(&RowItem::RemoveWithClips)); - assert!( - !row_enable( - RowItem::RemoveWithClips, - RowCtx { - exporting: true, - ..placed - } - ) - .yes() - ); + assert!(!row_enable( + RowItem::RemoveWithClips, + RowCtx { + exporting: true, + ..placed + } + ) + .yes()); assert!(!row_enable(RowItem::Add, RowCtx::default()).yes()); // Every refusal is short enough to sit in the hint column beside its // label, the clip menu's rule. @@ -1282,7 +1277,11 @@ fn the_hanging_menus_mount_at_the_room_root_and_their_rows_wear_chords_not_prose } // §9: no junk drawer. A label that fits the plate whole beside its // chord, and never a sentence. - assert!(item.label().split_whitespace().count() <= 4, "{}", item.label()); + assert!( + item.label().split_whitespace().count() <= 4, + "{}", + item.label() + ); } // The two removes must not read as the same verb now that the column // beside them is empty. @@ -1604,11 +1603,9 @@ fn adding_a_row_drops_the_whole_source_in_at_the_playhead() { let frames = session.file_frames(&second); // Through the engine door `insert_source` uses, with the row's own // stream: the button, the drop and this are one call. - assert!( - session - .place_stream_at(2.0, &second, 0, None) - .expect("av2 is already on the timeline") - ); + assert!(session + .place_stream_at(2.0, &second, 0, None) + .expect("av2 is already on the timeline")); // The whole of source 1 went in and nothing was painted over: the // timeline is longer by exactly that file. assert_eq!(session.timeline_duration(), 9.0); @@ -1635,11 +1632,9 @@ fn adding_a_row_drops_the_whole_source_in_at_the_playhead() { let path = session.sources()[0].path.clone(); let frames = session.file_frames(&path); let end = session.timeline_duration(); - assert!( - session - .place_stream_at(end, &path, 1, None) - .expect("the French track shares the timeline's parameters") - ); + assert!(session + .place_stream_at(end, &path, 1, None) + .expect("the French track shares the timeline's parameters")); assert_eq!(session.sources()[1].audio_stream, 1); assert_eq!(session.timeline_duration(), end * 2.0); // Both rows are the same file, so both rows are that file's length -- @@ -1689,11 +1684,9 @@ fn a_row_dropped_on_the_open_bed_lands_under_the_pointer() { // ...and what the release does with it: the frame back through the same // rate every box is drawn at, into the door the Add button uses too. - assert!( - session - .place_stream_at(f64::from(at) / fps, &second, 0, None) - .expect("av2 is already on this timeline") - ); + assert!(session + .place_stream_at(f64::from(at) / fps, &second, 0, None) + .expect("av2 is already on this timeline")); let head = |lane| { session .lane_clips(lane) @@ -1727,11 +1720,9 @@ fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() { session.import(&asset("test_av2.mp4")).expect("av2 matches"); let second = session.sources()[1].path.clone(); let end = session.timeline_duration(); - assert!( - session - .place_stream_at(end, &second, 0, None) - .expect("a file just imported is on this timeline") - ); + assert!(session + .place_stream_at(end, &second, 0, None) + .expect("a file just imported is on this timeline")); let streams = HashMap::new(); let rows = |session: &PlaybackSession| { library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len() @@ -1943,6 +1934,211 @@ fn trim_to_playhead_moves_the_selected_clips_edge_and_undoes_in_one_step() { assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the tail is back"); } +/// The window's own copy of the rate and the two switches follows the +/// *session* across `^z` and `^y`: a history entry carries the project's +/// settings beside its lanes ([`engine::Project::snapshot`]), so a step puts +/// them back -- and a window that kept its old copies counts every cut, step +/// and fade in the rate it just undid, keeps showing a switch the session no +/// longer has (`settings_stance`), and pushes that switch at the next session +/// it makes. +#[test] +fn the_windows_settings_caches_follow_the_session_across_undo_and_redo() { + use crate::player::actions::{history_step, HistoryBefore, SessionCaches}; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let native = session.meta().frame_rate; + let (proxies, auto) = (!session.proxies(), !session.auto_proxies()); + + // The three picks as the window makes them, with the copies it keeps beside + // them (`Player::apply_frame_rate`'s own write, both toggle doors'). + assert!(session.set_frame_rate(native * 2.0), "the rate pick"); + session.set_proxies(proxies); + session.set_auto_proxies(auto); + let mut caches = SessionCaches { + fps: session.meta().frame_rate, + proxies_on: proxies, + auto_proxies_on: auto, + }; + assert_ne!( + caches.fps, native, + "the test needs a rate that really moved" + ); + + // Back, one step at a time: after each one the window's copies are the + // session's, never the pick's. + for step in 0..3 { + let before = HistoryBefore::of(session.subtitles(), 0); + let out = history_step(&before, &mut caches, &mut session, PlaybackSession::undo) + .expect("a pick behind this one"); + assert_eq!( + caches.fps, + session.meta().frame_rate, + "undo {step}: the rate" + ); + assert_eq!( + caches.proxies_on, + session.proxies(), + "undo {step}: the switch" + ); + assert_eq!( + caches.auto_proxies_on, + session.auto_proxies(), + "undo {step}: the auto switch" + ); + assert!(!out.drop_sub_image, "undo {step}: no palette moved"); + } + assert_eq!(caches.fps, native, "the rate pick is undone"); + assert_eq!( + (caches.proxies_on, caches.auto_proxies_on), + (!proxies, !auto), + "and both switches are back where they were" + ); + + // ...and forward again, where the picks come home. + for step in 0..3 { + let before = HistoryBefore::of(session.subtitles(), 0); + history_step(&before, &mut caches, &mut session, PlaybackSession::redo) + .expect("a pick in front of this one"); + assert_eq!( + caches.fps, + session.meta().frame_rate, + "redo {step}: the rate" + ); + assert_eq!( + caches.proxies_on, + session.proxies(), + "redo {step}: the switch" + ); + } + assert_eq!(caches.fps, native * 2.0, "the pick's own rate is back"); + assert_eq!(caches.proxies_on, proxies, "and its switch"); +} + +/// Rows above the picked subtitle move the pick down with them +/// ([`sub_pick_after_removal`]), and a `^z` of that removal has to move it back +/// up: the palette comes home out of the entry, the pick is an *index* into it, +/// and an index left where it was highlights one row and names another. The +/// plate over the picture goes too, not because it is keyed by the pick -- it is +/// keyed by where a cue sits -- but because the step moves the cues under it. +#[test] +fn the_subtitle_pick_follows_its_track_across_an_undo_of_a_removal() { + use crate::player::actions::{history_step, HistoryBefore, SessionCaches}; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + assert_eq!( + session.add_subtitle_tracks(vec![ + sub("/subs/one.srt", None, "one.srt"), + sub("/subs/two.srt", None, "two.srt"), + sub("/subs/three.srt", None, "three.srt"), + ]), + 3, + "the palette" + ); + let mut caches = SessionCaches { + fps: session.meta().frame_rate, + proxies_on: session.proxies(), + auto_proxies_on: session.auto_proxies(), + }; + // The last row picked, which is where a click on it leaves the pick. + let pick = 2; + let picked = sub_pick_name(session.subtitles(), pick).expect("a name for the pick"); + + // The row *above* it goes, through the removal door's own fixup. + session + .remove_subtitles(0) + .expect("a row with nothing on it"); + let pick = sub_pick_after_removal(pick, 0, session.subtitles().len()); + assert_eq!(pick, 1, "the pick slid down with the rows"); + assert_eq!( + sub_pick_name(session.subtitles(), pick).as_deref(), + Some(picked.as_str()), + "and still names the same track" + ); + + let before = HistoryBefore::of(session.subtitles(), pick); + let out = history_step(&before, &mut caches, &mut session, PlaybackSession::undo) + .expect("the removal is a step like any other cut"); + assert_eq!(session.subtitles().len(), 3, "the palette is back"); + assert_eq!( + out.sub_track, 2, + "the row came back above the pick, so the pick moves up" + ); + assert_eq!( + sub_pick_name(session.subtitles(), out.sub_track).as_deref(), + Some(picked.as_str()), + "and still names the same track" + ); + assert_ne!( + sub_pick_name(session.subtitles(), pick).as_deref(), + Some(picked.as_str()), + "which is what the index left where it was would have named" + ); + assert!( + out.drop_sub_image, + "the drawn plate went through the pick that moved" + ); + + // ...and forward again: the removal, with the fixup it does at its own door. + let before = HistoryBefore::of(session.subtitles(), out.sub_track); + let out = history_step(&before, &mut caches, &mut session, PlaybackSession::redo) + .expect("the removal is in front of this one"); + assert_eq!( + out.sub_track, 1, + "the removal slides the pick down with the rows" + ); + assert_eq!( + sub_pick_name(session.subtitles(), out.sub_track).as_deref(), + Some(picked.as_str()) + ); + assert!(out.drop_sub_image, "and the plate goes with it"); +} + +/// The app-level write-back of a history step is not reachable from this binary +/// -- `Player` needs a `TestAppContext` this one has none of -- so the wiring is +/// pinned where it can be read: both keyboard doors route through +/// [`Player::step_history`], and its body still keeps the three session caches +/// and the pick, and still drops the plate. What those values *are* is pinned +/// against a real session by the two tests above ([`history_step`] is the free +/// function they drive); this is the copy back into the window's own fields, +/// which no test can call. +#[test] +fn a_history_step_still_takes_its_settings_and_its_pick_back_up() { + let actions = src_text("player/actions.rs"); + for needle in [ + "self.step_history(PlaybackSession::undo);", + "self.step_history(PlaybackSession::redo);", + ] { + assert!( + actions.contains(needle), + "a history door stopped routing through Player::step_history: {needle}" + ); + } + let body = fn_body("step_history"); + // The state the step is asked about, and the answer taken back up: every one + // of these deleted leaves a cache or the pick stale for the next cut, the + // next frame count, or the next repaint. + for needle in [ + "let mut caches = SessionCaches {", + "HistoryBefore::of(", + "self.fps = caches.fps;", + "self.proxies_on = caches.proxies_on;", + "self.auto_proxies_on = caches.auto_proxies_on;", + "self.sub_track = outcome.sub_track;", + "if outcome.drop_sub_image {", + "self.sub_image = None;", + "self.reset_after_reseek();", + ] { + assert!( + body.contains(needle), + "Player::step_history no longer carries `{needle}` -- a history step \ + leaves it behind (the app suite cannot see this: it has no \ + TestAppContext to call the door)" + ); + } +} + /// The oracle side of trim-to-playhead (debt #42): needs a subject cut *and* /// the playhead actually resting on it, unlike the nudge pair above it which /// only needs a cut -- the "spot" a keyless drag would snap to has to be on @@ -2058,11 +2254,9 @@ fn a_track_can_be_added_dropped_on_edited_and_taken_back() { // A library row let go over that row: the same door the Add button // uses, told which lane it was let go over. let path = session.sources()[0].path.clone(); - assert!( - session - .place_stream_at(1.0, &path, 0, Some(v2)) - .expect("its own file is on this timeline") - ); + assert!(session + .place_stream_at(1.0, &path, 0, Some(v2)) + .expect("its own file is on this timeline")); assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2"); assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead"); // ...with the sound it came with, on the row of its own the drop added: @@ -2149,22 +2343,18 @@ fn a_selection_drag_moves_every_pick_by_the_same_delta() { // clip0 on V1 at the fixture's own start; clip1 on V1 ten seconds in, // appended to the open bed and rippling nothing. - assert!( - session - .place_stream_at(10.0, &second, 0, None) - .expect("av2 is on this timeline") - ); + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); let clip0 = session.lane_clips(Lane::V1)[0]; let clip1 = session.lane_clips(Lane::V1)[1]; assert_eq!((clip0.start, clip1.start), (0, 300)); // clipC on a second video row, well past both of the above. let v2 = session.add_lane(LaneKind::Video); - assert!( - session - .place_stream_at(20.0, &path, 0, Some(v2)) - .expect("test_av.mp4 is on this timeline") - ); + assert!(session + .place_stream_at(20.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); let clip_c = session.lane_clips(v2)[0]; assert_eq!(clip_c.start, 600); @@ -2217,28 +2407,22 @@ fn a_selection_drag_refuses_as_one_set_when_any_pick_cannot_land() { session.import(&asset("test_av2.mp4")).expect("av2 matches"); let second = session.sources()[1].path.clone(); - assert!( - session - .place_stream_at(10.0, &second, 0, None) - .expect("av2 is on this timeline") - ); + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); let clip0 = session.lane_clips(Lane::V1)[0]; let clip1 = session.lane_clips(Lane::V1)[1]; let v2 = session.add_lane(LaneKind::Video); - assert!( - session - .place_stream_at(0.0, &path, 0, Some(v2)) - .expect("test_av.mp4 is on this timeline") - ); + assert!(session + .place_stream_at(0.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); let clip_c = session.lane_clips(v2)[0]; // A clip clip1 is not picked, blocking the road on V2 the drag is about // to try: clip1 dragged onto V2 lands its head inside this one. - assert!( - session - .place_stream_at(10.0, &second, 0, Some(v2)) - .expect("av2 is on this timeline") - ); + assert!(session + .place_stream_at(10.0, &second, 0, Some(v2)) + .expect("av2 is on this timeline")); let blocker = session.lane_clips(v2)[1]; assert_eq!(blocker.start, 300); @@ -2293,20 +2477,16 @@ fn a_three_pick_copy_paste_preserves_gaps_and_lane_assignment() { session.import(&asset("test_av2.mp4")).expect("av2 matches"); let second = session.sources()[1].path.clone(); - assert!( - session - .place_stream_at(10.0, &second, 0, None) - .expect("av2 is on this timeline") - ); + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); let clip0 = session.lane_clips(Lane::V1)[0]; let clip1 = session.lane_clips(Lane::V1)[1]; let v2 = session.add_lane(LaneKind::Video); - assert!( - session - .place_stream_at(20.0, &path, 0, Some(v2)) - .expect("test_av.mp4 is on this timeline") - ); + assert!(session + .place_stream_at(20.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); let clip_c = session.lane_clips(v2)[0]; // Copied in click order, out of the lanes each was clicked in -- exactly @@ -2354,20 +2534,16 @@ fn a_colliding_set_paste_refuses_whole() { session.import(&asset("test_av2.mp4")).expect("av2 matches"); let second = session.sources()[1].path.clone(); - assert!( - session - .place_stream_at(10.0, &second, 0, None) - .expect("av2 is on this timeline") - ); + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); let clip0 = session.lane_clips(Lane::V1)[0]; let clip1 = session.lane_clips(Lane::V1)[1]; let v2 = session.add_lane(LaneKind::Video); - assert!( - session - .place_stream_at(20.0, &path, 0, Some(v2)) - .expect("test_av.mp4 is on this timeline") - ); + assert!(session + .place_stream_at(20.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); let clip_c = session.lane_clips(v2)[0]; let items = [(Lane::V1, clip0), (Lane::V1, clip1), (v2, clip_c)]; @@ -2422,11 +2598,9 @@ fn a_grouped_clip_on_an_added_lane_closes_its_hole_with_its_caption() { let (mut session, sub_lane) = with_subtitle_lane(); let v2 = session.add_lane(LaneKind::Video); let path = session.sources()[0].path.clone(); - assert!( - session - .place_stream_at(0.0, &path, 0, Some(v2)) - .expect("its own file is on this timeline") - ); + assert!(session + .place_stream_at(0.0, &path, 0, Some(v2)) + .expect("its own file is on this timeline")); session .place_sub(sub_lane, 0, one_second(0)) .expect("the caption goes down"); @@ -2486,20 +2660,38 @@ fn a_source_is_only_ever_asked_for_its_peaks_once() { .collect::>() }; let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new(); - assert_eq!(unseen_sources(&sources, &waves), keys(&sources)); + assert_eq!( + unseen_sources(&sources, &waves, std::time::Instant::now()), + keys(&sources) + ); // The entry goes in when the decode *starts*, so the sixty repaints a // second that happen while it runs must not start it again -- which is // what this asserts about a key whose value is not an answer yet. waves.insert((a.clone(), 0), Wave::Loading); assert_eq!( - unseen_sources(&sources, &waves), + unseen_sources(&sources, &waves, std::time::Instant::now()), keys(&sources[1..]), "the file's other stream is a key of its own" ); // A file with no audio is an answer like any other: never re-asked. waves.insert((a, 1), Wave::Silent); waves.insert((b.clone(), 0), Wave::Silent); - assert!(unseen_sources(&sources, &waves).is_empty()); + assert!(unseen_sources(&sources, &waves, std::time::Instant::now()).is_empty()); + // A decode that *failed* is not an answer: the reason may have gone away + // (the file was still being copied when it arrived), so it is asked again + // -- once the stamp is older than the cooldown, so sixty repaints a second + // do not become sixty decodes. + let now = std::time::Instant::now(); + waves.insert((b.clone(), 0), Wave::Failed(now)); + assert!( + unseen_sources(&sources, &waves, now).is_empty(), + "a failure that just landed is not re-asked at once" + ); + assert_eq!( + unseen_sources(&sources, &waves, now + crate::subs::WAVE_RETRY), + keys(&sources[2..]), + "and is asked again once the cooldown is out" + ); // The stream probe is per *file*: the two entries of `a` ask once. let mut streams: HashMap> = HashMap::new(); assert_eq!( @@ -2802,13 +2994,21 @@ fn every_verb_the_spine_carried_is_a_right_click_row() { // Every menu is a list of actions the keyboard already reaches, so every // row can wear its chord (DESIGN §4): a row built here out of an id the // registry never files would print an empty column. - for action in MENU_ITEMS.into_iter().chain(BENCH_ITEMS).chain(heads.iter().copied()) { + for action in MENU_ITEMS + .into_iter() + .chain(BENCH_ITEMS) + .chain(heads.iter().copied()) + { assert!( ActionId::ALL.contains(&action), "{action:?} is a menu row and not a registered action" ); } - for list in [MENU_ITEMS.to_vec(), BENCH_ITEMS.to_vec(), lane_items(Lane::A1)] { + for list in [ + MENU_ITEMS.to_vec(), + BENCH_ITEMS.to_vec(), + lane_items(Lane::A1), + ] { let first = list.iter().position(|&a| destructive(a)); if let Some(first) = first { assert!( diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index b5ee76e..3620196 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -351,7 +351,7 @@ fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() { /// strip's row at the zoom boundary without the strip to show for it. #[test] fn the_scroll_strip_row_comes_and_goes_with_the_zoom() { - use crate::{SCROLL_HIT, Split, lanes_h, split_size, timeline_fixed_h, timeline_h}; + use crate::{lanes_h, split_size, timeline_fixed_h, timeline_h, Split, SCROLL_HIT}; use gpui::{px, size}; // The strip's row, and only the strip's row, is what the two faces differ @@ -398,8 +398,8 @@ fn the_scroll_strip_row_comes_and_goes_with_the_zoom() { /// on the track, the time axis's own thumb turned through a right angle. #[test] fn the_lane_thumb_is_the_visible_share_of_the_stack() { - use crate::SCROLL_THUMB_MIN; use crate::lanes_thumb; + use crate::SCROLL_THUMB_MIN; // Whole stack on screen: the track fills and there is nothing to scroll. assert_eq!(lanes_thumb(200., 104., 200., 0.), (0., 200.)); @@ -1301,7 +1301,7 @@ fn the_darkroom_subtitle_palette_drags_tracks_to_subtitle_lanes() { /// arrival order, at the end. #[test] fn a_file_subtitle_group_follows_its_own_row() { - use crate::ui::dock_stance::{Slot, source_list_order}; + use crate::ui::dock_stance::{source_list_order, Slot}; let film = PathBuf::from("/films/a.mkv"); let other = PathBuf::from("/rec/b.mp4"); let loose = PathBuf::from("/subs/late.srt"); @@ -1320,7 +1320,12 @@ fn a_file_subtitle_group_follows_its_own_row() { &[film.clone(), other.clone(), film.clone()], &[film.clone()] ), - [Slot::Media(0), Slot::Media(1), Slot::Media(2), Slot::Subs(0)], + [ + Slot::Media(0), + Slot::Media(1), + Slot::Media(2), + Slot::Subs(0) + ], ); // Nobody's `.srt`: still a top-level row, still last. assert_eq!( @@ -1366,7 +1371,9 @@ fn same_named_files_are_told_apart_on_the_metadata_line() { .collect(); let rows = library_rows(&three, &HashMap::new(), &HashMap::new(), None, |_| 90); assert_eq!( - rows.iter().map(|row| row.detail.as_str()).collect::>(), + rows.iter() + .map(|row| row.detail.as_str()) + .collect::>(), ["a", "b", ""], "twins say which folder they came out of" ); @@ -1379,7 +1386,9 @@ fn same_named_files_are_told_apart_on_the_metadata_line() { .collect(); let rows = library_rows(&twins, &HashMap::new(), &HashMap::new(), None, |_| 90); assert_eq!( - rows.iter().map(|row| row.detail.as_str()).collect::>(), + rows.iter() + .map(|row| row.detail.as_str()) + .collect::>(), ["#1", "#2"], "one folder, one stem: arrival order tells them apart" ); @@ -1483,6 +1492,45 @@ fn removing_a_subtitle_row_carries_the_pick_with_it() { assert_eq!(sub_pick_after_removal(0, 0, 0), 0); } +/// A `^z` moves rows without saying which one moved, so the pick is followed by +/// what it *names* ([`sub_pick_after_restore`]) rather than by its index: the +/// same three rows as the removal test above, restored instead of taken away, +/// where the index is the wrong answer in the first case and the right one in +/// the second. +#[test] +fn a_restored_palette_carries_the_pick_by_what_it_names() { + let palette = [ + sub("/films/a.mkv", Some(1), "eng"), + sub("/films/a.mkv", Some(2), "fre"), + sub("/films/a.mkv", Some(3), "ger"), + ]; + // The pick on "ger" at index 1 of the two rows a removal of the first left. + let short = [palette[1].clone(), palette[2].clone()]; + let picked = SubPickKey::of(&short, 1).expect("a row the pick names"); + assert_eq!( + sub_pick_after_restore(1, Some(&picked), &palette), + 2, + "the row above it came back" + ); + // The row that came back *below* the pick leaves it where it was. + let short = [palette[0].clone(), palette[1].clone()]; + let picked = SubPickKey::of(&short, 1).expect("a row the pick names"); + assert_eq!( + sub_pick_after_restore(1, Some(&picked), &palette), + 1, + "a row after it is not its business" + ); + // The picked row itself gone from the restored palette: the old index + // clamped into it, which is the removal door's own fallback. + let picked = SubPickKey::of(&palette, 2).expect("a row the pick names"); + assert_eq!(sub_pick_after_restore(2, Some(&picked), &palette[..2]), 1); + assert_eq!( + sub_pick_after_restore(0, None, &[]), + 0, + "an emptied palette is a state, not a panic" + ); +} + /// The same claim from the click's end, on the order imports actually /// arrive in: two films opened one after the other and an `.srt` dropped /// last interleave in the flat list, and the display reorders them. What a @@ -1707,7 +1755,11 @@ fn darkroom_lane_header_verbs_are_targeted_and_visible() { // `overlays.rs` routes those rows through the same `act_lane` door the // head's buttons used. let bench = src_text("ui/bench_stance.rs"); - for gone in ["\"bench-mix-lane\"", "\"bench-remove-lane\"", "lane.{}.remove"] { + for gone in [ + "\"bench-mix-lane\"", + "\"bench-remove-lane\"", + "lane.{}.remove", + ] { assert!(!bench.contains(gone), "the lane head still wears {gone}"); } for door in ["\"bench-show-sub-lane\"", "this.show_sub_lane(lane, cx)"] { @@ -1746,8 +1798,8 @@ fn darkroom_lane_header_verbs_are_targeted_and_visible() { fn a_dragged_divider_stops_before_either_panel_disappears() { use crate::ui::theme::INSPECTOR_MIN_W; use crate::{ - SIDE_MAX_FRAC, SPLIT_W, Split, TIMELINE_MAX_SHARE, TOOLBAR_H, inspector_w, library_w, - split_drag_size, split_size, timeline_fixed_h, timeline_h, + inspector_w, library_w, split_drag_size, split_size, timeline_fixed_h, timeline_h, Split, + SIDE_MAX_FRAC, SPLIT_W, TIMELINE_MAX_SHARE, TOOLBAR_H, }; use gpui::{point, px, size}; @@ -1867,7 +1919,7 @@ fn a_dragged_divider_stops_before_either_panel_disappears() { fn the_darkroom_seams_stop_before_either_side_disappears() { use crate::ui::theme::INSPECTOR_MIN_W; use crate::{ - BENCH_MIN_H, SIDE_MAX_FRAC, SPLIT_W, Split, split_bounds, split_drag_size, split_size, + split_bounds, split_drag_size, split_size, Split, BENCH_MIN_H, SIDE_MAX_FRAC, SPLIT_W, }; use gpui::{point, px, size}; @@ -1926,9 +1978,9 @@ fn the_darkroom_seams_stop_before_either_side_disappears() { /// ~2px at the old `BENCH_MIN_H = 80.`). #[test] fn both_default_lanes_fit_the_bench_at_its_floor() { - use crate::BENCH_MIN_H; - use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H, row_h}; + use crate::ui::bench_stance::{row_h, LANE_MIN_H, ROW_GAP, RULER_H}; use crate::ui::stance::BENCH_CHROME_H; + use crate::BENCH_MIN_H; let box_h = BENCH_MIN_H - BENCH_CHROME_H; let avail = box_h - RULER_H - ROW_GAP; @@ -1968,9 +2020,9 @@ fn both_default_lanes_fit_the_bench_at_its_floor() { /// painted bounds back, so it stays geometry-only, same as its neighbours. #[test] fn the_whole_bench_stack_fits_its_own_floor_with_the_ledger_seam_clear() { - use crate::BENCH_MIN_H; use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H}; use crate::ui::stance::BENCH_CHROME_H; + use crate::BENCH_MIN_H; const BENCH_BORDER_T: f32 = 1.; const BENCH_PY_TOP: f32 = 4.; @@ -2040,9 +2092,9 @@ fn a_lane_row_fits_what_its_own_head_draws() { #[test] fn a_saved_seam_survives_a_reload() { use crate::{ - BENCH_MIN_H, SIDE_MAX_FRAC, Split, Splits, load_stance_splits_from, save_stance_splits_to, + load_stance_splits_from, save_stance_splits_to, Split, Splits, BENCH_MIN_H, SIDE_MAX_FRAC, }; - use gpui::{Pixels, Size, px, size}; + use gpui::{px, size, Pixels, Size}; let dir = engine::scratch::Scratch::dir("edith-stance-splits"); let path = dir.join("stance-splits"); @@ -2085,7 +2137,7 @@ fn a_saved_seam_survives_a_reload() { /// drag that never started (`None`) owes nothing. #[test] fn only_the_persisted_seams_owe_a_save_when_a_drag_loses_the_window() { - use crate::{Split, player::timeline_edit::split_drag_owes_save}; + use crate::{player::timeline_edit::split_drag_owes_save, Split}; assert!(split_drag_owes_save(Some(Split::Dock))); assert!(split_drag_owes_save(Some(Split::Bench))); @@ -2099,8 +2151,8 @@ fn only_the_persisted_seams_owe_a_save_when_a_drag_loses_the_window() { /// `load_stance_splits`'s doc comment promises. #[test] fn a_missing_stance_splits_file_leaves_every_region_at_its_default() { - use crate::{Split, load_stance_splits_from}; - use gpui::{Pixels, Size, px, size}; + use crate::{load_stance_splits_from, Split}; + use gpui::{px, size, Pixels, Size}; let dir = engine::scratch::Scratch::dir("edith-stance-splits-missing"); let window: Size = size(px(1280.), px(720.)); @@ -2182,13 +2234,7 @@ fn the_stance_renders_its_five_regions_in_the_documented_order() { // Open paren only, no close: DESIGN §12 steps 3 and 4 hand most of the // regions player/window state to read, so their call sites carry // arguments now. Order is what this asserts, not arity. - let calls = [ - "screen(", - "time_band(", - "bench(", - "ledger(", - "dock(", - ]; + let calls = ["screen(", "time_band(", "bench(", "ledger(", "dock("]; let composed: Vec = calls .iter() .map(|c| { @@ -2662,12 +2708,13 @@ fn every_action_has_a_darkroom_widget_home_or_explicit_owner() { text.lines() .filter(|l| !l.contains("=> format!(\"{full} (global)\")")) .any(|line| { - line.match_indices(&format!("ActionId::{name}")).any(|(i, m)| { - !line[i + m.len()..] - .chars() - .next() - .is_some_and(|c| c.is_alphanumeric() || c == '_') - }) + line.match_indices(&format!("ActionId::{name}")) + .any(|(i, m)| { + !line[i + m.len()..] + .chars() + .next() + .is_some_and(|c| c.is_alphanumeric() || c == '_') + }) }) } let darkroom = [ @@ -2946,7 +2993,7 @@ fn the_bench_answers_a_wheel_notch_anywhere_over_it() { /// kept beside the first ([`Splits::clear`]). #[test] fn a_double_pressed_divider_forgets_the_size_it_was_dragged_to() { - use crate::layout::{Split, Splits, split_size}; + use crate::layout::{split_size, Split, Splits}; use gpui::{px, size}; let window = size(px(1280.), px(720.)); @@ -3007,7 +3054,8 @@ fn the_seam_paints_nothing_until_a_pointer_finds_it() { // gets after it no longer needs it (a `bench=207` -- a press with no // drag in it -- beside a dragged `dock=277`). assert!( - body.find(".group(group.clone())").expect("the band's group") + body.find(".group(group.clone())") + .expect("the band's group") < body.find("border_t_1()").expect("the hairline"), "the hairline is painted outside the band: {body}" ); @@ -3030,13 +3078,12 @@ fn the_bench_seam_reaches_no_further_than_every_other_seam() { ); } - /// The clamp table, driven: the seam refuses exactly two things, and neither /// is anywhere near where a hand drags. Measured live at 2560x1440 -- /// `bench=105` at the floor, `bench=1164` at the ceiling. #[test] fn the_bench_seam_stops_at_its_floor_and_its_ceiling() { - use crate::{BENCH_MIN_H, Split, split_bounds, split_size}; + use crate::{split_bounds, split_size, Split, BENCH_MIN_H}; use gpui::{px, size}; let window = size(px(2560.), px(1440.)); @@ -3065,8 +3112,11 @@ fn the_bench_seam_stops_at_its_floor_and_its_ceiling() { fn the_lane_bed_clips_its_clips_at_the_pinned_heads() { let src = src_text("ui/bench_stance.rs"); let start = src.find(r#".id(("bench-bed""#).expect("the bed"); - let bed = - &src[start..start + src[start..].find(".bg(rgb(DARK_CANVAS()))").expect("its fill")]; + let bed = &src[start + ..start + + src[start..] + .find(".bg(rgb(DARK_CANVAS()))") + .expect("its fill")]; assert!( bed.contains(".overflow_hidden()"), "the bed lets its clips paint outside itself, straight over the \ @@ -3130,7 +3180,10 @@ fn a_source_row_shows_its_name_before_anything_else() { "the metadata line no longer drops the decoder seat" ); let usage = &dock[dock.find("fn usage_line(").expect("the usage line")..start]; - assert!(!usage.contains("use{}"), "the metadata line still counts uses"); + assert!( + !usage.contains("use{}"), + "the metadata line still counts uses" + ); // DESIGN §8: the permanent footer telling the editor how to use a list // ("drag · ↵ add · double-click plays") is instructional copy and is gone. assert!( @@ -3183,7 +3236,10 @@ fn every_dock_body_mounts_the_ring_it_is_standing_in_for() { "the dock's key handler stops a stroke outside its tab/escape branches" ); for branch in ["is_focus_cycle_key(key)", "is_focus_exit_key(key)"] { - assert!(body.contains(branch), "{branch} left the dock's key handler"); + assert!( + body.contains(branch), + "{branch} left the dock's key handler" + ); } } @@ -3299,7 +3355,10 @@ fn a_room_ghost_wears_no_chord_that_repeats_its_name() { fn the_ledger_carries_the_rooms_four_verbs_and_no_rail_remains() { let src = src_text("ui/stance.rs"); for gone in ["stance-spine", "spine_stance", "SPINE_W", "fn spine("] { - assert!(!src.contains(gone), "the rail is still in the stance: {gone}"); + assert!( + !src.contains(gone), + "the rail is still in the stance: {gone}" + ); } let ledger = &src[src.find("fn ledger(").expect("the ledger strip") ..src.find("/// The dock:").expect("the dock frame")]; @@ -3341,8 +3400,8 @@ fn the_ledger_carries_the_rooms_four_verbs_and_no_rail_remains() { /// deletion. #[test] fn select_all_left_the_ruler_for_the_rulers_own_menu() { - use crate::ActionId; use crate::menus::BENCH_ITEMS; + use crate::ActionId; let bench = src_text("ui/bench_stance.rs"); for gone in ["bench-select-all", "select_all_band", "SELECT_ALL_PAD"] { assert!(!bench.contains(gone), "the ruler still carries {gone}"); @@ -3431,7 +3490,10 @@ fn one_name_per_source_one_stem_helper_and_one_save_door() { // a path with no name at all still reads as something. use crate::files::{file_name, stem}; use std::path::Path; - assert_eq!(stem(Path::new("/x/he_is_not_the_only_one.mp4")), "he_is_not_the_only_one"); + assert_eq!( + stem(Path::new("/x/he_is_not_the_only_one.mp4")), + "he_is_not_the_only_one" + ); assert_eq!(stem(Path::new("/x/untitled")), "untitled"); assert_eq!(stem(Path::new("/x/a.b.edith")), "a.b"); assert_eq!(stem(Path::new("/")), file_name(Path::new("/"))); @@ -3461,7 +3523,6 @@ fn the_ruler_plate_shows_the_timecode_only_while_a_scrub_is_live() { ); } - /// The band overflowed its own column at 1280x720 (`$EDITH_HITMAP`: /// `action.Export x=1113 w=80` with the column ending at x=995, the contact /// strip measured `w=0`), so the Export chip was invisible under the dock and @@ -3471,8 +3532,14 @@ fn the_ruler_plate_shows_the_timecode_only_while_a_scrub_is_live() { #[test] fn the_time_band_never_paints_outside_its_own_column() { let src = src_text("ui/timeband_stance.rs"); - let start = src.find(r#".id("stance-time-band-row")"#).expect("the band row"); - let row = &src[start..start + src[start..].find(".child(hero_timecode(").expect("the timecode")]; + let start = src + .find(r#".id("stance-time-band-row")"#) + .expect("the band row"); + let row = &src[start + ..start + + src[start..] + .find(".child(hero_timecode(") + .expect("the timecode")]; assert!( row.contains(".overflow_hidden()"), "the band row lets its children paint (and be clicked) under the dock: {row}" @@ -3518,9 +3585,16 @@ fn the_band_sheds_its_chords_and_nothing_else() { fn every_ghost_in_the_time_band_carries_a_full_hit_area() { let src = src_text("ui/timeband_stance.rs"); let start = src.find("fn ghost(").expect("the band's ghost"); - let ghost = &src[start..start + src[start..].find(".child(glyph.into())").expect("its glyph")]; + let ghost = &src[start + ..start + + src[start..] + .find(".child(glyph.into())") + .expect("its glyph")]; for needle in [".min_w(px(HIT_MIN))", ".min_h(px(HIT_MIN))"] { - assert!(ghost.contains(needle), "the band's ghost lost {needle}: {ghost}"); + assert!( + ghost.contains(needle), + "the band's ghost lost {needle}: {ghost}" + ); } assert!(HIT_MIN >= 24.); } @@ -3532,8 +3606,15 @@ fn every_ghost_in_the_time_band_carries_a_full_hit_area() { #[test] fn the_band_writes_no_monitoring_level() { let src = src_text("ui/timeband_stance.rs"); - for gone in ["player.volume.percent()", "fn volume_readout(", "fn volume_slider("] { - assert!(!src.contains(gone), "the monitoring cluster is back in the band: {gone}"); + for gone in [ + "player.volume.percent()", + "fn volume_readout(", + "fn volume_slider(", + ] { + assert!( + !src.contains(gone), + "the monitoring cluster is back in the band: {gone}" + ); } } @@ -3552,7 +3633,11 @@ fn transport_verbs_differ_by_shape_not_only_by_chord() { let mut seen = shapes.to_vec(); seen.sort(); seen.dedup(); - assert_eq!(seen.len(), shapes.len(), "two transport verbs share one glyph: {shapes:?}"); + assert_eq!( + seen.len(), + shapes.len(), + "two transport verbs share one glyph: {shapes:?}" + ); } /// DESIGN §6: "the cut readout is the odometer". Keyed off the selection it @@ -3745,7 +3830,9 @@ fn the_export_section_is_four_rows_and_no_fifth() { .find("fn export_section(") .expect("the export section"); let body = &source[start..]; - let end = body.find("\n/// The page itself").expect("the page's render fn"); + let end = body + .find("\n/// The page itself") + .expect("the page's render fn"); let body = &body[..end]; let rows = [ "settings-export-picture", @@ -3760,10 +3847,16 @@ fn the_export_section_is_four_rows_and_no_fifth() { // unrated one's readout, never both at once -- so the count is by label, // not by id. for label in ["\"Picture\"", "\"Sound\"", "\"Encoder\"", "\"Range\""] { - assert!(body.contains(label), "the EXPORT section has no {label} row"); + assert!( + body.contains(label), + "the EXPORT section has no {label} row" + ); } let ids = body.match_indices("\"settings-export-").count(); - assert_eq!(ids, 5, "the EXPORT section grew a row past the four (the two Sound rows are one row's two shapes)"); + assert_eq!( + ids, 5, + "the EXPORT section grew a row past the four (the two Sound rows are one row's two shapes)" + ); assert!( source.contains("what a delivery is written as"), "the section lost its head" @@ -3780,7 +3873,7 @@ fn the_export_section_is_four_rows_and_no_fifth() { /// cannot write, because [`Player::set_format`] would only refuse it back. #[test] fn the_picture_row_cycles_codec_and_container_together_and_skips_a_refusal() { - use crate::ui::settings_stance::{PICTURE_CYCLE, next_picture, picture_label}; + use crate::ui::settings_stance::{next_picture, picture_label, PICTURE_CYCLE}; assert_eq!( PICTURE_CYCLE, [ @@ -4017,7 +4110,6 @@ fn no_region_root_wears_a_focus_ring() { } } - /// The user could not find the three columns (2026-09-10: "I couldn't realize /// them when I look at"), because their heads were 12px `ink3` -- the room's /// quietest type -- with a prose tail running on after each one. The page's @@ -4187,9 +4279,13 @@ fn the_settings_page_is_a_centred_modal_with_one_column_of_measure() { #[test] fn the_picture_row_tail_is_the_current_format_alone() { let source = src_text("ui/settings_stance.rs"); - let start = source.find("fn export_section(").expect("the export section"); + let start = source + .find("fn export_section(") + .expect("the export section"); let body = &source[start..]; - let body = &body[..body.find("\n/// The page itself").expect("the page's render fn")]; + let body = &body[..body + .find("\n/// The page itself") + .expect("the page's render fn")]; assert!( !body.contains("PICTURE_CYCLE"), "the Picture row walks the whole cycle to build its tail again" diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index eee46f2..6fa15d2 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -6,8 +6,8 @@ use crate::player::library::{ auto_proxies_pref_path, load_auto_proxies_pref, save_auto_proxies_pref, }; use crate::subs::{ - SUB_SIZE_RANGE, audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for, - subtitle_style_path, + audio_import_tail, load_subtitle_style, save_subtitle_style, sub_line_h_for, + subtitle_style_path, SUB_SIZE_RANGE, }; use crate::ui::preview::{bgra_to_rgba, screenshot_path}; @@ -32,8 +32,8 @@ fn an_audio_import_names_its_rate_channels_and_length() { /// stuck read and never as a frozen window. #[test] fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() { - use std::sync::Arc; use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + use std::sync::Arc; let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8)); let started = Instant::now() - Duration::from_secs(9); let mut import = Import { @@ -303,7 +303,10 @@ fn a_strand_slot_on_a_single_strand_clip_is_the_clip_s_own_colour() { // The clip's own slot is never redirected -- it is what the fallback // lands on. assert_eq!(VizSlot::Main.picked(one), VizSlot::Main); - assert_eq!(VizSlot::Strand.picked(with_viz_paint_strands(one, 2)), VizSlot::Strand); + assert_eq!( + VizSlot::Strand.picked(with_viz_paint_strands(one, 2)), + VizSlot::Strand + ); } /// A seek says nothing until it has stood: an ordinary one is a flicker and @@ -326,8 +329,8 @@ fn a_seek_says_so_only_once_it_has_stood() { /// fifty-one seconds on a 25 GB film. #[test] fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() { - use std::sync::Arc; use std::sync::atomic::Ordering::Relaxed; + use std::sync::Arc; let progress = Arc::new(engine::silence::Progress::default()); // Two hours and eight minutes, as the header claims it. progress.total.store(7680, Relaxed); @@ -757,11 +760,9 @@ fn every_codec_row_is_offered_or_says_why_not() { detail.contains("ec-vorbis"), "the row names the encoder like every other live one: {detail}" ); - assert!( - FORMATS - .into_iter() - .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra")) - ); + assert!(FORMATS + .into_iter() + .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra"))); // The destination follows the format and keeps the stem, mp4 included. assert_eq!( retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), diff --git a/crates/app/src/tests/mod.rs b/crates/app/src/tests/mod.rs index 19e70aa..ce51f9e 100644 --- a/crates/app/src/tests/mod.rs +++ b/crates/app/src/tests/mod.rs @@ -10,56 +10,55 @@ mod media; mod view; use super::{ - ACCENT_PRIMARY, AUDIO_KBPS, BG_RAISED, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, - ColorEdit, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, EQ_CURVE_STEPS, EQ_FFT, - EQ_FREQ_HIGH, - EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, - EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, EXPORT_DONE, Enable, - BPS_COARSE, BPS_FINE, BPS_MAX, BPS_MIN, EXPORT_MOMENT_H, EncoderSeat, FORMATS, Format, HEADER_H, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, - KEYS_ROW_H, KEYS_W, KeyRow, LABEL_H, LANE_H, LANES_MAX, LATE_RESYNC, LIBRARY_MAX_W, - BENCH_ITEMS, LIBRARY_MIN_W, Lane, MB_FLOOR, MENU_ITEMS, MENU_PAD, - MENU_ROW_H, MENU_W, NO_FILE, NOTICES_MAX, NumberEdit, OVERLAID, PANEL_H, RESYNC_GAP, - ROW_ITEMS, RULER_HIT_H, RowCtx, RowItem, SCROLL_NOTCH_SHARE, SILENCE_ROWS, SOURCE_TINTS, + active_lane, auto_bps, band_label, bitrate_detail, clipboard_after_remove, color_snap, + containers, destructive, enable, enable_lane, envelope, eq_card_w, eq_freq, eq_freq_label, + eq_graph_h, eq_spectrum, eq_x, eq_y, estimated_bytes, export_path, export_settings, + format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, frame_rate_ladder, + histogram, inserted_band, is_project, keymap, keys_rows, keys_rows_matching, lane_items, + lanes_h, marked, menu_at, menu_items, menu_rows_h, next_container, normalise, nothing_to_play, + notice_tone, panel_h, parse_budget, project_path, proxies_to_start, push_notice, px_below, + range_word, rate_label, retarget, row_enable, row_items, scrub_due, secs_label, should_resync, + silence_rate, size_label, snap_cue, snap_marks, snapped, source_tint, span_partner, speed_at, + sub_pick_after_removal, sub_pick_after_restore, subtitle_plan, timecode, timeline_fixed_h, + tip_may_paint, transport, typed, unseen_paths, unseen_sources, viz_held_paint, whole_take, + window_title, Clip, ColorEdit, Ctx, Enable, EncoderSeat, Format, KeyRow, Lane, NumberEdit, + RowCtx, RowItem, Source, Speed, StreamInfo, SubPickKey, Transport, VizSlot, Volume, Wave, + ACCENT_PRIMARY, AUDIO_KBPS, BENCH_ITEMS, BG_RAISED, BPS_COARSE, BPS_FINE, BPS_MAX, BPS_MIN, + COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, + EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, + EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, + EXPORT_DONE, EXPORT_MOMENT_H, FORMATS, HEADER_H, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, + KEYS_ROW_H, KEYS_W, LABEL_H, LANES_MAX, LANE_H, LATE_RESYNC, LIBRARY_MAX_W, LIBRARY_MIN_W, + MB_FLOOR, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_W, NOTICES_MAX, NO_FILE, OVERLAID, PANEL_H, + RESYNC_GAP, ROW_ITEMS, RULER_HIT_H, SCROLL_NOTCH_SHARE, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, STATUS_ERROR, STATUS_SUCCESS, STATUS_WARNING, SUB_PLAN_CHARS, - Source, Speed, StreamInfo, TIMELINE_SHARE, Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, - WAVE_COLS_MAX, Wave, ZOOM_MIN_FRAMES, active_lane, auto_bps, band_label, bitrate_detail, - clipboard_after_remove, color_snap, containers, destructive, enable, enable_lane, envelope, eq_card_w, - eq_freq, eq_freq_label, eq_graph_h, eq_spectrum, eq_x, eq_y, estimated_bytes, export_path, - export_settings, format_refusal, fps_choices, fps_label, frac_along, frac_down, - frame_at, frame_rate_ladder, histogram, inserted_band, is_project, keymap, keys_rows, keys_rows_matching, lanes_h, - lane_items, marked, menu_at, menu_items, menu_rows_h, next_container, normalise, nothing_to_play, - notice_tone, panel_h, parse_budget, project_path, range_word, proxies_to_start, push_notice, px_below, retarget, - row_enable, row_items, scrub_due, secs_label, should_resync, silence_rate, size_label, - rate_label, snap_cue, snap_marks, snapped, source_tint, span_partner, speed_at, sub_pick_after_removal, - subtitle_plan, timecode, timeline_fixed_h, tip_may_paint, - transport, typed, unseen_paths, unseen_sources, viz_held_paint, VizSlot, whole_take, - window_title, + TIMELINE_SHARE, VOLUME_W, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, ZOOM_MIN_FRAMES, }; use super::{ - ActionId, Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, IMPORT_STALL, Import, ImportStage, - Landing, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, SAMPLE_RATES, SEEK_STALL, - Scale, ScanKey, ScanPlan, SilenceScan, SubClip, View, ZOOM_OUT_MARGIN, ZOOM_STEP, arrival, - audio_rate_choices, av1_hw_warning, clip_width, clock, encoder_choices, encoder_label, + arrival, audio_rate_choices, av1_hw_warning, clip_width, clock, encoder_choices, encoder_label, eta_secs, file_name, file_uri, fit_choices, frames_of_us, full_scan_key, import_line, landing, lane_refuses, launch_queue, library_rows, live_idx, next_fit, next_resolution, note_progress, pending_fps_choices, pending_resolution_choices, px_along, read_ahead, repeats, resolution_choices, resolution_ladder, sample_rate_choices, scan_plan, seek_line, silence_cached, silence_line, slice_whole_levels, source_secs, stash_or_write, tone_choices, - tone_label, trimmed_clip, trimmed_sub, trims, unscannable, unusable, + tone_label, trimmed_clip, trimmed_sub, trims, unscannable, unusable, ActionId, Choice, Edge, + Import, ImportStage, Landing, LaneKind, Preset, Repeat, Scale, ScanKey, ScanPlan, SilenceScan, + SubClip, View, EDGE_W, ETA_SPAN, FITS, FRAME_RATES, IMPORT_STALL, PPS_DEFAULT, PPS_MIN, + RESOLUTIONS, SAMPLE_RATES, SEEK_STALL, ZOOM_OUT_MARGIN, ZOOM_STEP, }; use super::{ - SUB_BOTTOM, SUB_CUE_MIN_W, SUB_LINE_H, SUB_TEXT, Subs, carries_subtitles, cue_box, cues_at, - file_tint, is_subtitle, lang_human, sub_bottom, sub_pick_name, subtitle_detail, - subtitle_notice, subtitle_rows, subtitle_tail, subtitle_toggle_notice, walk_subtitles, + carries_subtitles, cue_box, cues_at, file_tint, is_subtitle, lang_human, sub_bottom, + sub_pick_name, subtitle_detail, subtitle_notice, subtitle_rows, subtitle_tail, + subtitle_toggle_notice, walk_subtitles, Subs, SUB_BOTTOM, SUB_CUE_MIN_W, SUB_LINE_H, SUB_TEXT, }; use engine::PlaybackSession; use engine::scale::FitPolicy; -use gpui::{Bounds, Pixels, point, px, size}; +use gpui::{point, px, size, Bounds, Pixels}; use std::collections::HashMap; diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index 0f46262..fd01558 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -891,7 +891,7 @@ fn the_zoom_button_says_how_much_is_on_the_bed() { /// lives. #[test] fn tab_cycles_dock_bench_inspector_and_wraps() { - use crate::ui::stance::{Surface, next_surface}; + use crate::ui::stance::{next_surface, Surface}; assert_eq!(next_surface(Surface::Dock, false), Surface::Bench); assert_eq!(next_surface(Surface::Bench, false), Surface::Inspector); @@ -912,7 +912,7 @@ fn tab_cycles_dock_bench_inspector_and_wraps() { /// surface being entered is always the one mounted. #[test] fn surface_wants_src_active_mounts_the_tab_before_focus_lands_on_it() { - use crate::ui::stance::{Surface, surface_wants_src_active}; + use crate::ui::stance::{surface_wants_src_active, Surface}; assert_eq!(surface_wants_src_active(Surface::Dock), Some(true)); assert_eq!(surface_wants_src_active(Surface::Inspector), Some(false)); diff --git a/crates/app/src/ui/settings_stance.rs b/crates/app/src/ui/settings_stance.rs index 0a7bea4..6127830 100644 --- a/crates/app/src/ui/settings_stance.rs +++ b/crates/app/src/ui/settings_stance.rs @@ -684,7 +684,11 @@ fn export_section(player: &Player, cx: &mut Context) -> impl IntoElement .as_ref() .and_then(|session| format_refusal(session, format)) .map(|why| (short_reason(&why).into(), INK4())); - let picture_ink = if refused_now.is_some() { INK4() } else { INK1() }; + let picture_ink = if refused_now.is_some() { + INK4() + } else { + INK1() + }; let (codec, rated) = sound_codec(format); let seat = player.encoder_seat(); let av1_gpu = seat == EncoderSeat::Hardware && matches!(format, Format::Av1 | Format::Av1Mp4); @@ -745,18 +749,25 @@ fn export_section(player: &Player, cx: &mut Context) -> impl IntoElement ) .into_any_element() })) - .child(row_chord( - "settings-export-encoder", - "Encoder", - encoder_word(seat), - "which encoder writes the picture: the GPU where this machine has a seat, or the CPU", - "g", - av1_gpu.then(|| (AV1_GPU_NOTICE.into(), NOTICE_LOOK())), - player, - cx.listener(|this, _: &ClickEvent, _, cx| { - this.cycle_encoder(cx); - }), - )) + // The encoder writes the *picture*, and the engine opens no seat for a + // song: with WAV/FLAC/MP3/Ogg picked the row would be a button that + // does nothing when pressed. The export moment mounts no row there + // either (`Format::has_video`), so this is that same rule rather than a + // third treatment. + .children(format.has_video().then(|| { + row_chord( + "settings-export-encoder", + "Encoder", + encoder_word(seat), + "which encoder writes the picture: the GPU where this machine has a seat, or the CPU", + "g", + av1_gpu.then(|| (AV1_GPU_NOTICE.into(), NOTICE_LOOK())), + player, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.cycle_encoder(cx); + }), + ) + })) // Read-only: the range is set on the timeline with the marks // themselves ([`keymap::ActionId::SetIn`]/`SetOut`), which is where a // person can see what they are marking. diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 980ba08..dfa6474 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -387,8 +387,24 @@ pub fn save( let result = std::fs::File::create(&part) .and_then(|mut f| { f.write_all(&emit( - &dir, sources, lanes, gains, subs, subtitles, eq, color, transform, resolution, - fps, tone, proxy, auto_proxy, encoder, limiter, sample_rate, playhead, + &dir, + sources, + lanes, + gains, + subs, + subtitles, + eq, + color, + transform, + resolution, + fps, + tone, + proxy, + auto_proxy, + encoder, + limiter, + sample_rate, + playhead, ))?; f.sync_all() }) @@ -810,10 +826,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } b"samplerate" if v17 => { if doc.sample_rate.is_some() || !doc.sources.is_empty() { - return Err(format!( - "line {n}: samplerate belongs once, before the sources" - ) - .into()); + return Err( + format!("line {n}: samplerate belongs once, before the sources").into(), + ); } let f = fields(rest, 1, "samplerate", n)?; let rate = number(f[0], n)?; @@ -838,9 +853,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } b"proxy" if v12 => { if !doc.sources.is_empty() { - return Err( - format!("line {n}: proxy belongs once, before the sources").into() - ); + return Err(format!("line {n}: proxy belongs once, before the sources").into()); } let f = fields(rest, 1, "proxy", n)?; doc.proxy = match f[0] { @@ -877,7 +890,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { b"encoder" if v14 => { if !doc.sources.is_empty() { return Err( - format!("line {n}: encoder belongs once, before the sources").into() + format!("line {n}: encoder belongs once, before the sources").into(), ); } let f = fields(rest, 1, "encoder", n)?; @@ -1215,7 +1228,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames), fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames), transition_out: number(f.get(11).copied().unwrap_or(b"0"), n)?.min(frames), - visualizer: number(f.get(13).copied().unwrap_or(b"0"), n)? as u8, + visualizer: flags_byte(f.get(13).copied().unwrap_or(b"0"), n)?, viz_paint: number64(f.get(14).copied().unwrap_or(b"0"), n)?, start: number(f[0], n)?, in_frame, @@ -1472,6 +1485,15 @@ fn float(field: &[u8], line: usize) -> crate::Result { } } +/// A clip's visualizer field: every bit of the byte is a flag +/// ([`crate::decode::VIZ_STYLE_FILL`]'s low bits, the fast bit, the ink +/// nibble), so a line naming one past what a byte holds is a look this +/// program does not have rather than a 300 that quietly loads as a 44. +fn flags_byte(field: &[u8], line: usize) -> crate::Result { + let n = number(field, line)?; + u8::try_from(n).map_err(|_| format!("line {line}: {n} is not a set of visualizer flags").into()) +} + fn number(field: &[u8], line: usize) -> crate::Result { match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) { Some(n) => Ok(n), @@ -1695,7 +1717,11 @@ mod tests { (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(7))]), (LaneKind::Subtitle, Vec::new()), ]; - let subs = vec![vec![], vec![], vec![caption(0, 30, Some(7)), caption(40, 10, None)]]; + let subs = vec![ + vec![], + vec![], + vec![caption(0, 30, Some(7)), caption(40, 10, None)], + ]; let bytes = super::emit( &dir, &doc().1, @@ -1917,7 +1943,10 @@ mod tests { for seat in [EncoderSeat::Hardware, EncoderSeat::Software] { let written = bytes(seat); let text = String::from_utf8_lossy(&written).to_string(); - assert!(text.contains(&format!("encoder {}\n", seat.name())), "{text}"); + assert!( + text.contains(&format!("encoder {}\n", seat.name())), + "{text}" + ); assert_eq!(parse(&written, &dir).expect("v14 parses").encoder, seat); } @@ -2622,7 +2651,10 @@ mod tests { "the fades are the clip line's last two fields" ); let back = parse(&bytes, &dir).expect("parse"); - assert_eq!(back.lanes, lanes, "the fades round trip as the very numbers"); + assert_eq!( + back.lanes, lanes, + "the fades round trip as the very numbers" + ); } /// The whole of the v19 bump, the fade test's twin: a clip's dissolve into @@ -3248,13 +3280,11 @@ mod tests { assert!(err.starts_with("line 4: clip at "), "{err}"); } // The lanes are independent, so a video line never crowds an audio one. - assert!( - parse( - b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n", - &dir - ) - .is_ok() - ); + assert!(parse( + b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n", + &dir + ) + .is_ok()); // ...and a lane may be empty as long as the other one is not. let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse"); assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty"); @@ -3457,7 +3487,10 @@ mod tests { parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes, two(Vec::new(), Vec::new()) ); - assert!(parse(b"edith 1\n", &dir).expect("a project of nothing").sources.is_empty()); + assert!(parse(b"edith 1\n", &dir) + .expect("a project of nothing") + .sources + .is_empty()); } /// Every truncation of a good file either parses or refuses; none panics. @@ -3479,4 +3512,48 @@ mod tests { "line 2: truncated % escape in the path" ); } + + /// A clip's visualizer field is a whole byte of flags, and a line naming one + /// past it used to be truncated into a look nobody chose (`300` loaded as + /// `44`, with the fast bit and the ink nibble both wrong). It is refused by + /// name now, like the resolution's bound, the sample rate's range, the tone + /// map and the encoder seat beside it. + #[test] + fn a_visualizer_byte_past_a_byte_is_refused_and_the_legal_ones_still_load() { + // The door the parser reads that field through: the low bits are the + // style, bit 3 the fast flag and the high nibble the ink, so every value a + // byte holds is a look and 256 and up is not one. + assert_eq!(flags_byte(b"0", 1).expect("zero is the plain look"), 0); + assert_eq!(flags_byte(b"255", 1).expect("the whole byte is flags"), 255); + let refused = flags_byte(b"300", 9).expect_err("300 is not a byte of flags"); + assert_eq!( + refused.to_string(), + "line 9: 300 is not a set of visualizer flags" + ); + } + + /// ...and the same field through the parser, on a document of the newest + /// dialect: the legal byte is what lands in the clip, the illegal one is the + /// refusal above rather than a truncation. + #[test] + fn a_clip_line_whose_visualizer_is_past_a_byte_loses_the_whole_load() { + let dir = PathBuf::from("/proj"); + let line = |flags: &str| { + format!( + "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 - {flags} 0\n" + ) + }; + let doc = parse(line("12").as_bytes(), &dir).expect("12 is a look"); + // The keyword is the saver's own for this dialect, so a mismatch here would + // be this test's line and not the field it is about. + assert_eq!(doc.lanes[0].1[0].visualizer, 12); + let refused = parse(line("300").as_bytes(), &dir).expect_err("300 is not a look"); + assert!( + refused + .to_string() + .contains("is not a set of visualizer flags"), + "{refused}" + ); + } } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 1ef55ad..c505f44 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -26,7 +26,7 @@ use crate::colorspace::{ColorDescription, ContentLight}; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; use crate::eq::EqParams; -use crate::project::{ +use crate::project::{ProjectSettings, Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip, }; use crate::scale::{Composer, FitPolicy}; @@ -1188,7 +1188,18 @@ impl PlaybackSession { // it, and [`Project::with_subs`] refuses one naming a row that is // not there. .with_subtitles(subtitles) - .with_subs(doc.subs)?; + .with_subs(doc.subs)? + // The header a load puts back: the canvas and rate above, which a + // save's own `resolution`/`fps` lines may have moved off the + // scaffold's, and the switches the literal below carries -- handed + // in here because they are the project's own and a door that moved + // one after this would snapshot whatever copy it holds, which until + // this line is the placeholder's. No undo step for + // [`Project::with_mix`]'s reason: a project that arrived one `z` + // from a state it was never in is a project whose first undo is a + // surprise. + .with_canvas(meta.width, meta.height, meta.frame_rate) + .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and @@ -1469,12 +1480,15 @@ impl PlaybackSession { /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows /// past `idx` move down by one: a caller holding a picked row (the export's /// subtitle pick) has to fix it up or drop it; the placements on the lanes - /// are walked down with it and need no fixing. Not an undo step, for the - /// reason [`Project::remove_subtitles`] gives -- the way back is - /// [`import_subtitles`](Self::import_subtitles), which reads a file's - /// subtitles and touches nothing else on the timeline -- and it *empties* - /// the undo history, because the steps in it name the tracks by the indexes - /// this call just changed. + /// are walked down with it and need no fixing. + /// + /// One undo step, and the reindex with it ([`Project::remove_subtitles`]'s + /// own entry): every step in the history names its tracks by index into the + /// palette, so an entry carries the palette it was taken beside its lanes -- + /// which is what lets a `z` put this row back, and every placement that + /// moved down with it. What that entry cannot bring back is the *pick*: it + /// is the caller's, and a caller holding one fixes it up or drops it + /// ([`crate::subs::sub_pick_after_restore`]). pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> { self.project.remove_subtitles(idx) } @@ -2820,11 +2834,17 @@ impl PlaybackSession { /// Says nothing about *which* films have one: a source with no stand-in /// keeps playing its own pictures either way, and one made while this is on /// is picked up at the next seek. + /// + /// One undo step ([`Project::push_settings_step`]), and the seek below is + /// what makes the undo of it land on the picture: it reopens the span + /// through [`picture_path`](Self::picture_path), which reads this switch. pub fn set_proxies(&mut self, on: bool) { if self.proxies == on { return; } + let from = self.settings_value(); self.proxies = on; + self.step_settings(from); let now = self.now(); self.seek(now); } @@ -2839,9 +2859,15 @@ impl PlaybackSession { } /// Pick the seat. Nothing to reseek and nothing to re-probe here: this - /// decides what an *export* opens, never what plays. + /// decides what an *export* opens, never what plays. One undo step, like + /// every other pick on the project. pub fn set_encoder_seat(&mut self, seat: crate::export::EncoderSeat) { + if self.encoder_seat == seat { + return; + } + let from = self.settings_value(); self.encoder_seat = seat; + self.step_settings(from); } /// The rate this project's mix was picked to run at @@ -2853,9 +2879,15 @@ impl PlaybackSession { /// Pick the mix's own rate, overriding the derived one. Nothing to reseek /// here: it takes effect at the next audio rebuild (a seek, an edit, a - /// reopen), not on the device already playing. + /// reopen), not on the device already playing. One undo step, like every + /// other pick on the project. pub fn set_sample_rate(&mut self, rate: Option) { + if self.sample_rate == rate { + return; + } + let from = self.settings_value(); self.sample_rate = rate; + self.step_settings(from); } /// Whether an imported film that wants a stand-in gets one made for it @@ -2867,8 +2899,15 @@ impl PlaybackSession { /// Make the stand-ins on import, or make none until asked. Nothing to /// reseek: this decides what is *started*, never what is decoded -- a proxy /// already in the cache is still cut on while [`Self::proxies`] is on. + /// + /// One undo step, like every other switch on the project. pub fn set_auto_proxies(&mut self, on: bool) { + if self.auto_proxies == on { + return; + } + let from = self.settings_value(); self.auto_proxies = on; + self.step_settings(from); } /// Which source `path` is, canonicalising only if it has to: a source's own @@ -2999,10 +3038,9 @@ impl PlaybackSession { /// that is not a picture -- zero either way, or past 8K, which is where the /// per-frame buffers stop being a sane thing to allocate from a keystroke. /// - /// corner-cut: not an undo step. The project resolution is not in the lane - /// snapshots [`Project::undo`] restores, so cycling it back is one more - /// keypress rather than a `z`. Upgrade path is snapshotting it beside the - /// lanes, which every existing snapshot site would then have to carry. + /// One undo step: the resolution is the project's own, so it rides in the + /// entry beside the lanes and a `z` takes the canvas back to the size it + /// was ([`Project::push_settings_step`]). pub fn set_resolution(&mut self, width: u32, height: u32) -> bool { if !crate::is_resolution(width, height) { return false; @@ -3010,8 +3048,10 @@ impl PlaybackSession { if (width, height) == (self.meta.width, self.meta.height) { return false; } + let from = self.settings_value(); self.meta.width = width; self.meta.height = height; + self.step_settings(from); self.invalidate(Dirty::Picture); true } @@ -3073,12 +3113,15 @@ impl PlaybackSession { /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate /// is refused at). /// - /// corner-cut: not an undo step, exactly as the project resolution is not -- - /// and this one *moves the frame numbers*, so the way back is picking the - /// old rate (or the media's, [`native_frame_rate`](Self::native_frame_rate)) - /// rather than a `z`, and it lands within a frame of where it started rather - /// than on it (see [`Project::retime`]). Upgrade path is the same one: the - /// project's settings snapshotted beside the lanes. + /// One undo step, and the entry it takes is the whole of the change: the + /// lanes as they were in the *old* rate's numbering, with that rate beside + /// them, so a `z` restores the two together ([`Project::retime`]). The + /// step is taken before the retime rather than after, since this is the one + /// settings door that moves the lanes the step holds. Picking the old rate + /// back is still within a frame of where it started rather than on it: the + /// *lanes* come home exactly out of the entry, and the per-source lengths + /// are the half that goes through the map twice + /// ([`PlaybackSession::adopt_settings`]). pub fn set_frame_rate(&mut self, fps: f64) -> bool { if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate { return false; @@ -3090,6 +3133,8 @@ impl PlaybackSession { let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else { return false; }; + let from = self.settings_value(); + self.project.push_settings_step(from.clone(), from); // Lengths first: the retime holds every clip inside its source's *new* // length, so a clip that played to the last frame of its file still // does rather than naming one past the end. @@ -3103,6 +3148,9 @@ impl PlaybackSession { } self.meta.frame_rate = fps; self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1); + // The copy the project keeps, now that the change has landed: what the + // next lane edit's entry carries. + self.project.mirror_settings(self.settings_value()); let now = self.now(); self.seek(now); true @@ -3511,15 +3559,19 @@ impl PlaybackSession { self.edit(Dirty::Both, |p| p.delete_in(lane, idx)) } - /// Undoes the last successful edit, and reseeks like a delete. + /// Undoes the last successful edit, and reseeks like a delete. A step on + /// the project's own settings comes back the same way: the canvas, the + /// rate and the switches are put back on the session here + /// ([`Self::adopt_settings`]), so a `z` after a resolution pick, an + /// encoder pick or a proxy switch lands exactly as one after a cut does. pub fn undo(&mut self) -> bool { - self.edit(Dirty::Both, Project::undo) + self.restored_step(Project::undo) } /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like - /// a delete. + /// a delete -- settings included, exactly as `undo` takes them back. pub fn redo(&mut self) -> bool { - self.edit(Dirty::Both, Project::redo) + self.restored_step(Project::redo) } /// Takes `path` into the **library**: it becomes a source of this session, @@ -3686,6 +3738,94 @@ impl PlaybackSession { /// policy rebuilds the picture where it stands, with the sound running /// through it untouched -- no flush, no re-open, no hole -- and an /// equalizer the other way round. + /// The project's own settings as this session has them now + /// ([`ProjectSettings`]): the canvas and the rate are `meta`'s, the + /// switches are this session's own fields, and the rendition and the + /// limiter are the project's -- two halves of one header, which is what + /// every history entry carries beside the lanes ([`Project::snapshot`]). + fn settings_value(&self) -> ProjectSettings { + ProjectSettings { + resolution: (self.meta.width, self.meta.height), + frame_rate: self.meta.frame_rate, + encoder_seat: self.encoder_seat, + sample_rate: self.sample_rate, + proxies: self.proxies, + auto_proxies: self.auto_proxies, + tone: self.project.tone(), + limiter: self.project.limiter(), + } + } + + /// One undo step for a change to the project's own settings, taken after + /// the change: `from` is the state the door found, and what the project + /// does with the two values is [`Project::push_settings_step`]'s. + fn step_settings(&mut self, from: ProjectSettings) { + let now = self.settings_value(); + self.project.push_settings_step(from, now); + } + + /// Puts the project's settings back on this session -- what a step that + /// restored them leaves for the player to take up. The canvas, the rate and + /// the switches live here, and the rendition and the limiter are the + /// project's own, already back in place by the time this runs. Every lane + /// edit's entry comes through here too and moves nothing, which is the + /// common case; the *rate* is the one that needs more than the fields, + /// because every source's frame count is held against it and the conform + /// that scaled them is not in the entry. + fn adopt_settings(&mut self) { + let s = self.project.settings_now(); + // A project nobody has handed a canvas to: a fresh [`Project`] carries + // the placeholder ([`ProjectSettings::placeholder`]) and no session is + // on one -- the entries pushed before the first settings door hold lane + // edits and that placeholder, and adopting it would zero the canvas. + if s.frame_rate <= 0.0 { + return; + } + let was = self.meta.frame_rate; + self.meta.width = s.resolution.0; + self.meta.height = s.resolution.1; + self.meta.frame_rate = s.frame_rate; + self.encoder_seat = s.encoder_seat; + self.sample_rate = s.sample_rate; + self.proxies = s.proxies; + self.auto_proxies = s.auto_proxies; + if s.frame_rate != was { + // Within a frame, like the way out ([`Self::set_frame_rate`]'s own + // caveat): the lane frame numbers came home exactly, out of the + // entry, and only the per-source lengths are re-derived through the + // map back. + let Ok(k) = Rate::from_fps(was, s.frame_rate) else { + return; + }; + for count in &mut self.counts { + *count = k.timeline_at(*count).max(1); + } + for rate in &mut self.rates { + *rate = rate.then(k); + } + self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1); + } + } + + /// [`Self::undo`] and [`Self::redo`] themselves: the project's own step, + /// and then whatever it restored for the session to take up + /// ([`Self::adopt_settings`]). Reseeks both halves, so a canvas that moved + /// is repainted and a proxy switch that flipped reopens the file. + fn restored_step(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool { + if !f(&mut self.project) { + return false; + } + // Adopted *before* the reseek below, never after it: everything the + // reseek reads is one of the settings the entry just put back -- + // `landing` the rate and the frame count, `picture_path` the switches, + // the sound the sample rate -- so a landing computed from the values + // the step *undid* lands on the wrong frame of the right project (and + // reopens the file through the switch that just went back). + self.adopt_settings(); + self.invalidate(Dirty::Both); + true + } + fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool { if !f(&mut self.project) { return false; @@ -5179,6 +5319,53 @@ mod tests { assert_eq!(next.index, first.index, "paused: same timeline position before and after"); } + /// A rate undo lands the picture where the playhead is, in the rate that + /// came *back*: the entry a pick takes carries the old numbering beside the + /// old rate, so an undo restores both and the reseek has to be computed + /// after the restore. Computed before it, the landing is the pre-undo + /// rate's reading of the post-undo project -- `now` clamps to the pre-undo + /// rate's idea of the timeline's end and the worker is handed the last + /// frame of a five-second timeline for a playhead at three seconds. + #[test] + fn a_rate_undo_reseeks_at_the_rate_it_restored() { + let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + s.set_gain(0.0); + let poll = |s: &mut PlaybackSession| -> crate::decode::Frame { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + loop { + if let Some(f) = s.try_frame() { + return f; + } + assert!(std::time::Instant::now() < deadline, "no frame within 20s"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }; + let native = s.native_frame_rate(); + s.seek(3.0); + assert_eq!(s.now(), 3.0, "the fixture is five seconds long"); + assert!(s.set_frame_rate(native * 2.0), "the rate pick"); + assert!(s.undo(), "the pick is one step"); + assert_eq!(s.meta().frame_rate, native, "the rate came back"); + assert_eq!( + s.now(), + 3.0, + "the playhead is the seconds it was, read at the rate that came back" + ); + // The worker's own landing, which is the half the clock alone cannot + // show: a frame 149 of 150 is exactly the pre-undo rate's clamp. + assert_eq!( + s.span.expect("a span for the picture").start, + secs_to_frame(3.0, native), + "the picture was asked for the playhead's own frame" + ); + let frame = poll(&mut s); + assert_eq!( + frame.index, + secs_to_frame(3.0, native), + "and that is the frame that arrived" + ); + } + /// The session's live look samples leave its history exactly where the /// press left it -- the colour-wheel drag's twin for the packed look, and /// what lets the app drive one from a pointer: `z` after a drag lands diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 66d8f51..cdeb0f9 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -116,6 +116,11 @@ pub(crate) struct SweepParts( pub(crate) usize, pub(crate) Vec<(LaneKind, Vec)>, pub(crate) Vec>, + /// The palette, which the history holds beside the lanes and an undo + /// therefore restores ([`Project::undo`]). Left out of this shape, a + /// round-trip check passed with the palette restore deleted outright. + pub(crate) Vec, + pub(crate) ProjectSettings, ); impl Speed { @@ -881,11 +886,75 @@ pub type Parts = ( /// How many undo steps a project keeps. One gesture is one step, so 100 is past /// any chain a person walks back by hand, and the oldest step is dropped rather -/// than the history growing without end: a snapshot is the whole lane list, so -/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak -/// that grows for as long as the session lasts. +/// than the history growing without end: a snapshot is the whole lane list plus +/// the palette and the project's own settings, so on a 1394-clip jumpcut +/// timeline this is a bounded ~10 MB instead of a leak that grows for as long +/// as the session lasts. const HISTORY_CAP: usize = 100; +/// The project's own settings, as one value: the header a `.edith` file carries +/// beside the edit list, and what every undo step restores beside the lanes. +/// None of it is the media's own -- the scaffolding file's picture and rate +/// ([`PlaybackSession::native`]) stay on the session and are never rolled back. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ProjectSettings { + /// The canvas every clip is composed onto: the project resolution, which a + /// clip of another size is placed onto rather than refused for. + pub(crate) resolution: (u32, u32), + /// The rate the timeline is cut at, which every clip and source is + /// conformed to ([`Project::retime`]). + pub(crate) frame_rate: f64, + /// Which encoder an export of this project opens its picture on + /// ([`crate::export::EncoderSeat`]). + pub(crate) encoder_seat: crate::export::EncoderSeat, + /// The rate the mix was picked to run at, or `None` for the one the first + /// audio source derives. + pub(crate) sample_rate: Option, + /// Whether the picture is decoded from the stand-ins ([`crate::proxy`]). + pub(crate) proxies: bool, + /// Whether a source that wants a stand-in gets one made for it as it + /// arrives ([`crate::proxy::wanted`]). + pub(crate) auto_proxies: bool, + /// Which HDR-to-SDR rendition the picture is watched and exported in. + pub(crate) tone: crate::tonemap::Preset, + /// The master limiter every lane's sound is summed through. + pub(crate) limiter: Limiter, +} + +impl ProjectSettings { + /// What a project built by hand carries before its constructor names the + /// canvas: the defaults every fresh open has -- nobody has picked stand-ins + /// (the films themselves are cut), an encoder or a mix rate, and the + /// rendition and limiter are the reference ones. Every door that builds a + /// session chains [`Project::with_canvas`] straight after, so the zero + /// canvas here is never a project anybody plays from. + fn placeholder() -> Self { + Self { + resolution: (0, 0), + frame_rate: 0.0, + encoder_seat: crate::export::EncoderSeat::default(), + sample_rate: None, + proxies: false, + auto_proxies: true, + tone: crate::tonemap::Preset::default(), + limiter: Limiter::default(), + } + } +} + +/// One undo step: the lanes, the subtitle palette and the project's own +/// settings exactly as they were before the edit that pushed it. Whole values +/// rather than the lane list alone, so an undo (or a redo) restores all three +/// together and no half of one edit can come back without the others -- which +/// is what lets a subtitle removal reindex every placement and still undo: the +/// restored palette names the very tracks the restored placements index. +#[derive(Clone, Debug)] +struct Snapshot { + lanes: Vec, + subtitles: Vec, + settings: ProjectSettings, +} + /// One gap a close-all sweep left open, with the frame it still starts on and /// the same refusal a single [`Project::gap_take_scope`] close would have said. #[derive(Clone, Debug, PartialEq, Eq)] @@ -917,32 +986,31 @@ pub struct Project { /// The same, for [`Clip::transform`]. transform: Vec, /// Snapshots pushed *before* each successful edit; `undo` pops one. The - /// whole lane list, so adding a lane undoes as well. Bounded by - /// [`HISTORY_CAP`]: at the cap the oldest step goes. - history: Vec>, - /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by + /// whole lane list, the subtitle palette and the project's own settings, + /// so adding a lane undoes as well and so does picking a resolution. Bounded + /// by [`HISTORY_CAP`]: at the cap the oldest step goes. + history: Vec, + /// Snapshots `undo` has stepped past; `redo` pops one. Cleared by /// [`Project::snapshot`], since a fresh edit invalidates whatever branch /// the undone steps came from. Not saved to `.edith`, matching `history`. - redo: Vec>, + redo: Vec, /// Never rolled back by an undo: an id retired by an undone split must not /// come back and group two clips that were never together. next_link: u32, /// The subtitle tracks this timeline shows, in the order they were added. - /// Not in the lane list and not in the history snapshots, for the reason - /// the limiter is not: which subtitles a project carries is a setting on - /// it, and it is saved as a *reference* to the file the cues came out of - /// ([`crate::subtitle`]). + /// Saved as a *reference* to the file the cues came out of + /// ([`crate::subtitle`]). In the history snapshots since the widened + /// [`Snapshot`]: a placement names a track by index into this list, so a + /// removal that reindexes the placements can only undo together with the + /// palette it removed the row from. subtitles: Vec, - /// The master limiter every lane's sound is summed *through* - /// ([`Project::limiter`]). Off by default, and not in the lane list, which - /// is what the history snapshots hold: it is a setting on the mix, like the - /// project's resolution is a setting on the picture, and neither is an undo - /// step. - limiter: Limiter, - /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and - /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like - /// the resolution, and not in the lane snapshots for the same reason. - tone: crate::tonemap::Preset, + /// The project's own settings ([`ProjectSettings`]) -- the canvas, the + /// rate, the proxies switches, the encoder seat, the mix rate, the + /// rendition and the limiter. In every snapshot, so each of them undoes + /// like a lane edit: they are the header of the project's own `.edith` + /// file, not this machine's, and a pick a ctrl+z could not take back + /// would be the one setting with no way out. + settings: ProjectSettings, } impl Project { @@ -980,8 +1048,7 @@ impl Project { redo: Vec::new(), next_link: 1, subtitles: Vec::new(), - limiter: Limiter::default(), - tone: crate::tonemap::Preset::default(), + settings: ProjectSettings::placeholder(), } } @@ -1124,8 +1191,7 @@ impl Project { redo: Vec::new(), next_link, subtitles: Vec::new(), - limiter: Limiter::default(), - tone: crate::tonemap::Preset::default(), + settings: ProjectSettings::placeholder(), }) } @@ -1400,7 +1466,8 @@ impl Project { /// different file. [`PlaybackSession::remove_source`] hands back the index /// that went for exactly that. /// - /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a + /// corner-cut: this retires the undo stack. `history` holds the lanes, the + /// subtitle palette and the project's own settings -- no source list -- so a /// snapshot older than the removal can name the very source being removed /// (delete a file's clips, then remove the file) and restoring it would /// point a clip at an entry that is gone. The upgrade path is snapshotting @@ -1679,14 +1746,44 @@ impl Project { data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); } } - self.limiter = limiter.with_ceiling(limiter.ceiling_db); + self.settings.limiter = limiter.with_ceiling(limiter.ceiling_db); self } /// The HDR rendition a *load* puts back -- the same door /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason. pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self { - self.tone = preset; + self.settings.tone = preset; + self + } + + /// The canvas and rate a *load* or a fresh open names -- the project + /// resolution and the rate every clip is counted in. The same door + /// [`with_mix`](Project::with_mix) is, and no undo step for the same + /// reason: a project that arrives one undo away from a state it was never + /// in is a project whose first ctrl+z is a surprise. + pub fn with_canvas(mut self, width: u32, height: u32, frame_rate: f64) -> Self { + self.settings.resolution = (width, height); + self.settings.frame_rate = frame_rate; + self + } + + /// The saved switches a *load* puts back: whether the picture is cut on + /// the stand-ins, whether new ones are made on arrival, which encoder an + /// export opens, and the rate the mix was picked to run at. The load half + /// of [`set_proxies`](Project::set_proxies) and its siblings, and no undo + /// step for [`with_mix`](Project::with_mix)'s reason. + pub fn with_switches( + mut self, + proxies: bool, + auto_proxies: bool, + encoder_seat: crate::export::EncoderSeat, + sample_rate: Option, + ) -> Self { + self.settings.proxies = proxies; + self.settings.auto_proxies = auto_proxies; + self.settings.encoder_seat = encoder_seat; + self.settings.sample_rate = sample_rate; self } @@ -1694,21 +1791,18 @@ impl Project { /// project setting, not a clip's: one picture, one look /// ([`crate::tonemap::Preset`]). pub fn tone(&self) -> crate::tonemap::Preset { - self.tone + self.settings.tone } /// Sets it. `false` for the one already in force, which is what keeps a - /// re-pick of the current rendition from costing a reseek. - /// - /// corner-cut: not an undo step, for the reason the limiter and the project - /// resolution are not -- it is not in the lane list the history snapshots. - /// Upgrade path is the same one: a history entry holding the project's own - /// settings beside the lanes. + /// re-pick of the current rendition from costing a reseek. One undo step + /// like every other project-setting pick. pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool { - if self.tone == preset { + if self.settings.tone == preset { return false; } - self.tone = preset; + self.snapshot(); + self.settings.tone = preset; true } @@ -1763,16 +1857,14 @@ impl Project { /// [`remove_source`](Project::remove_source) refuses the same way for the /// same silent corruption. /// - /// corner-cut: not an undo step, for the reason the limiter is not -- the - /// history snapshots hold the lane list and subtitles are not on it - /// ([`Project::subtitles`]). The inverse is putting the file's tracks back - /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own - /// door, which reads the subtitles of a file and nothing else -- and not a - /// ctrl+z; the upgrade path is the same one the limiter has: a history - /// entry holding the project's own settings beside the lanes. The history - /// is *cleared* rather than kept, as a source removal clears it: the - /// snapshots hold the indexes as they were before the reindex, so an undo - /// into one would put every placement past `idx` on the wrong track. + /// One undo step, and the reindex with it: every placement names a track + /// by index into the palette ([`crate::subtitle`]), so a removal that + /// renumbers them can only come back together with the palette it took + /// the row from -- which is what the history entry holds, beside the + /// lanes it also carries ([`Snapshot`]). The inverse, for a caller that + /// wants the file's tracks back, is [`crate::PlaybackSession::import_subtitles`] + /// -- the panel's own door, which reads the subtitles of a file and + /// nothing else. pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> { if idx >= self.subtitles.len() { return Err(format!("there is no subtitle track {idx} to remove").into()); @@ -1796,13 +1888,13 @@ impl Project { ) .into()); } + self.snapshot(); self.subtitles.remove(idx); for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) { if s.track > idx { s.track -= 1; } } - self.history.clear(); Ok(()) } @@ -2252,25 +2344,34 @@ impl Project { /// The master limiter the mix is summed through. A project setting, not a /// clip's and not a lane's: there is one mix. pub fn limiter(&self) -> Limiter { - self.limiter + self.settings.limiter } /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false` - /// for a setting already in force. - /// - /// corner-cut: not an undo step, for the reason the project resolution is not - /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the - /// lane list the history snapshots. Upgrade path is a history entry that - /// holds the mix settings beside the lanes. + /// for a setting already in force. One undo step like every other + /// project-setting pick. pub fn set_limiter(&mut self, limiter: Limiter) -> bool { let limiter = limiter.with_ceiling(limiter.ceiling_db); - if self.limiter == limiter { + if self.settings.limiter == limiter { return false; } - self.limiter = limiter; + self.snapshot(); + self.settings.limiter = limiter; true } + + + + + + + + + + + + /// What the clip at `idx` of `lane` plays through, or `None` for one that /// plays flat (and for an index that is not there) -- what a feeder and an /// export ask before they build an [`crate::eq::EqState`]. @@ -4948,6 +5049,36 @@ impl Project { self.redo.len() } + /// The project's own settings as they stand ([`ProjectSettings`]) -- what an + /// undo entry holds beside the lanes, and what the session reads back after + /// one is restored ([`crate::PlaybackSession::undo`]). + pub(crate) fn settings_now(&self) -> ProjectSettings { + self.settings.clone() + } + + /// One undo step for a change to the project's own settings: `from` is the + /// state the change is from and `now` the one it leaves behind. The entry + /// pushed holds `from`, while the copy kept here is `now` -- so the next + /// lane edit's own entry carries the canvas and the rate really in force + /// rather than the ones before the pick. The lanes the entry holds are the + /// ones in place at the call: a settings door leaves them alone and may + /// take this step after its change, and one that moves them + /// ([`Project::retime`] on a rate change) takes it before, with `now` equal + /// to `from`, mirroring the new state afterwards + /// ([`Project::mirror_settings`]). + pub(crate) fn push_settings_step(&mut self, from: ProjectSettings, now: ProjectSettings) { + self.settings = from; + self.snapshot(); + self.settings = now; + } + + /// Keeps `now` as this project's copy of its own settings, without a step: + /// the second half of a settings door that had to take its step before the + /// change. + pub(crate) fn mirror_settings(&mut self, now: ProjectSettings) { + self.settings = now; + } + /// Every part of the project that an edit can change, as comparable /// values: what the sweep's undo round-trip asks "byte identical?" of. #[cfg(test)] @@ -4956,31 +5087,45 @@ impl Project { self.sources.len(), self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(), self.lanes.iter().map(|l| l.subs.clone()).collect(), + self.subtitles.clone(), + self.settings.clone(), ) } - /// Restore every lane from before the last successful edit -- the clips and - /// the lane list both. `false` when there is nothing left to undo. Pushes - /// the lanes just left onto the redo stack, so [`Project::redo`] can walk - /// forward again. + /// Restore everything from before the last successful edit -- the lanes, + /// the subtitle palette and the project's own settings. `false` when there + /// is nothing left to undo. Pushes what was just left onto the redo stack, + /// so [`Project::redo`] can walk forward again. pub fn undo(&mut self) -> bool { match self.history.pop() { Some(prev) => { - self.redo.push(std::mem::replace(&mut self.lanes, prev)); + self.redo.push(Snapshot { + lanes: std::mem::replace(&mut self.lanes, prev.lanes), + subtitles: self.subtitles.clone(), + settings: self.settings.clone(), + }); + self.subtitles = prev.subtitles; + self.settings = prev.settings; true } None => false, } } - /// Restore every lane from before the last [`Project::undo`] -- the + /// Restore everything from before the last [`Project::undo`] -- the /// mirror of `undo`, walking the redo stack it fills. `false` when there /// is nothing left to redo, which is also true after any fresh edit: a /// new [`Project::snapshot`] clears the branch `undo` left behind. pub fn redo(&mut self) -> bool { match self.redo.pop() { Some(next) => { - self.history.push(std::mem::replace(&mut self.lanes, next)); + self.history.push(Snapshot { + lanes: std::mem::replace(&mut self.lanes, next.lanes), + subtitles: self.subtitles.clone(), + settings: self.settings.clone(), + }); + self.subtitles = next.subtitles; + self.settings = next.settings; true } None => false, @@ -5002,8 +5147,7 @@ impl Project { redo: Vec::new(), next_link: self.next_link, subtitles: self.subtitles.clone(), - limiter: self.limiter, - tone: self.tone, + settings: self.settings.clone(), } } @@ -5216,7 +5360,11 @@ impl Project { if self.history.len() == HISTORY_CAP { self.history.remove(0); } - self.history.push(self.lanes.clone()); + self.history.push(Snapshot { + lanes: self.lanes.clone(), + subtitles: self.subtitles.clone(), + settings: self.settings.clone(), + }); self.redo.clear(); } @@ -10405,4 +10553,42 @@ mod tests { .expect("valid parts"); assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]); } + +/// D4: removing a subtitle column used to clear the whole undo history, +/// because a placement names its track by index into the palette and the +/// reindex left every later entry naming the wrong one. The entry holds the +/// palette beside the lanes now, so the reindex undoes with it. +#[test] +fn removing_a_subtitle_column_undoes_with_its_reindex() { + let track = |label: &str| SubtitleTrack { + path: FILE.into(), + track: None, + language: "eng".into(), + name: String::new(), + label: label.into(), + cues: Vec::new(), + bitmap: false, + refused: None, + }; + let mut p = Project::single(FILE, 300) + .with_subtitles(vec![track("one"), track("two"), track("three")]); + assert_eq!(p.subtitles().len(), 3); + let before = p.parts(); + let palette = p.subtitles().to_vec(); + // Column 0 goes, which renumbers the two behind it. + p.remove_subtitles(0).expect("a column with nothing on it"); + assert_eq!(p.subtitles().len(), 2); + assert_eq!(p.subtitles()[0].label, "two"); + assert!(p.undo(), "the removal is a step like any other cut"); + // The palette itself, and not only what `parts` happens to compare: this + // is the assertion that cannot go vacuous if the restore below it ever + // leaves a field of it behind. + assert_eq!(p.subtitles(), palette.as_slice(), "the palette itself, back"); + assert_eq!(p.parts(), before, "the palette and the lanes, both back"); + assert!(p.redo(), "and forward again"); + assert_eq!(p.subtitles().len(), 2, "the column goes again"); + assert_eq!(p.subtitles()[0].label, "two"); + assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back"); +} + } diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs index 80d9b89..dd85b31 100644 --- a/crates/engine/src/subtitle.rs +++ b/crates/engine/src/subtitle.rs @@ -140,7 +140,11 @@ fn segments(set: &[u8]) -> Option> { } /// A subtitle track: where it came from and what it says. -#[derive(Clone, Debug)] +/// +/// `PartialEq` because it is one of the things an edit can change and therefore +/// one of the things an undo has to bring back exactly +/// ([`crate::Project::parts`], the sweep's round-trip). +#[derive(Clone, Debug, PartialEq, Eq)] pub struct SubtitleTrack { /// The file it was read out of: a standalone subtitle file, or the media /// file whose track number is below.