Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Timeline: Option-drag copies clips instead of moving them

impostazionia8b3d7f70391
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
index e12c56526..d79efe38f 100644
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@ -506,6 +506,60 @@ pub fn move_items(seq: &mut Sequence, moves: &[(ClipId, TrackId, Tick)], insert_
Ok(())
}
+/// Copy items to (track, time) with overwrite or insert semantics, leaving the originals where
+/// they are (Option-drag). `moves`: (item, destination track, start of the copy). The copies get
+/// new ids; copies of linked clips are linked to each other, not to the originals, and the
+/// transitions that would travel with a move are copied with them. Returns the copies' ids in
+/// the order of `moves`.
+pub fn copy_items(seq: &mut Sequence, moves: &[(ClipId, TrackId, Tick)], insert_mode: bool, ctx: &mut EditCtx) -> Result<Vec<ClipId>> {
+ let mut work = seq.clone();
+ let mut placed = Vec::new();
+ for (c, dest, start) in moves {
+ let (_, it) = work.find_item(*c).ok_or(EditError::NoItem(*c))?;
+ let mut it = it.clone();
+ if work.track(*dest).ok_or(EditError::NoTrack(*dest))?.locked {
+ return Err(EditError::Locked);
+ }
+ it.start = (*start).max(Tick::ZERO);
+ placed.push((*dest, it));
+ }
+ // worked out on the original ids, then moved over to the copies
+ let carried = carried_transitions(&work, &placed);
+ let mut ids = HashMap::new();
+ let mut links = HashMap::new();
+ for (_, it) in &mut placed {
+ let id = ClipId(ctx.alloc());
+ ids.insert(it.id, id);
+ it.id = id;
+ if let Some(l) = it.link {
+ it.link = Some(*links.entry(l).or_insert_with(|| ctx.alloc()));
+ }
+ }
+ // a copy whose linked partner is not copied is not linked
+ let mut counts: HashMap<u64, usize> = HashMap::new();
+ for l in placed.iter().filter_map(|(_, it)| it.link) {
+ *counts.entry(l).or_default() += 1;
+ }
+ for (_, it) in &mut placed {
+ if it.link.is_some_and(|l| counts.get(&l).copied().unwrap_or(0) < 2) {
+ it.link = None;
+ }
+ }
+ let out = if insert_mode { insert(&mut work, placed, ctx)? } else { overwrite(&mut work, placed, ctx)? };
+ for (dest, mut tr) in carried {
+ tr.id = TransitionId(ctx.alloc());
+ tr.from = tr.from.and_then(|c| ids.get(&c).copied());
+ tr.to = tr.to.and_then(|c| ids.get(&c).copied());
+ let t = track_mut(&mut work, dest)?;
+ if [tr.from, tr.to].into_iter().flatten().all(|c| t.item(c).is_some()) && (tr.from.is_some() || tr.to.is_some()) {
+ t.transitions.push(tr);
+ t.sort();
+ }
+ }
+ *seq = work;
+ Ok(out)
+}
+
/// The transitions that travel with a move (#227, #374): those whose clips all move, onto one
/// track and by one offset (a fade at a moved clip's edge, or the cut between two clips that move
/// together), shifted to where those clips land.
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 6f2eb007b..ab00abc27 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -302,7 +302,9 @@ pub(crate) fn item_p(p: &Value, k: &str) -> Option<ItemId> {
/// every clip of the call lands later by the same amount, so the spacing asked for is kept.
/// `overwritten` lists every clip the move covered without being asked to move it: its length
/// before and after (ticks) and the clips what is left of it now lives on as (none = removed; a
-/// clip a moved clip lands inside is split in two).
+/// clip a moved clip lands inside is split in two). With `copy: true` (Option-drag) the clips stay
+/// where they are and copies land at the destinations instead; the copies are selected and listed
+/// as `copied`.
fn move_clips(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "timeline.move";
let mut listed: Vec<(ClipId, TrackId, Tick)> = Vec::new();
@@ -345,19 +347,31 @@ fn move_clips(s: &mut Session, p: &Value) -> Result<Value> {
moves.push((clip, track, start));
}
let ins = bool_p(p, "insert").unwrap_or(false);
+ let copy = bool_p(p, "copy").unwrap_or(false);
// every clip on the sequence now: id -> (track, start, end, project item)
let spots = |s: &Session| -> Vec<(u64, TrackId, Tick, Tick, ItemId)> {
let q = s.active_sequence();
q.into_iter().flat_map(|q| q.all_tracks()).flat_map(|t| t.items.iter().map(move |i| (i.id.0, t.id, i.start, i.end(), i.item))).collect()
};
let before = spots(s);
- s.edit_sequence(if ins { "Move (Insert)" } else { "Move" }, |q, ctx, _| Ok(edit::move_items(q, &moves, ins, ctx)?))?;
+ let copied = if copy {
+ let label = if ins { "Copy (Insert)" } else { "Copy" };
+ s.edit_sequence(label, |q, ctx, st| {
+ let ids = edit::copy_items(q, &moves, ins, ctx)?;
+ st.selection = ids.clone();
+ st.transition_selection.clear();
+ Ok(ids)
+ })?
+ } else {
+ s.edit_sequence(if ins { "Move (Insert)" } else { "Move" }, |q, ctx, _| Ok(edit::move_items(q, &moves, ins, ctx)?))?;
+ Vec::new()
+ };
// An overwrite shortens, splits or removes whatever already sits where a clip lands, and a
// shortened clip may live on under a new id: name each clip the move changed without being
// asked to, with what is left of it, so the caller hears about it instead of finding out later.
let after = spots(s);
- let moved = |c: u64| moves.iter().any(|m| m.0.0 == c);
- let new = |c: u64| !before.iter().any(|b| b.0 == c);
+ let moved = |c: u64| moves.iter().any(|m| m.0.0 == c) && !copy;
+ let new = |c: u64| !before.iter().any(|b| b.0 == c) && !copied.iter().any(|k| k.0 == c);
let mut overwritten = Vec::new();
for &(c, track, start, end, item) in before.iter().filter(|b| !moved(b.0)) {
let kept = after.iter().find(|a| a.0 == c);
@@ -369,6 +383,9 @@ fn move_clips(s: &mut Session, p: &Value) -> Result<Value> {
let now: i64 = pieces.iter().map(|a| (a.3 - a.2).0).sum();
overwritten.push(json!({"clip": c, "was": (end - start).0, "now": now, "pieces": pieces.iter().map(|a| a.0).collect::<Vec<_>>()}));
}
+ if copy {
+ return Ok(json!({"copied": copied.iter().map(|c| c.0).collect::<Vec<_>>(), "overwritten": overwritten}));
+ }
Ok(json!({"moved": moves.iter().map(|m| m.0.0).collect::<Vec<_>>(), "overwritten": overwritten}))
}
@@ -2251,7 +2268,7 @@ fn build() -> Vec<CommandSpec> {
"Move Clips",
[],
None,
- r#"{"moves":[{"clip":id,"track":id|"V2","time":ticks}],"insert":bool,"linked":bool?}"#,
+ r#"{"moves":[{"clip":id,"track":id|"V2","time":ticks}],"insert":bool,"linked":bool?,"copy":bool?}"#,
has_seq,
move_clips
),
diff --git a/crates/engine/src/timeline_move_tests.rs b/crates/engine/src/timeline_move_tests.rs
index e80c2f972..6f176b814 100644
--- a/crates/engine/src/timeline_move_tests.rs
+++ b/crates/engine/src/timeline_move_tests.rs
@@ -247,3 +247,38 @@ fn a_move_that_lands_on_another_clip_reports_what_it_cut() {
let r = s.execute("timeline.move", json!({"moves": [{"clip": a1.id.0, "track": a_track.0, "time": a2.start.0}], "insert": true, "linked": false})).unwrap();
assert_eq!(r["overwritten"], json!([]));
}
+
+/// Option-drag (`copy: true`) moved the clips instead of copying them.
+#[test]
+fn copy_leaves_the_originals_and_links_the_copies() {
+ let mut s = demo();
+ let (v_track, v, a_track, a) = pair_in_an_empty_sequence(&mut s, 0.0);
+ let to = v.end() + s.sequence_rate().tick_of(24);
+ let before = s.project.clone();
+ // the picture is listed; its linked sound is copied with it
+ let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V2", "time": to.0}], "copy": true})).unwrap();
+ let copies: Vec<ClipId> = r["copied"].as_array().unwrap().iter().map(|c| ClipId(c.as_u64().unwrap())).collect();
+ assert_eq!(copies.len(), 2, "picture and sound are copied: {r}");
+ assert_eq!((state(&s, v.id), state(&s, a.id)), ((v_track, v.start), (a_track, a.start)), "the originals stay");
+ let q = s.active_sequence().unwrap();
+ let (vt, vc) = q.find_item(copies[0]).unwrap();
+ let (at, ac) = q.find_item(copies[1]).unwrap();
+ assert_eq!((vt, vc.start, vc.item, vc.source_in, vc.duration), (q.video_tracks[1].id, to, v.item, v.source_in, v.duration));
+ assert_eq!((at, ac.start), (a_track, to), "the sound copy keeps its offset on its own track");
+ assert!(vc.link.is_some() && vc.link == ac.link && vc.link != v.link, "the copies are linked to each other only");
+ assert_eq!(s.state.selection, copies, "the copies are selected");
+ q.check().unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, *before, "one undo step");
+ // copying just one side (linked: false) leaves the copy unlinked
+ let r = s.execute("timeline.move", json!({"moves": [{"clip": a.id.0, "track": a_track.0, "time": to.0}], "copy": true, "linked": false})).unwrap();
+ let c = ClipId(r["copied"][0].as_u64().unwrap());
+ assert_eq!(r["copied"].as_array().unwrap().len(), 1);
+ assert!(s.active_sequence().unwrap().find_item(c).unwrap().1.link.is_none());
+ // a copy onto a locked track is refused and changes nothing
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("timeline.setTrack", json!({"track": "V2", "locked": true})).unwrap();
+ let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V2", "time": to.0}], "copy": true, "linked": false}));
+ assert!(r.is_err());
+ assert_eq!(s.active_sequence().unwrap().all_tracks().map(|t| t.items.len()).sum::<usize>(), 2);
+}
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 28b75008a..55c8b9c13 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -89,6 +89,9 @@ pub enum Drag {
start_track: TrackId,
offset: Tick,
track_delta: i32,
+ /// Option is held: the drop copies the clips instead of moving them (as of the last
+ /// drag frame, so letting go of both at once still copies).
+ copy: bool,
},
Trim {
clip: ClipId,
@@ -398,6 +401,12 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
// item, so the waveform and thumbnail stay where the media is instead of squeezing (#374)
let mut edited: HashMap<ClipId, TrackItem> = HashMap::new();
preview_drag(app, &seq, &mut previews, &mut edited);
+ // Option-drag copies: the clips stay where they are and their copies follow the pointer
+ let copying = matches!(app.tl.drag, Some(Drag::Move { copy: true, .. }));
+ let copies: Vec<(ClipId, (Tick, Tick, Option<TrackId>))> = if copying { previews.drain().collect() } else { Vec::new() };
+ if copying {
+ ctx.set_cursor_icon(CursorIcon::Copy);
+ }
for r in &rows {
let Some(tr) = seq.track(r.track) else { continue };
let clip_rect = if r.kind == TrackKind::Video { vclip } else { aclip };
@@ -449,6 +458,15 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
+ for (cid, (start, dur, mt)) in &copies {
+ if let Some((home, it)) = seq.find_item(*cid)
+ && mt.unwrap_or(home) == r.track
+ {
+ let body = Rect::from_min_max(pos2(layout.x_of(*start), r.rect.min.y + 1.0), pos2(layout.x_of(*start + *dur), r.rect.max.y - 1.0));
+ draw_clip(app, &ctx, &p, body, it, r.kind, true, &t, rate);
+ app.auto.add(&format!("timeline.clip.{}.copy", cid.0), body.intersect(content), &it.name);
+ }
+ }
// Show Through Edits: a small bow-tie on cuts between continuous pieces of one clip
if app.session.state.show_through_edits {
for te in filmcraft_edit::through::track_through_edits(tr) {
@@ -2080,7 +2098,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
}
if resp.drag_started() {
let clips = app.session.state.selection.clone();
- Some(Drag::Move { clips, grab_tick: t, start_track: track, offset: Tick::ZERO, track_delta: 0 })
+ Some(Drag::Move { clips, grab_tick: t, start_track: track, offset: Tick::ZERO, track_delta: 0, copy: mods.alt })
} else {
None
}
@@ -2173,7 +2191,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
(Some(c), Some(s)) if c.kind == s.kind => c.index as i32 - s.index as i32,
_ => 0,
};
- Some(Drag::Move { clips, grab_tick, start_track, offset, track_delta })
+ Some(Drag::Move { clips, grab_tick, start_track, offset, track_delta, copy: mods.alt })
}
Drag::Trim { clip, edge, mode, from, .. } => seq.find_item(clip).map(|(_, it)| {
let base = if edge == filmcraft_edit::Edge::In { it.start } else { it.end() };
@@ -2240,12 +2258,13 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
&& let Some(d) = app.tl.drag.take()
{
let r = match d {
- Drag::Move { clips, offset, track_delta, .. } if offset != Tick::ZERO || track_delta != 0 => {
+ Drag::Move { clips, offset, track_delta, copy, .. } if offset != Tick::ZERO || track_delta != 0 => {
let moves: Vec<Value> = clips
.iter()
.filter_map(|c| seq.find_item(*c).map(|(tid, it)| json!({"clip": c.0, "track": shift_track(seq, tid, track_delta).unwrap_or(tid).0, "time": (it.start + offset).max(Tick::ZERO).0})))
.collect();
- Some(app.session.execute("timeline.move", json!({"moves": moves, "insert": mods.command, "linked": false})))
+ // Option held while dropping copies (Premiere: Option-drag duplicates)
+ Some(app.session.execute("timeline.move", json!({"moves": moves, "insert": mods.command, "linked": false, "copy": copy || mods.alt})))
}
Drag::Trim { clip, edge, mode, delta, .. } if delta != Tick::ZERO => Some(app.session.execute(
"timeline.trim",
diff --git a/crates/ui-egui/tests/timeline_option_drag_ui.rs b/crates/ui-egui/tests/timeline_option_drag_ui.rs
new file mode 100644
index 000000000..01840f43d
--- /dev/null
+++ b/crates/ui-egui/tests/timeline_option_drag_ui.rs
@@ -0,0 +1,92 @@
+//! Option-drag of a timeline clip copies it (Premiere): the original stays, a copy lands where
+//! the pointer lets go and is selected; a plain drag still moves.
+
+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 {
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ 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_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx };
+ d.frames(4);
+ 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).unwrap();
+ 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}))
+ }
+ fn rect(&mut self, id: &str) -> [f64; 4] {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("no element {id}")).clone();
+ let r: Vec<f64> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ [r[0], r[1], r[2], r[3]]
+ }
+}
+
+fn clip_count(d: &mut Driver) -> usize {
+ d.harness.state().session.active_sequence().map(|q| q.all_tracks().map(|t| t.items.len()).sum()).unwrap_or(0)
+}
+
+#[test]
+fn option_drag_copies_a_clip_and_a_plain_drag_moves_it() {
+ let mut d = Driver::demo();
+ // the clip on V2 (no linked sound), and empty space to its right
+ let q = d.harness.state().session.active_sequence().unwrap().clone();
+ let v2 = q.video_tracks[1].items[0].clone();
+ let n = clip_count(&mut d);
+ let r = d.rect(&format!("timeline.clip.{}", v2.id.0));
+ let (x, y) = (r[0] + 10.0, r[1] + r[3] / 2.0);
+ d.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + 240.0, "y": y}, "steps": 12, "modifiers": {"alt": true}}));
+ d.frames(3);
+ let q2 = d.harness.state().session.active_sequence().unwrap().clone();
+ assert_eq!(clip_count(&mut d), n + 1, "one copy was added");
+ assert_eq!(q2.find_item(v2.id).map(|(_, i)| i.start), Some(v2.start), "the original stays");
+ let sel = d.harness.state().session.state.selection.clone();
+ assert_eq!(sel.len(), 1);
+ let (track, copy) = q2.find_item(sel[0]).unwrap();
+ assert_ne!(copy.id, v2.id);
+ assert_eq!((track, copy.item, copy.duration), (q.video_tracks[1].id, v2.item, v2.duration));
+ assert!(copy.start > v2.start, "the copy is where the pointer let go");
+ // one undo removes the copy
+ d.exec("edit.undo", json!({}));
+ assert_eq!(clip_count(&mut d), n);
+ // without Option the same drag moves the clip
+ d.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + 240.0, "y": y}, "steps": 12}));
+ d.frames(3);
+ assert_eq!(clip_count(&mut d), n);
+ assert!(d.harness.state().session.active_sequence().unwrap().find_item(v2.id).unwrap().1.start > v2.start, "moved");
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 28b86c30a..fc8f62a87 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -102,7 +102,10 @@ is, and so does one whose position would not change (the listed clip only change
lists every clip that moved, partners included. No clip is moved before the sequence
start: if one would be, all clips of the call land later by the same amount (their spacing is
kept). A `time` beyond the representable range is an "invalid parameters" error. The timeline
-panel's drag passes `linked: false`, because it already lists exactly the clips it moves.
+panel's drag passes `linked: false`, because it already lists exactly the clips it moves. With
+`copy: true` (Option-drag in the timeline) the clips stay where they are and copies land at the
+destinations instead (linked partners are copied too, unless `linked: false`); the result lists
+the new clips as `copied`, they are selected, and copies of linked clips are linked to each other.
**Trim mode** (`crates/engine/src/trim.rs`): `trim.selectEditPoint` / `trim.selectNearest` enter trim
mode (the Program monitor becomes the Trim Monitor, ids `trimMonitor.*`); `trim.monitor` returns what