From 222336b1c3cb96ebf0803502576361e77001d1ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 15:39:29 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(timeline):=20clips=20are=20tri?= =?UTF-8?q?mmed=20by=20dragging=20their=20edges?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 6 px strip at each end of a clip box takes the press the body-drag would otherwise take (gpui `occlude`), so one gesture stays one thing: an edge trims, the middle still moves the clip to another lane, and both ends still select and open the clip menu. The box follows the pointer while the button is down and the engine hears about it once, at the release -- one edit, one undo step for the whole drag, exactly as an equalizer gesture works. `Project::trim` clamps rather than refuses: one frame of clip always survives, an edge never crosses its neighbour on the lane, an in-point never walks back past the source's first frame, and an out-point never runs past the file's own last frame -- a clip ending past it is a project that will not open again. `Project` does not know how long a file is, so `PlaybackSession` now keeps the frame counts it already computes at every import and fills them in. Linked halves trim together to one clamped edge, the tightest wall of the group winning, because a link is one span on however many lanes. `trim_room` is the same clamp without the mutation: the drag asks it where the edge may land, so the width drawn is the width the release commits. A timeline drawn to fit the window has no room past its own last frame, so while a tail is dragged the bed is drawn out to as far as that tail may go -- without it the last clip could be pulled in and never let back out. --- crates/app/src/main.rs | 307 +++++++++++++++++++++++++++++--- crates/engine/src/playback.rs | 55 +++++- crates/engine/src/project.rs | 254 ++++++++++++++++++++++++++ crates/engine/tests/saveload.rs | 38 ++++ 4 files changed, 633 insertions(+), 21 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 59a5b02..cb93024 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -13,12 +13,13 @@ use engine::audio::StreamInfo; use engine::color::ColorParams; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; -use engine::project::{Lane, LaneKind, Source}; +use engine::project::{Edge, Lane, LaneKind, Source}; use engine::scale::FitPolicy; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ - AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, - MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point, + AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, + KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, + Point, RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size, }; @@ -216,6 +217,31 @@ struct ClipDrag { idx: usize, } +/// A clip edge being dragged: which end of which clip, and the timeline frame +/// the pointer has pulled it to. The box on screen is drawn from `to` while this +/// is set and the engine hears about it once, at the release +/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture, +/// exactly as an equalizer drag works. +#[derive(Clone, Copy)] +struct Trim { + lane: Lane, + idx: usize, + edge: Edge, + /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from + /// it is the width the release commits -- an edge stops under the pointer + /// rather than snapping back after the fact. + to: u32, + /// The dragged clip's group, so its other halves' boxes follow the edge on + /// screen exactly as the engine will move them. + link: Option, +} + +/// How wide a clip's edge is as a *target*: the strip at each end where a press +/// means "make this longer or shorter" instead of "move this to another lane". +/// Wide enough to hit, narrow enough that the middle of even a small box is +/// still the body. +const EDGE_W: f32 = 6.; + /// An open clip menu: which clip it was opened on, where it hangs, and whether /// it has been turned over to show what that clip *is* instead of what can be /// done to it. The lane and index are the ones the same click selected, so @@ -359,6 +385,10 @@ struct Player { /// A drag that started on the ruler. Moves anywhere in the window scrub /// while it is set; the release commits the exact position. scrubbing: bool, + /// A drag that started on a clip's edge, tracked on the root for + /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See + /// [`Trim`]. + trim: Option, last_scrub: Instant, last_target: u32, /// The running export. While it owns the UI the editor is read-only. @@ -527,6 +557,11 @@ impl Player { self.eos = false; self.done = false; self.pending_seek = true; + // An edit moves the indices a drag in flight is holding -- a stroke + // during one is exactly that -- and an edge committed against a moved + // index would trim a clip nobody grabbed. Dropping it is the whole fix: + // nothing has been written yet. + self.trim = None; } /// What an action does, wherever it was asked for -- a stroke, or the clip @@ -1168,6 +1203,135 @@ impl Player { cx.notify(); } + /// Opens the clip menu on the box under the pointer, from the right button + /// wherever it was pressed on that box -- its middle or one of its edge + /// strips, which cover the middle's own listener. Selecting first is part of + /// it: every item acts on the clip the menu names. + fn open_menu(&mut self, lane: Lane, idx: usize, at: Point, cx: &mut Context) { + if self.modal() { + return; + } + self.select((lane, idx), cx); + self.context_menu = Some(ContextMenu { + lane, + idx, + at, + details: false, + }); + cx.notify(); + } + + /// A press on a clip's edge: the start of the drag that changes how much of + /// its source it plays. It selects the clip as a press anywhere else on the + /// box does -- the edge strip covers the box's own listener (`occlude`), so + /// this is the only one that fires there. + fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context) { + if self.modal() || self.exporting().is_some() { + return; + } + let Some(clip) = self + .session + .as_ref() + .and_then(|session| session.lane_clips(lane).get(idx).copied()) + else { + return; + }; + self.select((lane, idx), cx); + self.trim = Some(Trim { + lane, + idx, + edge, + // Where the edge already is: a press that never moves is not an + // edit, and `Project::trim` refuses exactly that. + to: match edge { + Edge::Start => clip.start, + Edge::End => clip.end(), + }, + link: clip.link, + }); + cx.notify(); + } + + /// Where the pointer has pulled the edge to, clamped to the room the engine + /// says that edge has. Along the same bed the ruler is measured on and + /// against the same duration the boxes are drawn to, so the edge tracks the + /// pointer exactly. + fn trim_to(&mut self, x: Pixels, cx: &mut Context) { + let (duration, fps) = (self.drawn_duration(), self.fps); + let frac = frac_along(x, self.ruler.get()); + let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { + return; + }; + let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { + return; + }; + trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi); + cx.notify(); + } + + /// The release: the whole drag reaches the engine as one edit, so it is one + /// undo step. The selection survives it -- a trim inserts and removes + /// nothing, so every index a lane had still names the clip it named. + fn commit_trim(&mut self, cx: &mut Context) { + let Some(trim) = self.trim.take() else { + return; + }; + let trimmed = self + .session + .as_mut() + .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to)); + if trimmed { + self.reset_after_reseek(); + } + cx.notify(); + } + + /// The clip as the drag is showing it: an edge under the pointer moves its + /// own box, and the boxes of the halves linked to it, before anything is + /// committed. Display only -- the project is not touched until the release. + fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip { + let Some(trim) = self.trim.filter(|t| { + (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link) + }) else { + return clip; + }; + match trim.edge { + // The in-point follows the head, exactly as `Project::trim` moves + // it: what stays on screen plays what it always played. + Edge::Start => Clip { + in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start)) + .clamp(0, i64::from(clip.out_frame - 1)) as u32, + start: trim.to, + ..clip + }, + Edge::End => Clip { + out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1), + ..clip + }, + } + } + + /// How long the timeline is *drawn* as: its own length, and while a tail is + /// being dragged the furthest that tail may reach. A bed that ends exactly + /// at the last frame has nowhere to put a pointer that means "longer", so + /// without this the last clip on the timeline could be pulled in and never + /// let back out. + fn drawn_duration(&self) -> f64 { + let Some(session) = &self.session else { + return 0.; + }; + let duration = session.timeline_duration(); + match self.trim { + Some(trim) if trim.edge == Edge::End => { + let (_, hi) = session + .trim_room(trim.lane, trim.idx, trim.edge) + .unwrap_or((0, 0)); + duration.max(f64::from(hi) / self.fps) + } + _ => duration, + } + } + /// The one way a library row reaches the timeline: the Add button and a row /// dragged onto a lane both come here, so there is a single answer to what /// "add this source" does. The whole source goes in at the playhead as one @@ -1690,11 +1854,9 @@ impl Render for Player { } // Read per render, never cached: a delete shortens the timeline and the - // timecode, the ruler and the clamp below all have to follow it. - let duration = self - .session - .as_ref() - .map_or(0., PlaybackSession::timeline_duration); + // timecode, the ruler and the clamp below all have to follow it -- and + // so does the room a tail being dragged needs to grow into. + let duration = self.drawn_duration(); // The clock keeps running after the last frame (wall time takes over at // audio EOF) while the picture is frozen, so the timeline the UI shows is // the clamped one, pinned to the out-point once playback is done. @@ -1899,6 +2061,17 @@ impl Render for Player { } return; } + // A clip edge is 6 px wide and the pointer leaves it on the + // first drag, so the gesture is tracked here for the same + // reason -- and it ends here too when the button came up + // outside the window, still owing its one edit. + if this.trim.is_some() { + match event.pressed_button { + Some(MouseButton::Left) => this.trim_to(event.position.x, cx), + _ => this.commit_trim(cx), + } + return; + } if !this.scrubbing { return; } @@ -1921,6 +2094,13 @@ impl Render for Player { this.commit_eq(cx); return; } + if this.trim.is_some() { + // The release lands exactly, then the gesture is + // written once -- one edit, one undo step. + this.trim_to(event.position.x, cx); + this.commit_trim(cx); + return; + } if std::mem::take(&mut this.scrubbing) { this.scrub_to(event.position.x, true, cx); } @@ -3444,7 +3624,7 @@ impl Player { let (sel, sel_link) = (self.selected, self.selected_link()); let audio = lane.kind == LaneKind::Audio; let tip: SharedString = format!( - "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut", + "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", self.keymap.display(ActionId::Select), self.keymap.display(ActionId::SelectPrev), self.keymap.display(ActionId::SelectNext), @@ -3502,6 +3682,9 @@ impl Player { })) .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) .children(clips.iter().enumerate().map(|(i, clip)| { + // What a drag on an edge is showing, which is the clip + // itself while nothing is being dragged. + let clip = &self.trimmed(lane, i, *clip); let (start, len) = ( f64::from(clip.start) / self.fps, f64::from(clip.len()) / self.fps, @@ -3580,19 +3763,44 @@ impl Player { .on_mouse_down( MouseButton::Right, cx.listener(move |this, event: &MouseDownEvent, _, cx| { - if this.modal() { - return; - } - this.select((lane, i), cx); - this.context_menu = Some(ContextMenu { - lane, - idx: i, - at: event.position, - details: false, - }); - cx.notify(); + this.open_menu(lane, i, event.position, cx); }), ) + // The two strips a drag *lengthens* the clip by, + // one at each end. They occlude the box behind + // them, which is what keeps one gesture one thing: + // a press here trims, a press anywhere else on the + // box still starts the move to another lane. + .children([Edge::Start, Edge::End].map(|edge| { + let mut zone = div() + .absolute() + .top_0() + .h_full() + .w(px(EDGE_W)) + .occlude() + .cursor(CursorStyle::ResizeLeftRight) + .hover(|s| s.bg(rgb(ACCENT))) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _: &MouseDownEvent, _, cx| { + this.start_trim(lane, i, edge, cx); + }), + ) + // Occluded, so the box's own right-button + // listener never fires here: the menu is + // the same menu, opened by the same call. + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.open_menu(lane, i, event.position, cx); + }), + ); + zone = match edge { + Edge::Start => zone.left_0(), + Edge::End => zone.right_0(), + }; + zone + })) // Under the label row, never through it. .children(wave.filter(|_| audio).and_then(|wave| { let inner: AnyElement = match wave { @@ -5179,6 +5387,64 @@ mod tests { ); } + /// The trim-a-clip path through the doors the edge drag uses: + /// [`Player::trim_to`] clamps the pointer with `trim_room` and + /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less + /// of its file, the sound linked to it follows, the head trim moves the + /// in-point, and one undo takes a whole gesture back. + /// + /// The routing *to* these doors -- the 6 px edge strip claiming the press + /// the clip's own body-drag would otherwise take -- is gpui hitbox + /// behaviour (`occlude`) and is not reachable without a window. + #[test] + fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() { + use engine::project::Edge; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let whole = session.lane_clips(Lane::V1)[0]; + let full = session.timeline_duration(); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::End), + Some((whole.start + 1, whole.end())), + "the file's own last frame is how far the tail goes" + ); + assert!( + !session.trim_clip(Lane::V1, 0, Edge::End, 9_999), + "it already plays all of it" + ); + + // Pulled in by a third: the timeline ends earlier and the sound with it. + let shorter = whole.end() - whole.len() / 3; + assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter)); + assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter); + assert_eq!( + session.lane_clips(Lane::A1)[0].end(), + shorter, + "the linked sound was trimmed with the picture" + ); + assert!(session.timeline_duration() < full, "and plays out earlier"); + + // ...and dragged back out, as far as the file goes and no further. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999)); + assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back"); + + // The head takes the in-point with it, so what plays at the new start + // is source frame 10 rather than source frame 0. + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10)); + let head = session.lane_clips(Lane::V1)[0]; + assert_eq!((head.start, head.in_frame), (10, 10)); + assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too"); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0), + Some(0), + "and it may be pulled back out to the file's first frame" + ); + + assert!(session.undo(), "one step for the whole drag"); + assert_eq!(session.lane_clips(Lane::V1)[0], whole); + } + /// The move-a-clip-between-tracks path through the door the drop uses /// ([`Player::move_clip`] calls exactly this): the clip changes row, the /// *picture* comes from the new row afterwards -- which is what "it plays @@ -6226,6 +6492,7 @@ fn main() { streams: HashMap::new(), clipboard: None, scrubbing: false, + trim: None, last_scrub: Instant::now(), last_target: 0, export: None, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index e0925df..ca7e4be 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -25,7 +25,7 @@ use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Demuxer, VideoMeta}; use crate::eq::EqParams; -use crate::project::{Clip, Lane, LaneKind, Project, Source, Span}; +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span}; use crate::scale::{Composer, FitPolicy}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -122,6 +122,15 @@ pub struct PlaybackSession { /// The edit list. Everything a caller says in seconds is a *timeline* /// position; only this maps it onto the file. project: Project, + /// How many frames each source actually holds, indexed exactly as + /// [`Project::sources`] is and grown with it. The project itself does not + /// know -- a clip names a source by index and carries its own range -- and + /// [`Self::trim_clip`] is the one edit that could ask for frames past the + /// end of a file, which is a save that would not open again + /// ([`Self::open_project`] refuses one by name). Append-only for + /// `sources`'s reason: an index handed out stays valid, undone import or + /// not. + counts: Vec, /// What the current video worker was opened for: where it sits on the /// timeline, how long it runs, and which source frame it started at -- /// together they rewrite a source frame index into a timeline one. Not a @@ -185,6 +194,7 @@ impl PlaybackSession { audio, audio_disabled, project, + counts: vec![meta.frame_count], span, eos: false, }) @@ -310,6 +320,7 @@ impl PlaybackSession { audio, audio_disabled, project, + counts, span, eos: false, }; @@ -591,6 +602,45 @@ impl PlaybackSession { self.edit(|p| p.move_to_lane(from, idx, to)) } + /// Drags one end of that clip to timeline frame `to`, changing how much of + /// its source it plays and nothing else on the lane -- see [`Project::trim`] + /// for the walls it is clamped by, which this fills the source lengths in + /// for. One undo step per call, so a front-end calls it once, at the release + /// of the drag. Reseeks like every other edit, which is what makes the + /// picture (and the sound) follow a new in-point straight away. `false` for + /// a bad index and for an edge already where it was asked to go. + /// + /// A *frame*, where the rest of this type takes seconds: a drag has already + /// asked [`trim_room`](Self::trim_room) where the edge may land, and that + /// answer is in frames -- converting it back through seconds would be a + /// rounding step between the width drawn and the width committed. + pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool { + // Spelled out rather than through `edit`, whose closure cannot hold a + // second borrow of the session while it has the project. + if !self.project.trim(lane, idx, edge, to, &self.counts) { + return false; + } + let now = self.now(); + self.seek(now); + true + } + + /// Where that edge may land, `(first, last)` timeline frame inclusive: what + /// a drag clamps the pointer to so the box it draws is the box + /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index. + pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> { + self.project.trim_room(lane, idx, edge, &self.counts) + } + + /// Records how long a source is, for a source index that may be one + /// `Project::import` just made or one it handed back. See [`Self::counts`]. + fn note_frames(&mut self, source: usize, frames: u32) { + if source == self.counts.len() { + self.counts.push(frames); + } + debug_assert_eq!(self.counts.len(), self.project.sources().len()); + } + /// The clip the picture is coming from at `timeline_secs`: the lane it sits /// on and its index there, by the same topmost-lane-wins rule the decoder /// follows. `None` over a gap and past the end. What a card that grades @@ -729,6 +779,7 @@ impl PlaybackSession { let first = self.first_audio()?; audio_matches(&wanted, &first)?; let source = self.project.import(path, stream); + self.note_frames(source, frames.max(1)); let clip = Clip { start: 0, in_frame: 0, @@ -820,6 +871,7 @@ impl PlaybackSession { let old_end = self.timeline_duration(); let source = self.project.import(path, 0); + self.note_frames(source, meta.frame_count); // Refused only for an unknown index, and this one just came from `import`. self.project.append_clip(source, meta.frame_count); // Reseek like any other edit, even though nothing before the playhead @@ -852,6 +904,7 @@ impl PlaybackSession { let old_end = self.timeline_duration(); let source = self.project.import(path, 0); + self.note_frames(source, frames); let at = self.project.timeline_frames(); self.project.place( Lane::A1, diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 011f4ac..ecfdbf9 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -212,6 +212,17 @@ impl LaneData { } } +/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Edge { + /// Its first timeline frame; moving it changes where in the source the clip + /// starts reading, so the picture behind the edge slides with it. + Start, + /// One past its last timeline frame; moving it only says how much of the + /// source to keep. + End, +} + /// What a lane holds over one stretch of the timeline: either a placed clip or /// a gap. Returned already trimmed to the position it was asked about, so a /// caller can hand `len` straight to a decoder (or to a black-frame generator). @@ -1031,6 +1042,140 @@ impl Project { true } + /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` -- + /// the drag on a clip's end that makes it play more or less of its source. + /// The rest of the lane stays exactly where it is (nothing ripples), so what + /// a shortened clip leaves behind is a gap and what a lengthened one takes + /// is room that was already empty. One snapshot, so a whole drag is one + /// [`Project::undo`] -- commit once, at the release, rather than per pointer + /// sample. Changes the timeline->source mapping: the caller must reseek. + /// + /// [`Edge::Start`] moves the in-point with it: the frames that stay play + /// exactly what they played before, which is what makes this a trim and not + /// a slip. + /// + /// `to` is **clamped**, never refused -- a hand pulling an edge past what is + /// legal means "as far as it goes", and stopping the box there is the + /// affordance. The walls are: one frame of clip always survives, an edge + /// never crosses the neighbouring clip on its own lane, an in-point never + /// walks back past the source's first frame, and an out-point never runs + /// past `source_frames[clip.source]` -- the caller's table of how long each + /// source actually is ([`Project`] does not know, and a clip ending past its + /// file's last frame is a save that will not open again; see + /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry + /// there may not grow at all. + /// + /// Linked clips trim *together*, to one clamped edge: a link is one span on + /// however many lanes ([`links_are_consistent`]), so a picture trimmed away + /// from its sound would be a group no save could load. The room is therefore + /// what every member of the group has -- the tightest wall wins. + /// + /// `false`, changing nothing and costing no undo step, for an index that is + /// not there and for an edge that is already where it was asked to go. + pub fn trim( + &mut self, + lane: Lane, + idx: usize, + edge: Edge, + to: u32, + source_frames: &[u32], + ) -> bool { + let (Some((lo, hi)), Some(clip)) = ( + self.trim_room(lane, idx, edge, source_frames), + self.lane(lane).get(idx).copied(), + ) else { + return false; + }; + let to = to.clamp(lo, hi); + let at = match edge { + Edge::Start => clip.start, + Edge::End => clip.end(), + }; + if to == at { + return false; + } + self.snapshot(); + for (l, i) in self.group_of(lane, idx).expect("checked above") { + let c = &mut self.lanes[l].clips[i]; + match edge { + Edge::Start => { + // Non-negative by `lo`, which is what keeps the in-point on + // the source. + c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32; + c.start = to; + } + Edge::End => c.out_frame = c.in_frame + (to - c.start), + } + debug_assert!(sorted_disjoint(&self.lanes[l].clips)); + } + true + } + + /// How far that edge may travel, `(first, last)` timeline frame inclusive -- + /// the walls [`trim`](Project::trim) clamps to, without moving anything. + /// What a front-end drawing the box *during* a drag asks, so the live width + /// is the width the release will commit and an edge stops under the pointer + /// rather than snapping back. `None` for an index that is not there. + pub fn trim_room( + &self, + lane: Lane, + idx: usize, + edge: Edge, + source_frames: &[u32], + ) -> Option<(u32, u32)> { + let (mut lo, mut hi) = (u32::MIN, u32::MAX); + for (l, i) in self.group_of(lane, idx)? { + let clips = &self.lanes[l].clips; + let c = clips[i]; + let (member_lo, member_hi) = match edge { + Edge::Start => ( + // Back to the source's own first frame, and never over the + // clip in front of it. + (c.start - c.in_frame).max(i.checked_sub(1).map_or(0, |p| clips[p].end())), + c.end() - 1, + ), + Edge::End => ( + c.start + 1, + // Out to whatever is left of the source, and never over the + // clip behind it. + c.start + .saturating_add( + source_frames + .get(c.source) + .copied() + .unwrap_or(c.out_frame) + .saturating_sub(c.in_frame), + ) + .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)), + ), + }; + lo = lo.max(member_lo); + hi = hi.min(member_hi); + } + // `hi.max(lo)`: for a clip the invariants hold for, the range always + // contains the edge's own place, and a caller's wrong `source_frames` + // must not become an empty range (or a panicking `clamp`) here. + Some((lo, hi.max(lo))) + } + + /// The clips that move as one with the clip at `idx` of `lane` -- itself and + /// whatever carries its link on the other lanes -- as `(lane storage index, + /// clip index)` pairs. `None` for an index that is not there. + fn group_of(&self, lane: Lane, idx: usize) -> Option> { + let clip = *self.lane(lane).get(idx)?; + Some(match clip.link { + Some(link) => self + .lanes + .iter() + .enumerate() + .filter_map(|(l, data)| { + Some((l, data.clips.iter().position(|c| c.link == Some(link))?)) + }) + .collect(), + None => vec![(self.index(lane).expect("the clip was found on it"), idx)], + }) + } + /// Insert `clip` into the first lane of each kind at `timeline_frame` as one /// new group, pushing everything from there on later by its length in /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip @@ -2093,6 +2238,115 @@ mod tests { assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]); } + /// How long `FILE` is, which is what a trim's tail is allowed to reach: + /// [`three`] cuts up all nine of its frames. + const SRC: &[u32] = &[9]; + + /// The drag on a clip's tail: it plays less (or more) of its source, nothing + /// else on the lane moves, and every wall stops the edge rather than + /// refusing the gesture. + #[test] + fn trimming_the_tail_stops_at_every_wall() { + let mut p = three(); + + // Pulled in: a gap opens behind it and the clip after it stays put. + assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC)); + assert_eq!( + shape(&p)[0], + vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)] + ); + assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing"); + assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap"); + + // ...and back out, no further than the clip behind it. + assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC)); + assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour"); + assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall"); + + // One frame of clip always survives, however far back the pointer went. + assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC)); + assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0)); + + // The last clip has no neighbour, so what stops it is the file: nine + // frames is nine frames. + assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC)); + assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC)); + assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take"); + assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further"); + // A source nobody told us the length of may not grow at all -- an + // out-point past the end of a file is a save that will not open again. + assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[])); + assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown"); + } + + /// The head pulled in takes the in-point with it -- what stays plays what it + /// always played -- and stops at the source's own first frame. + #[test] + fn trimming_the_head_moves_the_in_point() { + let mut p = three(); + assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); + assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front"); + assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2"); + assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap"); + assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again"); + assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0)); + // One frame survives here too. + assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC)); + assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0)); + + // A clip that does not begin at its source's first frame: its head goes + // back to source frame 0 and not one frame further. + let mut p = Project::single(FILE, 9); + assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0))); + assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it"); + assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC)); + assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left"); + } + + /// Linked halves trim as one: a link is one span on however many lanes, so + /// the sound follows the picture's edge -- and the tightest wall of the two + /// is what stops both. + #[test] + fn linked_halves_trim_together() { + let mut p = three(); + let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids"); + assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped"); + + assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC)); + assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0)); + assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed"); + assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it"); + assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows"); + links_are_consistent(&p.lanes).expect("one id per lane, one span"); + + // Something in the way on the *audio* lane stops the picture's tail as + // well: the group can only go as far as its tightest member. + assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0))); + assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC)); + assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip"); + assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0)); + links_are_consistent(&p.lanes).expect("still one span"); + } + + /// A whole drag is one undo step -- the front-end commits once, at the + /// release -- and an edge asked to stay where it is costs none at all. + #[test] + fn a_trim_is_one_undo_step() { + let mut p = three(); + let before = shape(&p); + let history = p.history.len(); + + assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC)); + assert_eq!(p.history.len(), history + 1, "one snapshot per gesture"); + assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there"); + assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip"); + assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC)); + assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing"); + + assert!(p.undo()); + assert_eq!(shape(&p), before, "both halves back, in one step"); + } + /// A moved half stays in its group: a link names a span, not a lane, so the /// picture on `V2` is still the same take as the sound under it on `A1`. #[test] diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 308e03e..eb828ab 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -100,6 +100,44 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() { std::fs::remove_dir_all(&dir).expect("cleanup"); } +/// Why a trim's tail stops where the file ends: a clip reaching past the last +/// frame of its source is a project that will not open again (`open_project` +/// refuses it by name). Pulled in on both ends and then dragged out as far as +/// the pointer can ask for, the save still comes back as itself. +#[test] +fn a_trimmed_timeline_saves_and_opens_again() { + use engine::project::Edge; + + let dir = scratch("trim"); + let media = copy_in(&dir, "test_av.mp4"); + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + let whole = session.clip_at(0).expect("one clip"); + + assert!(session.trim_clip(Lane::V1, 0, Edge::End, whole.end() / 2)); + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 5)); + let path = dir.join("trimmed.edith"); + session.save_project(&path).expect("save"); + let loaded = PlaybackSession::open_project(&path).expect("a trimmed project opens"); + assert_eq!( + loaded.clip_at(0).map(|c| (c.start, c.in_frame, c.out_frame)), + Some((5, 5, whole.end() / 2)), + "the trimmed range is what came back" + ); + + // A hand that keeps pulling: the tail stops at the file's own last frame, + // and the save of *that* opens too. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, u32::MAX)); + assert_eq!( + session.clip_at(0).expect("still one clip").out_frame, + whole.out_frame, + "as far as the file goes and not one frame further" + ); + session.save_project(&path).expect("save"); + PlaybackSession::open_project(&path).expect("and it still opens"); + std::fs::remove_dir_all(&dir).expect("cleanup"); +} + /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline /// with something to lose in every field. fn edited(dir: &Path) -> PlaybackSession {