From aae5734f1ad57203fd28fc52a041d66f645891b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 17:57:16 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20copy/paste=20clips=20at=20p?= =?UTF-8?q?layhead?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Project::paste splices a clip in at a timeline position, splitting the clip under it when the position is mid-clip and appending past the end. One history snapshot, so one undo takes a paste back. PlaybackSession::clip_at hands a clip out for copying and paste_at goes through the same edit() reseek as delete/undo. The app keeps an Option clipboard on ctrl+c / ctrl+v. --- crates/app/src/main.rs | 44 +++++++++-- crates/engine/src/playback.rs | 15 ++++ crates/engine/src/project.rs | 129 ++++++++++++++++++++++++++++++++ crates/engine/tests/playback.rs | 74 ++++++++++++++++++ 4 files changed, 256 insertions(+), 6 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index c4bba84..d990b37 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use std::sync::Arc; use std::time::{Duration, Instant}; -use engine::{Frame, PlaybackSession}; +use engine::{Clip, Frame, PlaybackSession}; use gpui::{ App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions, @@ -52,6 +52,9 @@ struct Player { /// Which clip the edit keys act on. Indices move under every edit, so this /// is cleared by all of them. selected: Option, + /// The copied clip. Frame ranges only, so it survives the clip it was taken + /// from being deleted -- and it outlives the selection. + clipboard: Option, /// 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, @@ -167,6 +170,26 @@ impl Player { cx.notify(); } + /// Copies the selected clip. Nothing on screen changes, so no notify. + fn copy_selected(&mut self) { + if let Some(clip) = self.selected.and_then(|i| self.session.clip_at(i)) { + self.clipboard = Some(clip); + } + } + + /// Drops the copied clip in at the playhead. The engine reseeks itself, so + /// like a delete this owes the flag reset -- and the selection, whose index + /// the insert has just moved. + fn paste(&mut self, cx: &mut Context) { + if let Some(clip) = self.clipboard + && self.session.paste_at(self.session.now(), clip) + { + self.selected = None; + self.reset_after_reseek(); + } + cx.notify(); + } + fn undo(&mut self, cx: &mut Context) { if self.session.undo() { self.reset_after_reseek(); @@ -241,11 +264,19 @@ impl Render for Player { if event.is_held { return; } - match event.keystroke.key.as_str() { - "space" => this.toggle_or_restart(cx), - "c" => this.cut(cx), - "x" | "delete" => this.delete_selected(cx), - "z" => this.undo(cx), + // On linux gpui reports ctrl-c as key "c" with the control + // modifier set (the control code is mapped back), so the plain + // and modified bindings are told apart here and nowhere else. + match ( + event.keystroke.key.as_str(), + event.keystroke.modifiers.control, + ) { + ("space", _) => this.toggle_or_restart(cx), + ("c", true) => this.copy_selected(), + ("v", true) => this.paste(cx), + ("c", false) => this.cut(cx), + ("x", _) | ("delete", _) => this.delete_selected(cx), + ("z", _) => this.undo(cx), _ => {} } })) @@ -661,6 +692,7 @@ fn main() { pending_seek: false, ruler: Rc::default(), selected: None, + clipboard: None, scrubbing: false, last_scrub: Instant::now(), last_target: 0, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 1e421d3..6fd4929 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -226,6 +226,21 @@ impl PlaybackSession { .cut(secs_to_frame(timeline_secs, self.meta.frame_rate)) } + /// The clip at `idx` -- what a caller copies. It is a pair of source frame + /// numbers and nothing else, so a copy stays valid after the clip it came + /// from is deleted. `None` past the end. + pub fn clip_at(&self, idx: usize) -> Option { + self.project.clips().get(idx).copied() + } + + /// Inserts `clip` at the playhead, splitting the clip under it. Like a + /// delete this moves every following frame, so the session reseeks; past + /// the end of the timeline the clip is appended. One undo step. + pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool { + let at = secs_to_frame(timeline_secs, self.meta.frame_rate); + self.edit(|p| p.paste(at, clip)) + } + /// Removes a clip and closes the gap. Unlike a cut this *does* move every /// following frame, so the session reseeks to wherever the playhead now /// points. `false` for a bad index or the last remaining clip. diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 76d56ea..5140b8e 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -111,6 +111,43 @@ impl Project { true } + /// Insert `clip` so that it starts at `timeline_frame`. Mid-clip the + /// containing clip is split there and `clip` goes between the halves; at an + /// existing boundary (0 included) it goes in front of the clip that starts + /// there; at or past the end of the timeline it is appended -- a paste past + /// the end clamps rather than refuses, because there is nothing between the + /// end and it. Refused only for an empty `clip`, which the never-empty + /// invariant forbids but the public fields still allow a caller to build. + /// + /// Exactly one history snapshot, so one [`Project::undo`] takes it back -- + /// hence the splice rather than a `cut` plus an insert. Changes the + /// timeline->source mapping: the caller must reseek. + pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool { + if clip.out_frame <= clip.in_frame { + return false; + } + self.history.push(self.clips.clone()); + match self.map_timeline(timeline_frame) { + Some((idx, source)) if source > self.clips[idx].in_frame => { + let out = self.clips[idx].out_frame; + self.clips[idx].out_frame = source; + self.clips.splice( + idx + 1..idx + 1, + [ + clip, + Clip { + in_frame: source, + out_frame: out, + }, + ], + ); + } + Some((idx, _)) => self.clips.insert(idx, clip), + None => self.clips.push(clip), + } + true + } + /// Remove a clip and close the gap. Refused for an out-of-range index and /// for the last remaining clip (an empty timeline is undefined this slice). /// Changes the timeline->source mapping: the caller must reseek. @@ -270,6 +307,98 @@ mod tests { assert_eq!(p.map_timeline(9), None); } + /// The clip a copy would hand back: source `[100, 102)`, unrelated to + /// anything in `three()` so it is recognisable wherever it lands. + const PASTED: Clip = Clip { + in_frame: 100, + out_frame: 102, + }; + + #[test] + fn paste_mid_clip_splits_around_it() { + let mut p = three(); + assert!(p.paste(6, PASTED)); // inside [5,9), one frame in + assert_eq!(p.timeline_frames(), 11); + assert_eq!( + p.clips(), + [ + Clip { + in_frame: 0, + out_frame: 3 + }, + Clip { + in_frame: 3, + out_frame: 5 + }, + Clip { + in_frame: 5, + out_frame: 6 + }, + PASTED, + Clip { + in_frame: 6, + out_frame: 9 + }, + ] + ); + // The pasted frames are exactly where they were asked for, and the + // split-off remainder resumes after them. + assert_eq!(p.map_timeline(6), Some((3, 100))); + assert_eq!(p.map_timeline(7), Some((3, 101))); + assert_eq!(p.map_timeline(8), Some((4, 6))); + } + + #[test] + fn paste_at_boundary_zero_and_end() { + let mut p = three(); + assert!(p.paste(3, PASTED), "existing boundary: no split"); + assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]); + assert_eq!(p.map_timeline(3), Some((1, 100))); + + let mut p = three(); + assert!(p.paste(0, PASTED)); + assert_eq!(p.map_timeline(0), Some((0, 100))); + assert_eq!(p.map_timeline(2), Some((1, 0))); + + // At the end and past it both append -- there is nothing to sit before. + let mut p = three(); + assert!(p.paste(9, PASTED)); + assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]); + assert!(p.paste(1_000, PASTED)); + assert_eq!(p.timeline_frames(), 13); + + // An empty clip is the one thing refused, and it pushes no history. + let mut p = three(); + assert!(!p.paste( + 4, + Clip { + in_frame: 7, + out_frame: 7 + } + )); + assert_eq!(p.clips().len(), 3); + } + + #[test] + fn paste_undoes_in_one_step() { + let mut p = three(); + let before = p.clips().to_vec(); + assert!(p.paste(6, PASTED)); + assert!(p.undo()); + assert_eq!(p.clips(), before.as_slice(), "a paste is one undo step"); + } + + #[test] + fn a_copy_outlives_the_clip_it_came_from() { + let mut p = three(); + let copied = p.clips()[1]; // [3,5) + assert!(p.delete(1)); + // Just a frame range: the source is still on disk either way. + assert!(p.paste(0, copied)); + assert_eq!(p.map_timeline(0), Some((0, 3))); + assert_eq!(p.timeline_frames(), 9); + } + #[test] fn delete_closes_the_gap() { let mut p = three(); diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index 158f7ed..80a76ca 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -400,6 +400,80 @@ fn edits_traverse_cuts() { ); } +/// Copy and paste. A clipboard clip is a pair of *source* frame numbers, so the +/// pasted stretch has to decode its own range -- not the frames the timeline +/// used to hold at that position. +#[test] +fn paste_duplicates_a_clip_at_the_playhead() { + let path = asset("test_baseline.mp4"); + let mut session = PlaybackSession::open(&path).expect("open"); + let (fps, total) = (session.meta().frame_rate, session.meta().frame_count); + let whole = f64::from(total) / fps; + + assert!(session.cut_at(2.0), "cut at 2 s"); + let copied = session.clip_at(0).expect("clip 0"); + let copied_len = copied.len(); + assert_eq!(copied_len, (2.0 * fps) as u32); + assert!(session.clip_at(2).is_none(), "only two clips so far"); + + // Mid-clip: the paste splits clip 1 and lands between the halves. + let at = (4.0 * fps) as u32; + assert!(session.paste_at(4.0, copied), "paste at 4 s"); + assert_eq!(session.clip_spans().len(), 4); + let grown = total + copied_len; + assert!( + (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9, + "duration after the paste: {}", + session.timeline_duration() + ); + + // Play the edited timeline from the top, keeping the two seam frames. + session.seek(0.0); + session.play(); + let deadline = Instant::now() + Duration::from_secs(30); + let (mut expect, mut pasted, mut resumed) = (0, None, None); + loop { + session.tick(); + while let Some(frame) = session.try_frame() { + assert_eq!(frame.index, expect, "timeline indices must be contiguous"); + if frame.index == at { + pasted = Some(frame.bgra); + } else if frame.index == at + copied_len { + resumed = Some(frame.bgra); + } + expect += 1; + } + if session.is_eos() { + break; + } + assert!(Instant::now() < deadline, "still draining after 30 s"); + sleep(Duration::from_millis(4)); + } + assert_eq!(expect, grown, "the pasted timeline, whole and nothing but"); + // As above: an edit reseeks to *now*, so stop the clock before asserting. + session.pause(); + + // At the paste position the picture is the copied clip's first frame, and + // the split-off remainder resumes exactly where it was interrupted. + assert!( + pasted.expect("no frame at the paste") == source_frame(&path, copied.in_frame), + "the paste is not showing source {}", + copied.in_frame + ); + assert!( + resumed.expect("no frame after the paste") == source_frame(&path, at), + "the timeline did not resume at source {at}" + ); + + assert!(session.undo(), "undo the paste"); + assert_eq!(session.clip_spans().len(), 2, "one step, back to the cut"); + assert!( + (session.timeline_duration() - whole).abs() < 1e-9, + "undo did not restore the duration: {}", + session.timeline_duration() + ); +} + /// Editing while the device is running. A cut must not disturb playback at all /// and a delete reseeks under it -- in both cases the audio keeps coming, which /// is what stops `tick` from handing the timeline back to wall time.