FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Edit: Copy, Cut and Paste work on captions selected in the Timeline (#3041)
Tex Jerniganbd4139e43039
diff --git a/crates/engine/src/captions.rs b/crates/engine/src/captions.rsindex d620a9f8d..3a13cbe9f 100644--- a/crates/engine/src/captions.rs+++ b/crates/engine/src/captions.rs@@ -164,6 +164,58 @@ pub fn delete(s: &mut Session, ids: &[ClipId], ripple: bool) -> Result<Value> {Ok(json!({"deleted": n}))}+/// Copy the selected captions to the caption clipboard (Edit ▸ Copy / Cut with captions selected).+/// Returns how many were copied.+pub fn copy(s: &mut Session) -> usize {+ let Some(q) = s.active_sequence() else { return 0 };+ let sel = &s.state.caption_selection;+ let picked: Vec<(usize, filmcraft_project::Caption)> =+ q.caption_tracks.iter().enumerate().flat_map(|(ti, t)| t.captions.iter().filter(|c| sel.contains(&c.id)).map(move |c| (ti, c.clone()))).collect();+ let min = picked.iter().map(|(_, c)| c.start).min().unwrap_or_default();+ s.state.caption_clipboard = picked.into_iter().map(|(ti, c)| (ti, filmcraft_project::Caption { start: c.start - min, ..c })).collect();+ s.state.clipboard.clear();+ s.state.clipboard_markers.clear();+ s.state.caption_clipboard.len()+}++/// Paste the caption clipboard at the playhead, each caption on the caption track it was copied+/// from (the last one when that track is gone), overwriting what is there. Paste Insert first opens+/// a gap the copied span long on those tracks. The pasted captions are selected and the playhead+/// moves to their end.+pub fn paste(s: &mut Session, insert: bool) -> Result<Value> {+ let at = s.playhead();+ let clip = s.state.caption_clipboard.clone();+ let span = clip.iter().map(|(_, c)| c.end()).max().unwrap_or_default();+ let mut by_track: Vec<(TrackId, Vec<filmcraft_project::Caption>)> = Vec::new();+ {+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ for (ti, c) in clip {+ let Some(t) = q.caption_tracks.get(ti).or(q.caption_tracks.last()) else {+ return Err(bad("edit.paste", "the sequence has no caption track to paste into"));+ };+ let c = filmcraft_project::Caption { start: c.start + at, ..c };+ match by_track.iter_mut().find(|(id, _)| *id == t.id) {+ Some((_, v)) => v.push(c),+ None => by_track.push((t.id, vec![c])),+ }+ }+ }+ let ids = s.edit_sequence(if insert { "Paste Insert Captions" } else { "Paste Captions" }, |q, ctx, st| {+ let mut ids = Vec::new();+ for (tid, caps) in &by_track {+ if insert && let Some(tr) = q.caption_track_mut(*tid).filter(|t| !t.locked) {+ edit::captions::insert_gap(tr, at, span, ctx);+ }+ ids.extend(edit::captions::overwrite_captions(q, *tid, caps, ctx)?);+ }+ st.caption_selection = ids.clone();+ st.selection.clear();+ Ok(ids)+ })?;+ s.set_playhead(at + span);+ Ok(json!({"captions": ids.iter().map(|c| c.0).collect::<Vec<_>>()}))+}+fn caption_json(s: &Session, c: &filmcraft_project::Caption) -> Value {let q = s.active_sequence();let (rate, df) = q.map(|q| (q.settings.frame_rate, q.settings.drop_frame)).unwrap_or_default();diff --git a/crates/engine/src/captions_tests.rs b/crates/engine/src/captions_tests.rsindex 2f33951e6..a8b10c8db 100644--- a/crates/engine/src/captions_tests.rs+++ b/crates/engine/src/captions_tests.rs@@ -191,3 +191,36 @@ fn captions_duplicate_copies_and_overwrites() {assert_eq!(s.active_sequence().unwrap().caption_tracks[0].captions.len(), before + 1, "a caption named twice is copied once");s.active_sequence().unwrap().check().unwrap();}++#[test]+fn captions_copy_cut_and_paste() {+ let mut s = demo();+ // Copy / Paste with only captions selected copies captions, pasted at the playhead+ s.execute("playhead.set", json!({"seconds": 1.0})).unwrap();+ s.execute("captions.add", json!({"text": "hi", "durationSeconds": 1.0})).unwrap();+ assert!(s.state.selection.is_empty());+ assert_eq!(s.execute("edit.copy", json!({})).unwrap()["copied"], 1);+ s.execute("playhead.set", json!({"seconds": 10.0})).unwrap();+ s.execute("edit.paste", json!({})).unwrap();+ assert_eq!(caption_spans(&s), vec![(1.0, 2.0, "hi".into()), (10.0, 11.0, "hi".into())]);+ assert!((s.playhead().seconds() - 11.0).abs() < 0.05, "the playhead moves past the paste");+ // Cut takes it away and Paste puts it back+ s.execute("edit.cut", json!({})).unwrap();+ assert_eq!(caption_spans(&s), vec![(1.0, 2.0, "hi".into())]);+ s.execute("playhead.set", json!({"seconds": 4.0})).unwrap();+ s.execute("edit.paste", json!({})).unwrap();+ assert_eq!(caption_spans(&s)[1], (4.0, 5.0, "hi".into()));+ // copying clips afterwards makes Paste place clips again, not captions+ let clip = s.active_sequence().unwrap().video_tracks[0].items[0].id;+ s.execute("timeline.select", json!({"clips": [clip.0]})).unwrap();+ s.execute("edit.copy", json!({})).unwrap();+ assert!(s.state.caption_clipboard.is_empty() && !s.state.clipboard.is_empty());+ // undo takes back a caption paste as one step+ let mut s = demo();+ s.execute("captions.add", json!({"text": "x", "durationSeconds": 1.0})).unwrap();+ s.execute("edit.copy", json!({})).unwrap();+ s.execute("playhead.set", json!({"seconds": 5.0})).unwrap();+ s.execute("edit.paste", json!({})).unwrap();+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(caption_spans(&s).len(), 1);+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex e08003673..e01fa8491 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -79,6 +79,11 @@ pub(crate) fn has_selection(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;if s.state.selection.is_empty() { Err("no clips selected".into()) } else { Ok(()) }}+/// Clips or captions selected (Copy / Cut work on either).+fn has_clips_or_captions(s: &Session) -> std::result::Result<(), String> {+ has_seq(s)?;+ if s.state.selection.is_empty() && s.state.caption_selection.is_empty() { Err("no clips or captions selected".into()) } else { Ok(()) }+}/// Clips or captions selected (Clear / Ripple Delete work on either).fn has_any_selection(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;@@ -120,7 +125,7 @@ pub(crate) fn has_project_selection(s: &Session) -> std::result::Result<(), Stri}fn has_clipboard(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;- if s.state.clipboard.is_empty() { Err("clipboard is empty".into()) } else { Ok(()) }+ if s.state.clipboard.is_empty() && s.state.caption_clipboard.is_empty() { Err("clipboard is empty".into()) } else { Ok(()) }}/// The ids a caller named under `many` (a list) or `one` (a single id), when the command documents@@ -1624,7 +1629,13 @@ fn build() -> Vec<CommandSpec> {// ================= Edit =================cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!({"undone": s.undo()}))),cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!({"redone": s.redo()}))),- cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{}", has_selection, |s, _| {+ cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{}", has_clips_or_captions, |s, _| {+ if s.state.selection.is_empty() {+ crate::captions::copy(s);+ let caps = s.state.caption_selection.clone();+ crate::captions::delete(s, &caps, false)?;+ return Ok(Value::Null);+ }copy_selection(s);let sel = with_links(s, &s.state.selection.clone());s.edit_sequence("Cut", |q, _, st| {@@ -1634,7 +1645,10 @@ fn build() -> Vec<CommandSpec> {})?;Ok(Value::Null)}),- cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{}", has_selection, |s, _| {+ cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{}", has_clips_or_captions, |s, _| {+ if s.state.selection.is_empty() {+ return Ok(json!({"copied": crate::captions::copy(s)}));+ }copy_selection(s);Ok(json!({"copied": s.state.clipboard.len()}))}),@@ -3670,9 +3684,13 @@ fn copy_selection(s: &mut Session) {}s.state.clipboard = clip;s.state.clipboard_markers = markers;+ s.state.caption_clipboard.clear();}fn paste(s: &mut Session, insert: bool) -> Result<Value> {+ if !s.state.caption_clipboard.is_empty() {+ return crate::captions::paste(s, insert);+ }let at = s.playhead();let clip = s.state.clipboard.clone();let markers = if s.state.copy_paste_sequence_markers { s.state.clipboard_markers.clone() } else { Vec::new() };diff --git a/crates/engine/src/explicit_targets_tests.rs b/crates/engine/src/explicit_targets_tests.rsindex 2abbcee12..cf1384595 100644--- a/crates/engine/src/explicit_targets_tests.rs+++ b/crates/engine/src/explicit_targets_tests.rs@@ -130,7 +130,7 @@ fn naming_nothing_usable_does_not_enable_a_command() {assert!(why.starts_with("-1 is not a clip id"), "{why}");assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({"clips": [v1(&s)[0].id.0], "item": 987_654_321u64}))), "select a clip in the Project panel");// `edit.cut` takes no `clips`: it works on the selection only- assert_eq!(disabled(s.execute("edit.cut", json!({"clips": [v1(&s)[0].id.0]}))), "no clips selected");+ assert_eq!(disabled(s.execute("edit.cut", json!({"clips": [v1(&s)[0].id.0]}))), "no clips or captions selected");assert!(std::sync::Arc::ptr_eq(&before, &s.project), "nothing was edited");}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 47a9cfd6e..dd2680bb4 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -381,6 +381,11 @@ pub struct EditorState {/// Sequence markers copied with the clipboard clips (start relative to the copied range).#[serde(skip)]pub clipboard_markers: Vec<filmcraft_project::Marker>,+ /// Captions copied from the Timeline, with their caption track's index (starts relative to the+ /// copied range). Copying clips empties it and copying captions empties `clipboard`, so Paste+ /// places whichever was copied last.+ #[serde(skip)]+ pub caption_clipboard: Vec<(usize, filmcraft_project::Caption)>,/// The last Edit ▸ Find… (Find Next continues it).#[serde(default)]pub find: Option<project_tools::FindState>,diff --git a/crates/ui-egui/tests/it/caption_copy_paste_ui.rs b/crates/ui-egui/tests/it/caption_copy_paste_ui.rsnew file mode 100644index 000000000..c3852b7c7--- /dev/null+++ b/crates/ui-egui/tests/it/caption_copy_paste_ui.rs@@ -0,0 +1,85 @@+//! Cmd+C / Cmd+V with a caption selected in the Timeline pastes a copy at the playhead, as with+//! clips. The real `FilmcraftApp` under `egui_kittest` with the demo project.++use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use serde_json::{Value, json};++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+}++impl Driver {+ /// The demo project with snapping off, so drags land where the pointer goes; frames 1/60 s+ /// apart, as on a display.+ fn demo() -> Self {+ let mut session = Session::default();+ session.execute("file.openDemoProject", json!({})).expect("demo project");+ session.execute("sequence.snap", json!({"on": false})).expect("snapping off");+ let (tx, rx) = channel();+ let app = FilmcraftApp::new(session).with_control(rx);+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000).build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx };+ d.frames(4);+ d.ok("ui.elements", json!({"prefix": "timeline.clip."}));+ d+ }++ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }++ fn ok(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).expect("control channel");+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");+ return v["result"].clone();+ }+ }+ panic!("no reply to {method} {params}");+ }++ fn exec(&mut self, command: &str, params: Value) -> Value {+ self.ok("engine.execute", json!({"command": command, "params": params}))+ }++ /// (start, end, text) of every caption on C1.+ fn captions(&mut self) -> Vec<(i64, i64, String)> {+ let r = self.exec("captions.list", json!({}));+ r["tracks"][0]["captions"]+ .as_array()+ .expect("captions")+ .iter()+ .map(|c| (c["start"].as_i64().expect("start"), c["end"].as_i64().expect("end"), c["text"].as_str().expect("text").to_string()))+ .collect()+ }+}++/// Cmd+C / Cmd+V with a caption selected in the Timeline pastes a copy at the playhead.+#[test]+fn copy_paste_duplicates_a_caption() {+ let mut d = Driver::demo();+ let id = d.exec("captions.add", json!({"seconds": 1.0, "durationSeconds": 1.0, "text": "again"}))["caption"].as_u64().expect("id");+ d.ok("ui.click", json!({"id": format!("timeline.caption.{id}")}));+ d.ok("ui.key", json!({"key": "Cmd+C"}));+ d.exec("playhead.set", json!({"seconds": 5.0}));+ d.ok("ui.key", json!({"key": "Cmd+V"}));+ let caps = d.captions();+ assert_eq!(caps.len(), 2, "pasted: {caps:?}");+ assert_eq!(caps[1].2, "again");+ assert!(caps[1].0 > caps[0].1);+}diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rsindex 3408b21da..88587dde3 100644--- a/crates/ui-egui/tests/it/main.rs+++ b/crates/ui-egui/tests/it/main.rs@@ -1,5 +1,6 @@mod audio51_ui;mod audio_fx_editor_ui;+mod caption_copy_paste_ui;mod caption_option_drag_ui;mod caption_properties_ui;mod caption_razor_ui;diff --git a/docs/captions.md b/docs/captions.mdindex 6e79d56b0..b1000588e 100644--- a/docs/captions.md+++ b/docs/captions.md@@ -48,6 +48,7 @@ Details of each format and the SCC encoder are in [`crates/captions/README.md`](| `captions.move` | drag a caption in the timeline | `captions`, `delta` or `deltaFrames` || `captions.duplicate` | ⌥-drag a caption in the timeline | `captions`, `delta` or `deltaFrames` — copies on the same tracks, overwriting what is there || `captions.delete` | Edit ▸ Clear / Ripple Delete with captions selected | `captions`, `ripple` |+| `edit.copy` / `edit.cut` / `edit.paste` / `edit.pasteInsert` | ⌘C / ⌘X / ⌘V / ⇧⌘V with only captions selected | captions paste at the playhead on the tracks they came from, overwriting (Paste Insert pushes later captions on); Paste places whichever of clips or captions was copied last || `captions.select`, `captions.goTo` | click / number button | `captions`, `add` / `caption` || `captions.setTrack` | caption track header (eye, lock) | `track`, `name`, `format`, `language`, `enabled`, `locked`, `syncLock` || `captions.setStyle` | Text panel style strip | `track`, `size`, `color`, `background`, `backgroundColor`, `outline`, `outlineColor`, `align`, `anchor`, `margin`, `lineSpacing`, `reset` |