diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 511f8c1..f0f207a 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -949,9 +949,12 @@ impl Keymap { // Seeking without a pointer, on the keys every player already // seeks with (gpui names them "left"/"right"/"home"/"end", // platform.rs:872-877). The colour card reads the same arrows - // for its sliders, but a card answers the stroke and returns - // before the keymap is consulted at all -- so these move the - // playhead only while no card is open. + // for its sliders, and a card answers its own strokes before the + // keymap is consulted -- the arrows among them -- so these move + // the playhead only while no card is open. The document chords + // are the exception and are not these: `Undo`, `Redo`, `Save`, + // `Copy` and `Paste` reach the keymap whatever is up + // (`ui::stance::card_safe_action`). b(ActionId::StepBack, "left", false), b(ActionId::StepForward, "right", false), b(ActionId::JumpBack, "left", true), diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 45b79b8..d7063d3 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -138,8 +138,11 @@ struct Player { /// The *lane* is half the key because the four PGS tracks of a remux are /// one film's subtitles in four languages: placed one over the other they /// start at the same microsecond, and a lane whose eye was shut would leave - /// the one before it on screen. - sub_image: Option<((Lane, i64), Arc)>, + /// the one before it on screen. The other half is the cue itself + /// ([`crate::ui::preview::SubImageKey`]): two different cues can share a + /// lane and a start too, and a key of those two alone served one caption's + /// picture for another's. + sub_image: Option<(crate::ui::preview::SubImageKey, Arc)>, /// A frame that arrived before its time; shown on the tick it comes due. /// The pump's buffer, not transport state -- but a frame waiting here is /// what keeps a finished decoder from reading as [`Transport::Ended`] one @@ -787,6 +790,17 @@ struct Player { /// The active session's identity, for the above: bumped by every door that /// swaps `session` or `preview_session`. session_gen: u64, + /// The engine's own word on the sound device, as the last pump saw it: the + /// cache [`Player::watch_audio`] compares each frame against so a reason is + /// announced once when it *changes* and taken back when it clears. `None` + /// while the sound is up, and seeded by `Player::seed_audio_watch` at every + /// open, whose own line already carries the same fact. + audio_reason: Option, + /// Which session generation (`session_gen`) the cached reason above describes: + /// the watch is keyed to the session it is a statement about, so a preview + /// opening or closing seeds the cache instead of announcing the *other* + /// session's device. + audio_watch_gen: u64, /// Which of the clip's two inks the look section's wheel and colour field /// act on ([`VizSlot`]): the clip's own colour, or the ring's dual half. /// The pick stays picked across clips, the way the dock tab's does. @@ -1116,6 +1130,10 @@ fn main() { picture_box: Rc::default(), shot_pending: None, session_gen: 0, + // Nothing heard yet: the first pump seeds it off the session + // it serves. + audio_reason: None, + audio_watch_gen: 0, viz_slot: VizSlot::Main, viz_hex_edit: None, pending_viz: None, diff --git a/crates/app/src/notices.rs b/crates/app/src/notices.rs index 299d54f..29e38a3 100644 --- a/crates/app/src/notices.rs +++ b/crates/app/src/notices.rs @@ -46,9 +46,98 @@ fn is_completion(message: &str) -> bool { /// decode: it plays perfectly, in silence, and that is the one thing the window /// would otherwise never say (the engine's own word for it, verbatim). pub(crate) fn audio_notice(session: &PlaybackSession) -> Option { - session - .audio_disabled_reason() - .map(|reason| format!(" — NO AUDIO: {reason}")) + session.audio_disabled_reason().map(audio_tail) +} + +/// [`audio_notice`]'s own tail, for a reason already read -- the one place the +/// engine's word is spelled into a line, so the open path and the mid-session +/// one cannot drift apart. +pub(crate) fn audio_tail(reason: &str) -> String { + format!(" — NO AUDIO: {reason}") +} + +/// The same fact said on its own, for a device that dies *after* a file was +/// opened: [`audio_notice`] is a tail to append to "OPENED x", and a death +/// mid-session has no line to hang off -- so it leads with the state word the +/// strip reads first, and the tail is the same one. +pub(crate) fn audio_lost_line(reason: &str) -> String { + format!("AUDIO LOST{}", audio_tail(reason)) +} + +/// What a frame of the sound watch decides, as a pure value: the cache's own +/// session generation against the frame's says whether the two are even talking +/// about the same session, and only then what the reason did. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum AudioStep { + /// The cache describes the session *before* this one + /// (`Player::session_swapped`): it is seeded and nothing is announced -- a + /// preview that opens or closes is not a device that came back. + Seed, + /// The same session's reason arrived, or changed to a new one. + Push, + /// ...and the same session's reason is gone: the line it earned is retracted. + Clear, + /// The ordinary frame. + Nothing, +} + +/// [`Player::watch_audio`]'s whole decision, pure: `cached_gen` is the session +/// generation the cache describes, `session_gen` the one the frame is serving, and +/// two reasons are what the engine says the sound is (`None` for sound that is +/// up). +/// +/// The generation is what keeps another session's reason out of this session's +/// cache: `pump` serves the preview while one is up and the timeline otherwise, +/// so a flip reads a reason that was never about the cached session at all -- a +/// live device on one side and a dead one on the other is not a change, it is +/// two different questions. +pub(crate) fn audio_step( + cached_gen: u64, + session_gen: u64, + was: Option<&str>, + now: Option<&str>, +) -> AudioStep { + if cached_gen != session_gen { + return AudioStep::Seed; + } + match (was, now) { + (Some(was), Some(now)) if was == now => AudioStep::Nothing, + (_, Some(_)) => AudioStep::Push, + (Some(_), None) => AudioStep::Clear, + (None, None) => AudioStep::Nothing, + } +} + +/// What a *change* in the engine's sound reason does to the notice queue, as a +/// pure step: the line pushed when a reason arrives, the same line taken back +/// when the reason clears. [`Player::watch_audio`] is the only caller and owns +/// the caching; this owns the queue, so a test can drive both directions without +/// a window and without a device that dies on cue. +/// +/// The reason is the engine's to write, and the engine's writer is the wave +/// branch's: `tick`'s dead branch sets the lost-device reason and `rearm_audio` +/// clears it (its own test observes both). This side is the reader and never +/// spells the engine's words, so the end-to-end flip is asserted on the merged +/// tree while this lane drives the same step through the seam below -- on this +/// lane's base engine no path flips the reason at all. +pub(crate) fn audio_change_notice( + notices: &mut std::collections::VecDeque, + was: Option<&str>, + now: Option<&str>, +) { + match (was, now) { + (_, Some(reason)) if was != Some(reason) => { + push_notice(notices, audio_lost_line(reason).into()); + } + // The sound is back: the line goes with it, or the strip keeps saying NO + // AUDIO over a film that plays. Only that line -- whatever else is + // queued is none of this step's business. + (Some(was), None) => { + let line = audio_lost_line(was); + notices.retain(|notice| notice.as_ref() != line.as_str()); + } + _ => {} + } } /// The strip's own width is finite and its message is one line: what a @@ -121,12 +210,14 @@ mod tests { #[test] fn a_long_name_loses_its_middle_rather_than_the_state_word() { assert_eq!(ledger_line("SNAP OFF"), "SNAP OFF"); - let long = ledger_line("OPENED he_is_not_the_only_one_at_all_here.mp4 · 1 subtitle track(s)"); + let long = + ledger_line("OPENED he_is_not_the_only_one_at_all_here.mp4 · 1 subtitle track(s)"); assert!(long.starts_with("OPENED "), "{long}"); assert!(long.ends_with(" · 1 subtitle track(s)"), "{long}"); assert!(long.contains('…'), "{long}"); assert!( - long.split(' ').all(|w| w.chars().count() <= LEDGER_WORD_MAX), + long.split(' ') + .all(|w| w.chars().count() <= LEDGER_WORD_MAX), "{long}" ); } diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 3edc3d9..2d8bb7b 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -36,6 +36,12 @@ impl Player { // costs nothing a real edit would not have earned anyway, and one list // here is the whole answer instead of fifteen scattered calls. // + // The two exceptions are the history pair, whose doors answer "there was + // a step to take" and are gated in their own arms below: `^z` with + // nothing to undo is not a stroke that earned an autosave, and the + // save-on-close question over a project nobody has touched is exactly + // what the card doors' own gate exists to prevent. + // // This list is the *action* doors only, and that is the class to mind // when adding an edit: a control that reaches the session from a // *click* -- the Clip tab's look chips and wheel, the settings rows, @@ -54,8 +60,6 @@ impl Player { | ActionId::Group | ActionId::Delete | ActionId::Lift - | ActionId::Undo - | ActionId::Redo | ActionId::AddVideoLane | ActionId::RemoveVideoLane | ActionId::AddAudioLane @@ -130,8 +134,16 @@ impl Player { ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx), ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx), ActionId::ZoomFit => self.zoom_fit(cx), - ActionId::Undo => self.undo(cx), - ActionId::Redo => self.redo(cx), + ActionId::Undo => { + if self.undo(cx) { + self.mark_dirty(); + } + } + ActionId::Redo => { + if self.redo(cx) { + self.mark_dirty(); + } + } ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), // The last track of that kind: the one the add key put there, so the @@ -611,12 +623,17 @@ impl Player { return; }; let to = nudge_edge(current, dir, lo, hi); - self.mark_dirty(); let trimmed = self .session .as_mut() .is_some_and(|s| s.trim_clip(lane, idx, edge, to)); if trimmed { + // The arm rides the door's own answer: `trim_clip` is `false` for an + // edge already where it was asked to go -- the `[`/`]` pressed + // against the wall the edge is already on -- so the flag, the + // autosave sidecar and the save-on-close question stay off a + // project nobody has changed. + self.mark_dirty(); self.reset_after_reseek(); // Loop-trim follows the edge it is trimming: the whole point of // the mode is hearing the cut as it moves. @@ -643,12 +660,15 @@ impl Player { return; }; let to = frame_at(session.now(), self.fps); - self.mark_dirty(); let trimmed = self .session .as_mut() .is_some_and(|s| s.trim_clip(lane, idx, edge, to)); if trimmed { + // The door's own answer again: an edge the playhead is already on is + // `false`, no undo step, and nothing for the unsaved ghost to be + // about. + self.mark_dirty(); self.reset_after_reseek(); // Loop-trim follows the edge it is trimming, same as the nudge // pair above. @@ -684,16 +704,33 @@ impl Player { cx.notify(); } - pub(crate) fn undo(&mut self, cx: &mut Context) { - self.step_history(PlaybackSession::undo); - self.selected.clear(); + /// Whether there was a step to take, for the reason the action table arms + /// nothing on its own: a `^z` with an empty history is not an edit, and it + /// may not raise the save-on-close question over a project nobody has + /// touched. The selection goes with the step for the same reason it used to + /// go every time: a step back puts the indices on different clips, while a + /// refused one leaves them naming exactly what they named. + /// + /// The step itself goes through [`Player::step_history`], which is what + /// takes the window's own copy of the rate, the two proxy switches, the + /// palette's pick and the plate over the picture back up with it. + pub(crate) fn undo(&mut self, cx: &mut Context) -> bool { + let stepped = self.step_history(PlaybackSession::undo); + if stepped { + self.selected.clear(); + } cx.notify(); + stepped } - pub(crate) fn redo(&mut self, cx: &mut Context) { - self.step_history(PlaybackSession::redo); - self.selected.clear(); + /// [`Player::undo`]'s twin, the same answer and the same gate. + pub(crate) fn redo(&mut self, cx: &mut Context) -> bool { + let stepped = self.step_history(PlaybackSession::redo); + if stepped { + self.selected.clear(); + } cx.notify(); + stepped } /// One step of the session's own history through the door both `^z` and @@ -705,7 +742,11 @@ impl Player { /// 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) { + /// + /// `false` where there was nothing to step: no session at all, or a history + /// step that refused ([`PlaybackSession::undo`]'s own answer), in which case + /// nothing in the window moves either. + fn step_history(&mut self, step: fn(&mut PlaybackSession) -> bool) -> bool { let mut caches = SessionCaches { fps: self.fps, proxies_on: self.proxies_on, @@ -720,7 +761,7 @@ impl Player { .as_mut() .and_then(|session| history_step(&before, &mut caches, session, step)) else { - return; + return false; }; self.fps = caches.fps; self.proxies_on = caches.proxies_on; @@ -732,6 +773,7 @@ impl Player { self.sub_image = None; } self.reset_after_reseek(); + true } } diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 16efa54..6a5de06 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -716,6 +716,11 @@ impl Player { cx.notify(); } } + // The picture swaps back to the timeline's, so everything keyed to a + // session hears it (`Player::session_swapped`) -- the sound watch among + // them, or the timeline's own unchanged reason would read as a device + // that came back the moment the preview closed. + self.session_swapped(); self.preview_playing = false; } diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index a7577d4..3f22151 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -50,12 +50,21 @@ impl Player { // not that. let cut = session.cut_at(f64::from(at) / self.fps); if cut { + // Only a split that happened drops the selection: a refusal is + // "NOTHING TO SPLIT", and the clip in hand is still the clip the + // next Delete, `x` or menu acts on -- clearing it there left the + // user with nothing picked and told them nothing about it. A + // real split is the other way round: the cut it leaves makes the + // picked index name a different clip, so the mark has to go. + // [`Player::regroup`] below has always cleared inside its own + // success branch; this is the same rule on the other half of the + // pair. + self.selected.clear(); self.notify_user("SPLIT".into()); } else { self.notify_user("NOTHING TO SPLIT — the playhead is already on a cut".into()); } } - self.selected.clear(); cx.notify(); } @@ -72,10 +81,7 @@ impl Player { if session.regroup_at(session.now()) { self.selected.clear(); } else { - self.notify_user( - "NOTHING TO REGROUP — no cut under the playhead" - .into(), - ); + self.notify_user("NOTHING TO REGROUP — no cut under the playhead".into()); } } cx.notify(); @@ -97,9 +103,7 @@ impl Player { ); } } - (Some(_), None) => { - self.notify_user("NOTHING DETACHED — nothing selected".into()) - } + (Some(_), None) => self.notify_user("NOTHING DETACHED — nothing selected".into()), (None, _) => {} } cx.notify(); @@ -126,9 +130,7 @@ impl Player { // index (a stroke nobody saw) is not a thing to group. let picks = self.marks().0; match (&mut self.session, self.selected.anchor(), picks.len()) { - (_, None, _) => { - self.notify_user("NOTHING GROUPED — nothing selected".into()) - } + (_, None, _) => self.notify_user("NOTHING GROUPED — nothing selected".into()), // The hand's group: every pick, one id. (Some(session), _, 2..) => { if let Err(e) = session.group_all(&picks) { @@ -146,10 +148,9 @@ impl Player { self.notify_user(format!("NOT GROUPED — {e}").into()); } } - None => self.notify_user( - "NOTHING TO GROUP WITH — no clip covers these frames" - .into(), - ), + None => { + self.notify_user("NOTHING TO GROUP WITH — no clip covers these frames".into()) + } }, (None, ..) => {} } @@ -237,9 +238,7 @@ impl Player { self.notify_user("NOTHING LIFTED — that half is no longer there".into()); } } - (Some(_), None) => { - self.notify_user("NOTHING LIFTED — nothing selected".into()) - } + (Some(_), None) => self.notify_user("NOTHING LIFTED — nothing selected".into()), (None, _) => {} } cx.notify(); @@ -351,7 +350,6 @@ impl Player { if self.exporting().is_some() { return; } - self.mark_dirty(); let (Some((start, _)), Some(was)) = ( self.drop_frame(from, idx, x), self.session @@ -386,6 +384,14 @@ impl Player { }; match moved { true => { + // The arm rides the door's own answer: `move_clip_to` / + // `move_selection_to` answer `false` for a clip let go where it + // was picked up (`Project::move_selection` refuses before its + // snapshot) and for a lane of the wrong kind, and the arms below + // say both in words. Armed before the call it dirtied a project + // nobody had touched -- the ledger's `unsaved` ghost and the + // save-on-close question over an unchanged file. + self.mark_dirty(); // Every pick named a `(lane, ...)` by index into that lane's // clips, sorted by start -- exactly what an insert or a lane // change reorders. Re-read by the frame each pick's clip now @@ -409,11 +415,7 @@ impl Player { // Everything else that could refuse (a clip that is not there) // cannot be dragged. false if from.kind != to.kind => self.notify_user( - format!( - "NOT ON {} — a {kind} clip takes a {lanes} lane", - to.label() - ) - .into(), + format!("NOT ON {} — a {kind} clip takes a {lanes} lane", to.label()).into(), ), // Picked up and put back down where it was: a click, and a click // says nothing. @@ -517,7 +519,6 @@ impl Player { if self.exporting().is_some() { return; } - self.mark_dirty(); self.snap_cue = None; self.ghost.clear(); let at = self.place_frame(x).0; @@ -535,12 +536,18 @@ impl Player { }, // The row is greyed and says why in the list; here it says why at // the moment somebody tried to use it anyway. - (None, Some(_)) => Some( - "NOT PLACED — that subtitle track has no cues" - .to_string(), - ), + (None, Some(_)) => Some("NOT PLACED — that subtitle track has no cues".to_string()), (_, None) => Some("NOT PLACED — no file open".to_string()), }; + // The arm rides the door's own answer: `text` is `None` exactly when + // `Project::place_sub` took the track, and every refusal -- an overlap, + // a lane that is not a subtitle lane, "no file open", "no cues" -- + // leaves the project byte-for-byte what it was. Armed ahead of the + // answer it wrote an autosave sidecar, the ledger's `unsaved` ghost and + // the save-on-close question over a project nobody had changed. + if text.is_none() { + self.mark_dirty(); + } match (text, marked) { (Some(text), _) => self.notify_user(text.into()), // It went down, and a lane holds its captions in start order @@ -605,12 +612,19 @@ impl Player { if self.exporting().is_some() { return; } - self.mark_dirty(); self.snap_cue = None; self.ghost.clear(); let Some(idx) = self.dragged_sub(drag) else { return; }; + // Where the caption stands *now*, so the arm below can tell a move from + // a drag let go where it began: `Project::move_sub` answers `Ok` for a + // pick-up-put-back too ("`Ok`, and no undo step, because nothing + // changed"), so its own answer is not a change report. + let was = self + .session + .as_ref() + .and_then(|session| session.sub_lane(drag.lane).get(idx).map(|sub| sub.start)); // Asked before the edit, on the indices the press captured: the // engine's own grouped-with-clips answer, which is exactly when its // move reseeks -- a caption grouped only with other captions moves no @@ -648,6 +662,20 @@ impl Player { .as_ref() .and_then(|session| sub_mark(session.sub_lane(to), start)) .map(|i| (to, i)); + // The arm rides the caption's own place having moved -- the + // engine's `Ok` covers the put-back that takes no undo step at + // all (`Project::move_sub`), and a project nobody has touched + // must not light the `unsaved` ghost. + let landed = mark.and_then(|(lane, i)| { + self.session + .as_ref()? + .sub_lane(lane) + .get(i) + .map(|sub| (lane, sub.start)) + }); + if landed != was.map(|start| (drag.lane, start)) { + self.mark_dirty(); + } self.selected = match mark { Some(mark) => { let mut sel = Selection::new(); @@ -678,7 +706,6 @@ impl Player { if self.exporting().is_some() { return; } - self.mark_dirty(); let lifted = self .session .as_mut() @@ -691,6 +718,11 @@ impl Player { false => "NOTHING LIFTED — that caption is not there any more".to_string(), }; if lifted { + // The arm rides the door's own answer: `false` is "NOTHING LIFTED — + // that caption is not there any more", and the project is exactly + // what it was, so the flag, the autosave sidecar and the + // save-on-close question must stay off it. + self.mark_dirty(); // Everything after it on that lane slid down one ([`Vec::remove`]), // so a mark or an open menu left at or past it names a *different* // caption now -- and the next Delete would take that one. Both go @@ -1293,12 +1325,7 @@ impl Player { /// a project can gain, and the one remove that applies to this lane's kind /// ([`oracle::lane_items`]). Nothing is selected -- a head owns no clip -- /// which is [`Player::open_gap_menu`]'s rule on the other empty target. - pub(crate) fn open_head_menu( - &mut self, - lane: Lane, - at: Point, - cx: &mut Context, - ) { + pub(crate) fn open_head_menu(&mut self, lane: Lane, at: Point, cx: &mut Context) { if self.modal() || self.session.is_none() { return; } @@ -1550,7 +1577,11 @@ impl Player { let Some(trim) = self.trim.take() else { return; }; - self.mark_dirty(); + // The arm rides each door's own answer or the caption's own edges -- + // never the call: a trim released where the edge already stood is + // `Ok`/`true` with no undo step, and it must not leave the project + // looking edited to autosave, the `unsaved` ghost or the close + // question. // A caption's edge reaches the engine through its own door, at this // timeline's rate. An `Ok` is *not* "something changed" -- an edge that // stopped at a wall it already stood against is `Ok` with no undo step @@ -1565,14 +1596,33 @@ impl Player { .session .as_ref() .is_some_and(|session| session.caption_grouped_with_clips(trim.lane, trim.idx)); + // The caption's own window, before and after: the only reading that + // can tell a trim from an edge released against the wall it already + // stood on. + let edges = |player: &Self| { + player.session.as_ref().and_then(|session| { + session + .sub_lane(trim.lane) + .get(trim.idx) + .map(|sub| (sub.start, sub.frames, sub.in_us, sub.out_us)) + }) + }; + let before = edges(self); let trimmed = self .session .as_mut() .map(|session| session.trim_sub(trim.lane, trim.idx, trim.edge, trim.to)); match trimmed { Some(Err(e)) => self.notify_user(format!("NOT TRIMMED — {e}").into()), - Some(Ok(())) if grouped => self.reset_after_reseek(), - _ => {} + Some(Ok(())) => { + if edges(self) != before { + self.mark_dirty(); + } + if grouped { + self.reset_after_reseek(); + } + } + None => {} } cx.notify(); return; @@ -1582,6 +1632,10 @@ impl Player { .as_mut() .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to)); if trimmed { + // The arm rides the door's own answer: `trim_clip` is `false` for an + // edge already where it was asked to go, which is no undo step and + // no edit. + self.mark_dirty(); self.reset_after_reseek(); } cx.notify(); @@ -1656,7 +1710,20 @@ impl Player { let Some(fade) = self.fade_drag.take() else { return; }; - self.mark_dirty(); + // The ramp the clip is carrying *now*, so the arm below can tell a drag + // from a press-and-release that left the handle where it was: `set_fade_in` + // / `set_fade_out` answer `true` for any index that exists and take an + // undo step either way, so their own answer is not a change report. + let was = match fade.is_in { + true => self + .session + .as_ref() + .map(|session| session.fade_in_of(fade.lane, fade.idx)), + false => self + .session + .as_ref() + .map(|session| session.fade_out_of(fade.lane, fade.idx)), + }; let set = self .session .as_mut() @@ -1665,6 +1732,19 @@ impl Player { false => session.set_fade_out(fade.lane, fade.idx, fade.to), }); if set { + let now = match fade.is_in { + true => self + .session + .as_ref() + .map(|session| session.fade_in_of(fade.lane, fade.idx)), + false => self + .session + .as_ref() + .map(|session| session.fade_out_of(fade.lane, fade.idx)), + }; + if now != was { + self.mark_dirty(); + } cx.notify(); } } @@ -1698,19 +1778,14 @@ impl Player { [a, b] if a.0 == b.0 && a.1.abs_diff(b.1) == 1 => Some((a.0, a.1.min(b.1))), _ => self.selected.anchor(), }) else { - self.notify_user( - "NOTHING TO CROSSFADE — no audio clip selected".into(), - ); + self.notify_user("NOTHING TO CROSSFADE — no audio clip selected".into()); cx.notify(); return; }; let frames = self.fps.round().max(1.) as u32; if let Some(session) = &mut self.session { if !session.crossfade(lane, idx, frames) { - self.notify_user( - "NOTHING TO CROSSFADE — no neighbour end to end" - .into(), - ); + self.notify_user("NOTHING TO CROSSFADE — no neighbour end to end".into()); } } cx.notify(); @@ -1730,9 +1805,7 @@ impl Player { [a, b] if a.0 == b.0 && a.1.abs_diff(b.1) == 1 => Some((a.0, a.1.min(b.1))), _ => self.selected.anchor(), }) else { - self.notify_user( - "NOTHING TO DISSOLVE — no video clip selected".into(), - ); + self.notify_user("NOTHING TO DISSOLVE — no video clip selected".into()); cx.notify(); return; }; @@ -1747,10 +1820,7 @@ impl Player { self.fps.round().max(1.) as u32 }; if !session.set_transition_out(lane, idx, frames) { - self.notify_user( - "NOTHING TO DISSOLVE — no neighbour end to end" - .into(), - ); + self.notify_user("NOTHING TO DISSOLVE — no neighbour end to end".into()); } else if removing { self.notify_user("DISSOLVE REMOVED — the clips cut again".into()); } diff --git a/crates/app/src/player/transport.rs b/crates/app/src/player/transport.rs index 2be6b48..1e51a14 100644 --- a/crates/app/src/player/transport.rs +++ b/crates/app/src/player/transport.rs @@ -25,12 +25,73 @@ impl Player { .map_or(self.fps, |s| s.meta().frame_rate) } + /// The engine's own word on the sound device, for the session the pump + /// serves ([`Player::active_session`]). + fn sound_reason(&self) -> Option<&str> { + self.active_session() + .and_then(PlaybackSession::audio_disabled_reason) + } + + /// The engine's word on the sound device, watched rather than asked once. + /// A file that *opens* silent says so in its own open line + /// ([`audio_notice`], `library.rs`); what used to reach no consumer at all is + /// a reason that changes *under* a session that is already up. This is the + /// reader of that state: the writer is the engine's (the wave branch's + /// `tick` dead branch sets the lost-device reason, `rearm_audio` clears it), + /// and this lane spells none of its words. + /// + /// Called from [`Player::pump`] because that is the one place every frame + /// passes through, and written to cost an ordinary frame nothing: one read of + /// an `Option<&str>` and one compare, with the strings built only on the step + /// the pure [`audio_step`] names. + /// + /// Keyed by session ([`Player::audio_watch_gen`] against `session_gen`): + /// `pump` serves the preview while one is up and the timeline otherwise, so + /// without the key a preview opening or closing would read the *other* + /// session's reason and announce a device loss that never happened. + pub(crate) fn watch_audio(&mut self) { + let step = audio_step( + self.audio_watch_gen, + self.session_gen, + self.audio_reason.as_deref(), + self.sound_reason(), + ); + if step == AudioStep::Nothing { + return; + } + let was = self.audio_reason.take(); + self.audio_reason = self.sound_reason().map(str::to_owned); + self.audio_watch_gen = self.session_gen; + if step == AudioStep::Seed { + // A session swap is not a change: the new session's own open line + // carries its reason, so only a line left over from the session + // before is taken back -- and only when this one's sound is up. + if self.audio_reason.is_none() { + if let Some(was) = was { + let line = audio_lost_line(&was); + self.notices + .retain(|notice| notice.as_ref() != line.as_str()); + } + } + return; + } + audio_change_notice( + &mut self.notices, + was.as_deref(), + self.audio_reason.as_deref(), + ); + } + /// Catches the display up to the clock: everything already due is taken off /// the channel and only the last of them is shown, which *is* the /// drop-when-behind policy. A frame that is not due yet waits in `held`, and /// while the clock is paused *nothing* is due -- a repaint re-presents the /// frame already on screen, whatever asked for the repaint. pub(crate) fn pump(&mut self, window: &mut Window) { + // Before the drain, on the one read that does not need the session + // mutably: the sound can die at any point in a frame, and the notice it + // earns is owed to the frame it died in. + self.watch_audio(); // Where the transport was before this drain, so the crossing into // `Ended` can be recognised as the one transition it is. let was = self.transport(); diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs index 9772a0e..db43f74 100644 --- a/crates/app/src/tests/cards.rs +++ b/crates/app/src/tests/cards.rs @@ -1628,6 +1628,88 @@ fn every_click_door_that_writes_the_project_arms_autosave() { "{name} arms outside its gate, so a no-op pick would dirty the project" ); } + // The drag-and-drop family on the timeline: the same class, and the same + // rule. Every one of these doors can answer "nothing happened" -- a clip let + // go where it was picked up, a caption dragged back to the frame it started + // on, a trim, a fade or a `[`/`]` nudge released against the wall the edge + // already stood on, a subtitle row dropped on an overlap ("NOT PLACED") or a + // caption that is not there any more ("NOTHING LIFTED") -- and each one used + // to arm the flag *before* the door was asked, so the ledger's `unsaved` + // ghost, the autosave sidecar and the save-on-close question described a + // project whose content was byte-for-byte what it was. + // + // Each arm now rides its own door's answer, or the one reading the door's + // answer cannot give: a caption's own window before and after the trim + // (`Project::trim_sub` answers `Ok` for an edge released at a wall it already + // stood against) and the ramp's own value before and after the fade + // (`set_fade_*` answer `true` for any index that exists). + for (name, gate) in [ + ("move_clip", "match moved {"), + ( + "place_sub", + "let text = match (self.sub_of_track(track), &mut self.session) {", + ), + ("move_sub", "Some(Ok(())) => {"), + ("lift_sub", "if lifted {"), + ("commit_trim", "if trim.lane.kind == LaneKind::Subtitle {"), + ("commit_fade", "if set {"), + ("nudge_cut", "let to = nudge_edge(current, dir, lo, hi);"), + ( + "trim_cut_to_playhead", + "let to = frame_at(session.now(), self.fps);", + ), + ] { + let body = fn_body(name); + let (before, after) = body + .split_once(gate) + .unwrap_or_else(|| panic!("{name} lost the gate its arm rides")); + assert!( + after.contains("mark_dirty()"), + "{name} arms outside its gate, so a stroke that changed nothing \ + would dirty the project" + ); + assert!( + !before.contains("mark_dirty()"), + "{name} still arms ahead of its gate, so a refusal -- or a drag let \ + go where it started -- leaves the project looking edited" + ); + } + // The history pair is the one place the action table does not arm early: + // the door's own answer ("there was a step to take") is the gate, so `^z` + // with an empty history leaves the flag -- and the close question -- clear. + let act = fn_body("act"); + for (gate, next) in [ + ("if self.undo(cx) {", "ActionId::Redo =>"), + ("if self.redo(cx) {", "ActionId::AddVideoLane =>"), + ] { + let arm = act + .split_once(gate) + .unwrap_or_else(|| panic!("{gate} is gone from the action table")) + .1; + // Cut at the arm *after* this one: "everything from here on" is + // satisfied by the sibling's arm, so deleting Undo's own would ship + // green. + let arm = arm.split_once(next).map_or(arm, |(arm, _)| arm); + assert!( + arm.contains("mark_dirty()"), + "the arm behind `{gate}` arms nothing, so a real step back is \ + invisible to autosave, the unsaved ghost and the close question" + ); + } + // ...and the answer the arm reads is the door's own: the session's bool, not + // a bare call that would arm for an undo with nothing to undo. + for name in ["undo", "redo"] { + let body = fn_body(name); + assert!( + body.contains("PlaybackSession::") && body.contains("stepped"), + "Player::{name} no longer answers whether there was a step to take" + ); + assert!( + !body.contains("mark_dirty"), + "Player::{name} arms its own flag, so the arm in `act` is a second \ + one for the same step" + ); + } } /// [`crate::ui::dock_stance::transition_of`]: the dock's duration row diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index e3dcec0..ce1ecf6 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -613,6 +613,20 @@ fn the_playhead_actions_still_work_with_a_caption_marked() { let clips = session.lane_clips(Lane::V1).len(); assert!(session.cut_at(2.0), "the playhead splits the clip under it"); assert_eq!(session.lane_clips(Lane::V1).len(), clips + 1); + // The refusal is a real state and not a defence against nothing: the + // playhead is standing on the seam the split just left, which is exactly the + // stroke `Player::cut` words as "NOTHING TO SPLIT — the playhead is already + // on a cut". + assert!( + !session.cut_at(2.0), + "a second split on the seam is refused, which is the state the door's \ + selection gate is about" + ); + assert_eq!( + session.lane_clips(Lane::V1).len(), + clips + 1, + "and adds none" + ); assert!(session.regroup_at(2.0), "and the seam rejoins"); assert_eq!(session.lane_clips(Lane::V1).len(), clips); assert_eq!(session.sub_lane(lane).len(), 1, "the caption is untouched"); @@ -2914,6 +2928,49 @@ fn escape_closes_a_card_before_it_can_ever_reach_deselect() { } } +/// A refused split is not an edit, so it may not drop the clip in hand: the +/// refused stroke is worded ("NOTHING TO SPLIT — the playhead is already on a +/// cut") and the pick is still what the next `x`, `delete` or clip-menu row acts +/// on. The clear rides the door's own answer, the way [`Player::regroup`]'s +/// always has -- a split that happened is the other way round: the seam it +/// leaves renumbers the lane, so a pick kept across it names the wrong clip. +/// +/// A scan and not a drive: `self.selected` lives on `Player`, which needs a gpui +/// `Context` this binary has no harness for. The state itself is driven in +/// `the_playhead_actions_still_work_with_a_caption_marked`, which holds the real +/// `cut_at` refusal this gate is about. +#[test] +fn a_refused_split_keeps_the_clip_in_hand() { + let body = fn_body("cut"); + let (before, after) = body + .split_once("if cut {") + .expect("the split door no longer gates anything on its own answer"); + // The door's own branch, cut apart at its `else`: "runs after `if cut {`" is + // satisfied by the shape this fix replaced as well, because the clear sat + // below the whole if/else and so inside everything that followed the gate -- + // a revert of the fix would have shipped green. What the arm has to be is + // inside the then-branch, and nothing that follows the branch may hold one. + let then = after + .split_once("} else {") + .expect("the split door no longer branches on what the cut answered") + .0; + // One arm's worth of clear, counted with `matches`: `split(..).count()` + // counts the pieces *between* matches, so a single occurrence reads as two + // there and the guard fails on the fix it is guarding. + let extra_clear = after.matches("self.selected.clear()").count() > 1; + assert!( + !before.contains("self.selected.clear()"), + "the split drops the selection before it knows the cut happened, so a \ + refused split leaves the user with nothing picked and nothing told" + ); + assert!( + then.contains("self.selected.clear()") && !extra_clear, + "the clear does not ride the split's own success branch: a split that \ + happened leaves the mark naming a different clip across the seam, and a \ + refused one must leave it naming the clip it named" + ); +} + /// The other half: with nothing on screen to claim the key, bare escape falls /// all the way through to `Player::act`, whose `ActionId::Deselect` arm is /// the one place `self.selected` is emptied by a bare stroke rather than by diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index 6fa15d2..e70b2b3 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -11,6 +11,126 @@ use crate::subs::{ }; use crate::ui::preview::{bgra_to_rgba, screenshot_path}; +/// The notice queue's own half of the sound watch, and the three words it is +/// spelled with -- reached by name because the app's own glob does not carry +/// them (`notices` is a private module re-exported for the window). +use crate::notices::{audio_change_notice, audio_lost_line, audio_tail}; + +/// A reason that changes under a session that is already open says so, and stops +/// saying so when it clears. This side is the *reader*: the writer of a reason is +/// the engine's own `audio_disabled_reason`, and the app's two call sites were +/// the *open* paths -- so a reason that arrived mid-session reached no consumer +/// at all and the window played on in silence with nothing said. The engine's +/// writer is the wave branch's, so the flip is driven through the seam here and +/// asserted end to end on the merged tree; nothing below depends on when the +/// engine's `tick` sets it. +/// +/// Driven through the queue step itself -- [`audio_change_notice`] is the whole +/// of what a reason change does to the strip -- because a test cannot make a +/// sound card fail on cue; the caching around it is the same comparison plus the +/// source guard below. +#[test] +fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() { + let mut notices: std::collections::VecDeque = + ["OPENED take.mp4".into()].into_iter().collect(); + let lost = audio_lost_line("AUDIO_LOST"); + // The file was fine, and then the sound is gone: the reason arrives between + // two frames. + audio_change_notice(&mut notices, None, Some("AUDIO_LOST")); + assert_eq!( + notices.back().map(|notice| &***notice), + Some(lost.as_str()), + "a reason that arrives mid-session is never pushed" + ); + assert!( + lost.starts_with("AUDIO LOST") && lost.ends_with(&audio_tail("AUDIO_LOST")), + "the standing line lost its state word, or stopped sharing \ + `audio_notice`'s own tail" + ); + // The same reason read again on the next frame is not news. + audio_change_notice(&mut notices, Some("AUDIO_LOST"), Some("AUDIO_LOST")); + assert_eq!(notices.len(), 2, "one death was announced twice"); + // The re-arm takes: the line goes with it, and nothing else does. + audio_change_notice(&mut notices, Some("AUDIO_LOST"), None); + assert_eq!( + notices.iter().map(|notice| &***notice).collect::>(), + vec!["OPENED take.mp4"], + "the NO AUDIO line is still on the strip over a film that plays" + ); + // A second death later says so again. + audio_change_notice(&mut notices, None, Some("AUDIO_LOST")); + assert_eq!(notices.back().map(|notice| &***notice), Some(lost.as_str())); + // The wiring: the pump is the one place every frame passes through, and a + // watcher nothing calls is a message nobody reads. + assert!( + fn_body("pump").contains("self.watch_audio();"), + "the pump stopped watching the engine's sound reason, so a device that \ + dies mid-session is silent again" + ); + // ...and the watch keys its cache to the session it is a statement about: + // the two generations are what the *step call* is asked, so a preview flip + // cannot be answered as if it were the cached session's own change. + let watch = fn_body("watch_audio"); + let args = watch + .split_once("audio_step(") + .expect( + "the watch decides for itself instead of through the pure step the flip test drives", + ) + .1; + let args = args.split_once(')').map_or(args, |(args, _)| args); + assert!( + args.contains("self.audio_watch_gen") && args.contains("self.session_gen"), + "the watch asks the step about something other than the session it serves, \ + so a preview opening or closing announces the other session's device" + ); + assert!( + fn_body("sound_reason").contains("self.active_session()"), + "the watch reads a reason off a session the pump is not serving, so its \ + cache and the frame disagree the moment a preview is up" + ); + // ...and every door that installs or drops a session says so, the preview's + // two among them (the one the flip was missed on). + for door in ["close_session", "open_preview", "close_preview"] { + assert!( + fn_body(door).contains("self.session_swapped();"), + "{door} installs or drops a session without telling anything keyed to \ + one, so a flip reads as news" + ); + } +} + +/// The flip logic itself, pure: a preview opening or closing is a *different* +/// session, so the reason it reports is not news about the cached one -- the +/// phantom device loss the verifier caught, and the reason the cache carries a +/// generation at all. A change on the session the cache describes is the one that +/// speaks. +#[test] +fn a_preview_flip_is_not_a_device_that_came_back() { + use crate::notices::{audio_step, AudioStep}; + // A swap, every way round: seeded, never announced. + assert_eq!(audio_step(7, 8, None, Some("AUDIO_LOST")), AudioStep::Seed); + assert_eq!(audio_step(7, 8, Some("AUDIO_LOST"), None), AudioStep::Seed); + assert_eq!( + audio_step(7, 8, Some("AUDIO_LOST"), Some("AUDIO_LOST")), + AudioStep::Seed, + "a flip whose reason reads the same on both sides is still a flip" + ); + // The same session, the reason arriving, changing, and going. + assert_eq!(audio_step(7, 7, None, Some("AUDIO_LOST")), AudioStep::Push); + assert_eq!( + audio_step(7, 7, Some("AUDIO_LOST"), Some("device gone")), + AudioStep::Push + ); + assert_eq!(audio_step(7, 7, Some("AUDIO_LOST"), None), AudioStep::Clear); + assert_eq!( + audio_step(7, 7, Some("AUDIO_LOST"), Some("AUDIO_LOST")), + AudioStep::Nothing, + "the same reason read again on the next frame is not news" + ); + assert_eq!(audio_step(7, 7, None, None), AudioStep::Nothing); + assert_eq!(audio_step(0, 0, None, None), AudioStep::Nothing); +} + /// The toast tail an audio import earns: rate, channel count and rounded /// length, in the words the IMPORTED line appends them in /// ([`Player::take_import`], [`Player::install_media`]). A film gets none of diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index fd01558..a161600 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -3,6 +3,63 @@ use super::*; +/// The preview's one cached cue picture is keyed by the *cue* and not only by +/// where it happens to sit: a lane and a start microsecond are not an identity -- +/// lift a bitmap caption off a lane, drop another track's caption at the same +/// frame, and a key of those two matched the cache, painting the picture of the +/// cue that is gone over the one that is up. The picture's own allocation is the +/// rest of the key, and an identical repeat still hits, which is the whole cache. +#[test] +fn a_cached_cue_picture_is_keyed_by_the_cue_not_only_its_moment() { + use crate::ui::preview::sub_image_key; + let (lane, other) = (Lane::S1, Lane::A1); + // Two cues that share the lane and the start, and nothing else: one lifted, + // one placed at the same frame. + let a = sub_image_key(lane, 1_000_000, 3_000_000, 0x1000); + let b = sub_image_key(lane, 1_000_000, 3_000_000, 0x2000); + assert_ne!( + a, b, + "two different cues at one moment on one lane are one cache key again, so \ + the second paints the first's picture" + ); + // The same cue repainted: still a hit. + assert_eq!( + a, + sub_image_key(lane, 1_000_000, 3_000_000, 0x1000), + "the cache misses on every repaint of the same cue, so it decodes an 8 MB \ + display set per frame" + ); + // The same picture recut over the same start is a different cue. + assert_ne!( + a, + sub_image_key(lane, 1_000_000, 2_500_000, 0x1000), + "a cue's own end is no part of the key, so a recut cue serves the old window" + ); + // And the other half of the old key still holds: the four PGS tracks of a + // remux start at the same microsecond, so the lane separates them. + assert_ne!( + a, + sub_image_key(other, 1_000_000, 3_000_000, 0x1000), + "the lane is no longer part of the key, so a lane's eye shut leaves the \ + other lane's caption on screen" + ); + // And the door builds its key this way, out of the cue's own picture: the + // cache is only keyed by the cue while the lookup goes through this + // constructor, and a test of the constructor alone would pass with the door + // still keying on `(lane, start_us)`. + let preview_rs = src_text("ui/preview.rs"); + assert!( + preview_rs.contains( + "let key = sub_image_key(lane, start_us, end_us, Arc::as_ptr(image) as usize);" + ), + "the cue picture is cached under a key that is not the cue's own" + ); + assert!( + preview_rs.contains("*up == key"), + "the cache no longer compares the key it built" + ); +} + /// What a drop reads: the frame under the pointer, through the same scale /// the boxes are drawn through. Zoomed in, the same pixel is a different /// frame -- which is the whole reason `Player::frame_under` goes through @@ -976,3 +1033,105 @@ fn focus_panels_is_bound_and_lands_on_the_dock() { // have stolen it. assert_eq!(k.lookup("tab", false), Some(ActionId::Select)); } + +/// A card is not a key-eating black box: the room-wide chords that act on the +/// document -- the edit history, the project file, the clipboard -- must reach +/// `Player::act` while any card is open. `param_card_key` answers `true` for +/// *every* stroke once one of the seven is up, so the dispatch has to stand in +/// front of it, not only in front of the blanket modal guard under it; and the +/// blanket guard's own `card_open()` has to read after that dispatch too, or a +/// chord that got past `param_card_key` (a menu dismiss comes to mind) would +/// still never reach the keymap. +/// +/// A scan of the handler's own source, for the reason every handler scan here +/// gives: this binary has no window harness to press `ctrl+z` through. +#[test] +fn an_open_card_does_not_swallow_the_document_chords() { + use crate::ui::stance::card_safe_action; + use keymap::ActionId; + // The five the room answers through a card, and the reason each is on the + // list: history, file, clipboard. + for action in [ + ActionId::Undo, + ActionId::Redo, + ActionId::Save, + ActionId::Copy, + ActionId::Paste, + ] { + assert!( + card_safe_action(action), + "{action:?} is a document chord and a card must not eat it" + ); + } + // ...and the strokes the cards' own branch list claims stay theirs: + // escape is every card's way out, `s` is the equalizer's spectrum, `x` its + // band removal, `m` every card's maximize, and the digits pick a band. + for action in [ + ActionId::Deselect, + ActionId::Cut, + ActionId::Delete, + ActionId::ToggleMute, + ActionId::Equalizer, + ActionId::Color, + ActionId::Loop, + ActionId::TrimIn, + ] { + assert!( + !card_safe_action(action), + "{action:?} is a card's own stroke and the card must keep it" + ); + } + // The chords are real bindings, not a list of actions nothing reaches. + let keys = keymap::Keymap::defaults(); + for (key, ctrl, action) in [ + ("z", true, ActionId::Undo), + ("y", true, ActionId::Redo), + ("s", true, ActionId::Save), + ("c", true, ActionId::Copy), + ("v", true, ActionId::Paste), + ] { + assert_eq!( + keys.lookup(key, ctrl), + Some(action), + "the keymap no longer binds {action:?}" + ); + } + // And the dispatch stands where it has to: inside the root handler, ahead + // of the cards' own branches and ahead of the blanket modal guard. + let stance_rs = src_text("ui/stance.rs"); + let dispatch = stance_rs.find("card_safe_action(action)").expect( + "the root key handler no longer asks which chords a card does not take -- an open card \ + eats every stroke again", + ); + assert!( + stance_rs[..dispatch].contains("this.keymap.lookup(key, ctrl)"), + "the dispatch no longer goes through the keymap, so a rebind would leave it behind" + ); + // The *statement* that dispatches, not just some `keymap.lookup` before it: + // the hold gate at the top of the handler resolves the same pair, so a needle + // that only asks for the lookup is satisfied by a dispatch resolving the + // action some other way entirely. + let resolve = stance_rs + .find("if let Some(action) = this.keymap.lookup(key, ctrl)") + .expect("the dispatch no longer resolves an action through the keymap"); + let stmt = &stance_rs[resolve..]; + let stmt = &stmt[..stmt.find('{').expect("the dispatch statement has no block")]; + assert!( + stmt.contains("card_safe_action("), + "the dispatch resolves an action and never asks whether a card may take \ + it, so an open card eats the document chords again" + ); + for (guard, label) in [ + ("if this.param_card_key(", "the cards' own key branches"), + ("if this.card_open()", "the blanket modal guard"), + ] { + let at = stance_rs + .find(guard) + .unwrap_or_else(|| panic!("{label} moved or was renamed")); + assert!( + dispatch < at, + "{label} reads before the document dispatch -- an open card would \ + swallow undo, redo, save and the clipboard pair again" + ); + } +} diff --git a/crates/app/src/ui/preview.rs b/crates/app/src/ui/preview.rs index 49534a0..ae6997a 100644 --- a/crates/app/src/ui/preview.rs +++ b/crates/app/src/ui/preview.rs @@ -5,6 +5,44 @@ use crate::ui::type_scale::{self, Typeset}; use crate::*; use std::path::{Path, PathBuf}; +/// What the preview's one cached cue picture is *of*: the lane, the moment, +/// the cue's own end, and the picture itself. +/// +/// The lane and the start microsecond alone are not a cue. Two bitmap cues can +/// share both -- lift a caption off a lane and drop another track's caption at +/// the same frame -- and with those two as the whole key the cache's `up == key` +/// test matched, painting the picture of the cue that is gone over the one that +/// is up. +/// +/// The picture's own allocation ([`Arc::as_ptr`]) is the identity: the cue list +/// a repaint is handed holds the same `Arc` for as long as that cue is in it, so +/// two repaints of one cue compare equal -- which is the whole cache hit -- while +/// two different cues never do. The bytes are never compared: a display set is +/// tens of kilobytes and this test runs on every frame. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct SubImageKey { + pub(crate) lane: Lane, + pub(crate) start_us: i64, + /// The cue's own end, so the same picture recut over the same start reads as + /// a different cue here too. + pub(crate) end_us: i64, + /// Where that picture lives -- [`Arc::as_ptr`] of the cue's image. + pub(crate) picture: usize, +} + +/// [`SubImageKey`] for one cue's picture: the one place the key is built, so the +/// lookup that trusts a hit and the test that pins what a hit means cannot drift +/// apart. `picture` is where the cue's image lives -- the caller passes +/// `Arc::as_ptr` of it, and nothing about the bytes is ever read here. +pub(crate) fn sub_image_key(lane: Lane, start_us: i64, end_us: i64, picture: usize) -> SubImageKey { + SubImageKey { + lane, + start_us, + end_us, + picture, + } +} + impl Player { /// The darkroom's own preview indicator (MOCK-SPEC.md): a plate /// (canvas-on-panel, §4), mono for what the film says, and a ghost @@ -314,8 +352,10 @@ impl Player { // lane is all there is here. let picture = cues .iter() - .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?))) - .and_then(|(start_us, image)| self.sub_picture(lane, start_us, image, window)); + .find_map(|cue| Some((cue.start_us, cue.end_us, cue.image.as_ref()?))) + .and_then(|(start_us, end_us, image)| { + self.sub_picture(lane, start_us, end_us, image, window) + }); // A picture is fitted onto the whole region and a plate hangs off the // bottom of it, and a track is one or the other -- so they are two // shapes and not one with the parts switched off. @@ -386,10 +426,10 @@ impl Player { ) } - /// The cue `lane` starts at `start_us` as a drawable picture, decoded on the - /// first repaint it is up for and kept until another cue takes its place - /// ([`Player::sub_image`]). `None` for a display set the decoder refuses, - /// which draws nothing rather than failing the frame. + /// The cue `lane` plays from `start_us` to `end_us` as a drawable picture, + /// decoded on the first repaint it is up for and kept until another cue + /// takes its place ([`Player::sub_image`]). `None` for a display set the + /// decoder refuses, which draws nothing rather than failing the frame. /// /// Its atlas tile is released as the video's is: every [`RenderImage`] gets /// a fresh id and its own tile, so a film's worth of cues would grow the @@ -398,10 +438,11 @@ impl Player { &mut self, lane: Lane, start_us: i64, - image: &engine::subtitle::CueImage, + end_us: i64, + image: &Arc, window: &mut Window, ) -> Option> { - let key = (lane, start_us); + let key = sub_image_key(lane, start_us, end_us, Arc::as_ptr(image) as usize); if let Some((up, ready)) = &self.sub_image && *up == key { diff --git a/crates/app/src/ui/stance.rs b/crates/app/src/ui/stance.rs index 3c7bcd6..65c5798 100644 --- a/crates/app/src/ui/stance.rs +++ b/crates/app/src/ui/stance.rs @@ -68,6 +68,55 @@ pub(crate) fn is_focus_exit_key(key: &str) -> bool { key == "escape" } +/// The room-wide chords an open card does not take. +/// +/// A card owns the keyboard for its own *values* -- the arrows on a slider, `r` +/// for reset, `m` for maximize, the digits on the equalizer, `enter` to apply +/// ([`Player::param_card_key`]'s branch list) -- and every one of those is a +/// *bare* stroke its own branch claims. These five are not: each acts on the +/// document rather than on the card the hand is looking at, and while a card is +/// open the room must still answer them. It is the equalizer card's own comment +/// that says so from the inside: "Nothing to undo: every change is already at +/// the clip, and undo is undo's own key". +/// +/// - `Undo`/`Redo`: the edit history. The one chord a hand reaches for *while* +/// looking at what it just changed, which is exactly when a card is open. +/// - `Save`: the project file. Its chord is `ctrl+s`, and no card's branch +/// answers a ctrl chord on purpose (`param_card_key` is handed the shift +/// modifier alone). +/// - `Copy`/`Paste`: the clip clipboard, the pair beside the history keys. +/// +/// Asked against the [`keymap::ActionId`] the stroke resolved to, never against +/// a key literal: a rebind moves the chord and this list follows it. +/// +/// Deliberately *not* here, in three kinds: +/// +/// 1. The strokes a card's own branch list claims, which the card must keep: +/// escape (every card's way out, and `Deselect`'s own stroke), the arrows +/// (`StepBack`/`StepForward`/`JumpBack`/`JumpForward` -- the branch reads +/// them with or without ctrl), `m` (`ToggleMute`) and the digits, plus the +/// bare letters the cards' verbs sit on -- `r` (`Loop`, `Resolution`), `f` +/// (`Mix`, `Crossfade`), `a` (`AddAudioLane`, `SelectAll`), `s` +/// (`Cut` -- the EQ card's spectrum), `x` (`Delete`, `Dissolve` -- the +/// band's removal), `k` (`Color`), `j`, `u`, `y` (`SubtitleStyle`), `enter` +/// (the silence card's apply). +/// 2. The chords that open a card: `Export`/`Settings`/`Color`/`Transform`/ +/// `Speed`/`Silence`/`Mix`/`Equalizer`/`SubtitleStyle`. They own the very +/// modal slot the open card is sitting in, and swapping the surface under a +/// hand mid-stroke is not a chord this fix is for. +/// 3. Everything else the keymap binds (the odometer, the trims, the zoom, the +/// lane add/remove pair, the theme, the screenshot...). They are left to the +/// card on purpose, the way [`Player::param_card_key`] left them before this: +/// the defect is a card swallowing the *history* while the user edits through +/// it, and each of these is one press away again the moment the card closes. +pub(crate) fn card_safe_action(action: crate::keymap::ActionId) -> bool { + use crate::keymap::ActionId; + matches!( + action, + ActionId::Undo | ActionId::Redo | ActionId::Save | ActionId::Copy | ActionId::Paste + ) +} + /// The dock mounts only one of its two tabs at a time /// (`dock_stance::render`'s `match src_active`), so `focus_dock` only has a /// tree node under Sources and `focus_inspector` only under Clip -- focusing @@ -1068,6 +1117,25 @@ pub(crate) fn render( cx.notify(); return; } + // A card is not a key-eating black box. The room-wide chords that + // act on the document rather than on the card -- the edit history, + // the project file, the clipboard ([`card_safe_action`]) -- run + // here, ahead of the cards' own key branches below and ahead of the + // blanket modal guard under them, so an open card cannot swallow + // the stroke a hand reaches for while looking at what it changed. + // `param_card_key` answers `true` for every stroke once a card is + // open, so this has to stand in front of *it*, not only in front of + // the guard: `ctrl+z` never reached `keymap.lookup` at all, and the + // card's own comment says undo was always meant to be undo's key. + // + // Asked through the keymap rather than as a table of key literals: + // a rebind moves the chord and this follows. + if let Some(action) = this.keymap.lookup(key, ctrl) + && card_safe_action(action) + { + this.act(action, window, cx); + return; + } // The param cards' own key branches (arrows nudge the focused // slider, digits pick an EQ band, `r` resets, card verbs) -- // `Player::param_card_key` (`player/cards.rs`), the same @@ -1125,6 +1193,12 @@ pub(crate) fn render( // clip_menu/row_menu/list chain follows (`render.rs`): this is // the fix for "no state may make the room modal without // showing anything", not only the source-dot's menu. + // + // Except the document chords, which were answered *above* and + // left the menu standing: a menu is a visible surface with + // escape and any other key still shutting it, and losing an + // undo to a square of the screen a right-click left open would + // be the black box this handler no longer is. this.context_menu = None; this.library_menu = None; this.picker = None;