forge
Explore
Log in

Don't you dare go Hollow

Copy/paste clips at playhead

Browse files at this commit

aae5734f1ad57203fd28fc52a041d66f645891b9Ahmet Kaan GümüşParent: 79c1a91
  • feat
    • copy/paste clips at playhead
Show full message
✨ feat: copy/paste clips at playhead

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<Clip> clipboard on ctrl+c / ctrl+v.
crates/app/src/main.rsmodified+38 -6
@@ -3,7 +3,7 @@ use std::rc::Rc;
3 use std::sync::Arc;3 use std::sync::Arc;
4 use std::time::{Duration, Instant};4 use std::time::{Duration, Instant};
5 5
6-use engine::{Frame, PlaybackSession};6+use engine::{Clip, Frame, PlaybackSession};
7 use gpui::{7 use gpui::{
8 App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,8 App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,
9 MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions,9 MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions,
@@ -52,6 +52,9 @@ struct Player {
52 /// Which clip the edit keys act on. Indices move under every edit, so this52 /// Which clip the edit keys act on. Indices move under every edit, so this
53 /// is cleared by all of them.53 /// is cleared by all of them.
54 selected: Option<usize>,54 selected: Option<usize>,
55+ /// The copied clip. Frame ranges only, so it survives the clip it was taken
56+ /// from being deleted -- and it outlives the selection.
57+ clipboard: Option<Clip>,
55 /// A drag that started on the ruler. Moves anywhere in the window scrub58 /// A drag that started on the ruler. Moves anywhere in the window scrub
56 /// while it is set; the release commits the exact position.59 /// while it is set; the release commits the exact position.
57 scrubbing: bool,60 scrubbing: bool,
@@ -167,6 +170,26 @@ impl Player {
167 cx.notify();170 cx.notify();
168 }171 }
169 172
173+ /// Copies the selected clip. Nothing on screen changes, so no notify.
174+ fn copy_selected(&mut self) {
175+ if let Some(clip) = self.selected.and_then(|i| self.session.clip_at(i)) {
176+ self.clipboard = Some(clip);
177+ }
178+ }
179+
180+ /// Drops the copied clip in at the playhead. The engine reseeks itself, so
181+ /// like a delete this owes the flag reset -- and the selection, whose index
182+ /// the insert has just moved.
183+ fn paste(&mut self, cx: &mut Context<Self>) {
184+ if let Some(clip) = self.clipboard
185+ && self.session.paste_at(self.session.now(), clip)
186+ {
187+ self.selected = None;
188+ self.reset_after_reseek();
189+ }
190+ cx.notify();
191+ }
192+
170 fn undo(&mut self, cx: &mut Context<Self>) {193 fn undo(&mut self, cx: &mut Context<Self>) {
171 if self.session.undo() {194 if self.session.undo() {
172 self.reset_after_reseek();195 self.reset_after_reseek();
@@ -241,11 +264,19 @@ impl Render for Player {
241 if event.is_held {264 if event.is_held {
242 return;265 return;
243 }266 }
244- match event.keystroke.key.as_str() {267+ // On linux gpui reports ctrl-c as key "c" with the control
245- "space" => this.toggle_or_restart(cx),268+ // modifier set (the control code is mapped back), so the plain
246- "c" => this.cut(cx),269+ // and modified bindings are told apart here and nowhere else.
247- "x" | "delete" => this.delete_selected(cx),270+ match (
248- "z" => this.undo(cx),271+ event.keystroke.key.as_str(),
272+ event.keystroke.modifiers.control,
273+ ) {
274+ ("space", _) => this.toggle_or_restart(cx),
275+ ("c", true) => this.copy_selected(),
276+ ("v", true) => this.paste(cx),
277+ ("c", false) => this.cut(cx),
278+ ("x", _) | ("delete", _) => this.delete_selected(cx),
279+ ("z", _) => this.undo(cx),
249 _ => {}280 _ => {}
250 }281 }
251 }))282 }))
@@ -661,6 +692,7 @@ fn main() {
661 pending_seek: false,692 pending_seek: false,
662 ruler: Rc::default(),693 ruler: Rc::default(),
663 selected: None,694 selected: None,
695+ clipboard: None,
664 scrubbing: false,696 scrubbing: false,
665 last_scrub: Instant::now(),697 last_scrub: Instant::now(),
666 last_target: 0,698 last_target: 0,
crates/engine/src/playback.rsmodified+15 -0
@@ -226,6 +226,21 @@ impl PlaybackSession {
226 .cut(secs_to_frame(timeline_secs, self.meta.frame_rate))226 .cut(secs_to_frame(timeline_secs, self.meta.frame_rate))
227 }227 }
228 228
229+ /// The clip at `idx` -- what a caller copies. It is a pair of source frame
230+ /// numbers and nothing else, so a copy stays valid after the clip it came
231+ /// from is deleted. `None` past the end.
232+ pub fn clip_at(&self, idx: usize) -> Option<Clip> {
233+ self.project.clips().get(idx).copied()
234+ }
235+
236+ /// Inserts `clip` at the playhead, splitting the clip under it. Like a
237+ /// delete this moves every following frame, so the session reseeks; past
238+ /// the end of the timeline the clip is appended. One undo step.
239+ pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
240+ let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
241+ self.edit(|p| p.paste(at, clip))
242+ }
243+
229 /// Removes a clip and closes the gap. Unlike a cut this *does* move every244 /// Removes a clip and closes the gap. Unlike a cut this *does* move every
230 /// following frame, so the session reseeks to wherever the playhead now245 /// following frame, so the session reseeks to wherever the playhead now
231 /// points. `false` for a bad index or the last remaining clip.246 /// points. `false` for a bad index or the last remaining clip.
crates/engine/src/project.rsmodified+129 -0
@@ -111,6 +111,43 @@ impl Project {
111 true111 true
112 }112 }
113 113
114+ /// Insert `clip` so that it starts at `timeline_frame`. Mid-clip the
115+ /// containing clip is split there and `clip` goes between the halves; at an
116+ /// existing boundary (0 included) it goes in front of the clip that starts
117+ /// there; at or past the end of the timeline it is appended -- a paste past
118+ /// the end clamps rather than refuses, because there is nothing between the
119+ /// end and it. Refused only for an empty `clip`, which the never-empty
120+ /// invariant forbids but the public fields still allow a caller to build.
121+ ///
122+ /// Exactly one history snapshot, so one [`Project::undo`] takes it back --
123+ /// hence the splice rather than a `cut` plus an insert. Changes the
124+ /// timeline->source mapping: the caller must reseek.
125+ pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
126+ if clip.out_frame <= clip.in_frame {
127+ return false;
128+ }
129+ self.history.push(self.clips.clone());
130+ match self.map_timeline(timeline_frame) {
131+ Some((idx, source)) if source > self.clips[idx].in_frame => {
132+ let out = self.clips[idx].out_frame;
133+ self.clips[idx].out_frame = source;
134+ self.clips.splice(
135+ idx + 1..idx + 1,
136+ [
137+ clip,
138+ Clip {
139+ in_frame: source,
140+ out_frame: out,
141+ },
142+ ],
143+ );
144+ }
145+ Some((idx, _)) => self.clips.insert(idx, clip),
146+ None => self.clips.push(clip),
147+ }
148+ true
149+ }
150+
114 /// Remove a clip and close the gap. Refused for an out-of-range index and151 /// Remove a clip and close the gap. Refused for an out-of-range index and
115 /// for the last remaining clip (an empty timeline is undefined this slice).152 /// for the last remaining clip (an empty timeline is undefined this slice).
116 /// Changes the timeline->source mapping: the caller must reseek.153 /// Changes the timeline->source mapping: the caller must reseek.
@@ -270,6 +307,98 @@ mod tests {
270 assert_eq!(p.map_timeline(9), None);307 assert_eq!(p.map_timeline(9), None);
271 }308 }
272 309
310+ /// The clip a copy would hand back: source `[100, 102)`, unrelated to
311+ /// anything in `three()` so it is recognisable wherever it lands.
312+ const PASTED: Clip = Clip {
313+ in_frame: 100,
314+ out_frame: 102,
315+ };
316+
317+ #[test]
318+ fn paste_mid_clip_splits_around_it() {
319+ let mut p = three();
320+ assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
321+ assert_eq!(p.timeline_frames(), 11);
322+ assert_eq!(
323+ p.clips(),
324+ [
325+ Clip {
326+ in_frame: 0,
327+ out_frame: 3
328+ },
329+ Clip {
330+ in_frame: 3,
331+ out_frame: 5
332+ },
333+ Clip {
334+ in_frame: 5,
335+ out_frame: 6
336+ },
337+ PASTED,
338+ Clip {
339+ in_frame: 6,
340+ out_frame: 9
341+ },
342+ ]
343+ );
344+ // The pasted frames are exactly where they were asked for, and the
345+ // split-off remainder resumes after them.
346+ assert_eq!(p.map_timeline(6), Some((3, 100)));
347+ assert_eq!(p.map_timeline(7), Some((3, 101)));
348+ assert_eq!(p.map_timeline(8), Some((4, 6)));
349+ }
350+
351+ #[test]
352+ fn paste_at_boundary_zero_and_end() {
353+ let mut p = three();
354+ assert!(p.paste(3, PASTED), "existing boundary: no split");
355+ assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
356+ assert_eq!(p.map_timeline(3), Some((1, 100)));
357+
358+ let mut p = three();
359+ assert!(p.paste(0, PASTED));
360+ assert_eq!(p.map_timeline(0), Some((0, 100)));
361+ assert_eq!(p.map_timeline(2), Some((1, 0)));
362+
363+ // At the end and past it both append -- there is nothing to sit before.
364+ let mut p = three();
365+ assert!(p.paste(9, PASTED));
366+ assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
367+ assert!(p.paste(1_000, PASTED));
368+ assert_eq!(p.timeline_frames(), 13);
369+
370+ // An empty clip is the one thing refused, and it pushes no history.
371+ let mut p = three();
372+ assert!(!p.paste(
373+ 4,
374+ Clip {
375+ in_frame: 7,
376+ out_frame: 7
377+ }
378+ ));
379+ assert_eq!(p.clips().len(), 3);
380+ }
381+
382+ #[test]
383+ fn paste_undoes_in_one_step() {
384+ let mut p = three();
385+ let before = p.clips().to_vec();
386+ assert!(p.paste(6, PASTED));
387+ assert!(p.undo());
388+ assert_eq!(p.clips(), before.as_slice(), "a paste is one undo step");
389+ }
390+
391+ #[test]
392+ fn a_copy_outlives_the_clip_it_came_from() {
393+ let mut p = three();
394+ let copied = p.clips()[1]; // [3,5)
395+ assert!(p.delete(1));
396+ // Just a frame range: the source is still on disk either way.
397+ assert!(p.paste(0, copied));
398+ assert_eq!(p.map_timeline(0), Some((0, 3)));
399+ assert_eq!(p.timeline_frames(), 9);
400+ }
401+
273 #[test]402 #[test]
274 fn delete_closes_the_gap() {403 fn delete_closes_the_gap() {
275 let mut p = three();404 let mut p = three();
crates/engine/tests/playback.rsmodified+74 -0
@@ -400,6 +400,80 @@ fn edits_traverse_cuts() {
400 );400 );
401 }401 }
402 402
403+/// Copy and paste. A clipboard clip is a pair of *source* frame numbers, so the
404+/// pasted stretch has to decode its own range -- not the frames the timeline
405+/// used to hold at that position.
406+#[test]
407+fn paste_duplicates_a_clip_at_the_playhead() {
408+ let path = asset("test_baseline.mp4");
409+ let mut session = PlaybackSession::open(&path).expect("open");
410+ let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
411+ let whole = f64::from(total) / fps;
412+
413+ assert!(session.cut_at(2.0), "cut at 2 s");
414+ let copied = session.clip_at(0).expect("clip 0");
415+ let copied_len = copied.len();
416+ assert_eq!(copied_len, (2.0 * fps) as u32);
417+ assert!(session.clip_at(2).is_none(), "only two clips so far");
418+
419+ // Mid-clip: the paste splits clip 1 and lands between the halves.
420+ let at = (4.0 * fps) as u32;
421+ assert!(session.paste_at(4.0, copied), "paste at 4 s");
422+ assert_eq!(session.clip_spans().len(), 4);
423+ let grown = total + copied_len;
424+ assert!(
425+ (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9,
426+ "duration after the paste: {}",
427+ session.timeline_duration()
428+ );
429+
430+ // Play the edited timeline from the top, keeping the two seam frames.
431+ session.seek(0.0);
432+ session.play();
433+ let deadline = Instant::now() + Duration::from_secs(30);
434+ let (mut expect, mut pasted, mut resumed) = (0, None, None);
435+ loop {
436+ session.tick();
437+ while let Some(frame) = session.try_frame() {
438+ assert_eq!(frame.index, expect, "timeline indices must be contiguous");
439+ if frame.index == at {
440+ pasted = Some(frame.bgra);
441+ } else if frame.index == at + copied_len {
442+ resumed = Some(frame.bgra);
443+ }
444+ expect += 1;
445+ }
446+ if session.is_eos() {
447+ break;
448+ }
449+ assert!(Instant::now() < deadline, "still draining after 30 s");
450+ sleep(Duration::from_millis(4));
451+ }
452+ assert_eq!(expect, grown, "the pasted timeline, whole and nothing but");
453+ // As above: an edit reseeks to *now*, so stop the clock before asserting.
454+ session.pause();
455+
456+ // At the paste position the picture is the copied clip's first frame, and
457+ // the split-off remainder resumes exactly where it was interrupted.
458+ assert!(
459+ pasted.expect("no frame at the paste") == source_frame(&path, copied.in_frame),
460+ "the paste is not showing source {}",
461+ copied.in_frame
462+ );
463+ assert!(
464+ resumed.expect("no frame after the paste") == source_frame(&path, at),
465+ "the timeline did not resume at source {at}"
466+ );
467+
468+ assert!(session.undo(), "undo the paste");
469+ assert_eq!(session.clip_spans().len(), 2, "one step, back to the cut");
470+ assert!(
471+ (session.timeline_duration() - whole).abs() < 1e-9,
472+ "undo did not restore the duration: {}",
473+ session.timeline_duration()
474+ );
475+}
476+
403 /// Editing while the device is running. A cut must not disturb playback at all477 /// Editing while the device is running. A cut must not disturb playback at all
404 /// and a delete reseeks under it -- in both cases the audio keeps coming, which478 /// and a delete reseeks under it -- in both cases the audio keeps coming, which
405 /// is what stops `tick` from handing the timeline back to wall time.479 /// is what stops `tick` from handing the timeline back to wall time.