Skip to content

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

engine: keep linked edit points together in Trim Mode (#3085) (#3224)

Michael Butler817b515ef646
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 1089046fc..e22b88059 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -2886,7 +2886,7 @@ fn build() -> Vec<CommandSpec> {
.map(Tick)
.or_else(|| p.get("deltaFrames").and_then(Value::as_i64).map(|f| s.sequence_rate().tick_of(f)))
.unwrap_or_default();
- // `followLinks: false` rolls only this pair: Trim mode already lists linked partners as edit points of their own
+ // `followLinks: false` rolls only this pair; the default clamps linked cuts together.
let follow = s.state.linked_selection && p.get("followLinks").and_then(Value::as_bool).unwrap_or(true);
let (x, n, linked) = s.edit_sequence("Rolling Edit", |q, ctx, _| {
let pairs = linked_roll_pairs(q, l, r, follow);
diff --git a/crates/engine/src/trim.rs b/crates/engine/src/trim.rs
index f9bb63ec3..86ef185f6 100644
--- a/crates/engine/src/trim.rs
+++ b/crates/engine/src/trim.rs
@@ -3,7 +3,10 @@
//! An edit point is one edge of a clip plus a trim kind. Trim and Ripple act on that edge; Roll acts
//! on the edge shared with the adjacent clip on the same track. Trimming delegates to the
//! `timeline.trim` / `timeline.roll` commands so linked partners and sync locks behave the same as
-//! with the mouse.
+//! with the mouse. Linked Selection adds unlocked partner edges to both explicit and nearest-edge
+//! selections. Shift-click toggles the linked group. A roll follows only linked cuts at the same
+//! time, preserving split edits; regular/ripple trims follow the corresponding In or Out edges.
+//! Each linked group is clamped and applied once, including when both partners were selected.
//!
//! **Trim Monitor** ([`monitor_info`]): while edit points are selected the Program monitor shows the
//! outgoing clip's last frame and the incoming clip's first frame, with the Out/In shift counters
@@ -87,6 +90,29 @@ fn kind_p(p: &Value) -> Option<TrimKind> {
serde_json::from_value(p.get("kind")?.clone()).ok()
}
+/// The edges that the timeline command will edit together. Rolls follow only matching linked
+/// cuts; regular/ripple trims follow the same edge of linked clips, including split edits.
+fn linked_points(s: &Session, ep: EditPoint) -> Vec<EditPoint> {
+ let Some(seq) = s.active_sequence() else { return vec![ep] };
+ let clips = if ep.kind == TrimKind::Roll {
+ let Some((left, right)) = roll_pair(seq, &ep) else { return vec![ep] };
+ crate::commands::linked_roll_pairs(seq, left, right, s.state.linked_selection).into_iter().map(|(l, r)| if ep.out { l } else { r }).collect()
+ } else {
+ crate::commands::with_links(s, &[ep.clip])
+ };
+ clips
+ .into_iter()
+ .filter(|c| *c == ep.clip || seq.find_item(*c).is_some_and(|(t, _)| seq.track(t).is_some_and(|tr| !tr.locked)))
+ .map(|clip| EditPoint { clip, ..ep })
+ .collect()
+}
+
+/// Either side of a rolling cut denotes the same edit, even when selected separately.
+fn same_edge(seq: &Sequence, a: &EditPoint, b: &EditPoint) -> bool {
+ (a.clip == b.clip && a.out == b.out)
+ || (a.kind == TrimKind::Roll && b.kind == TrimKind::Roll && roll_pair(seq, a).is_some_and(|p| Some(p) == roll_pair(seq, b)))
+}
+
/// `trim.selectEditPoint {clip, edge: "in"|"out", kind, add?}`
pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
let clip = p.get("clip").and_then(Value::as_u64).map(ClipId).ok_or_else(|| EngineError::Other("need `clip`".into()))?;
@@ -94,14 +120,17 @@ pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
let kind = kind_p(p).unwrap_or(TrimKind::Trim);
s.active_sequence().and_then(|q| q.find_item(clip)).ok_or_else(|| EngineError::Other(format!("no clip {}", clip.0)))?;
let ep = EditPoint { clip, out, kind };
+ let points = linked_points(s, ep);
if p.get("add").and_then(Value::as_bool).unwrap_or(false) {
- if let Some(i) = s.state.edit_points.iter().position(|e| e.clip == clip && e.out == out) {
- s.state.edit_points.remove(i);
- } else {
- s.state.edit_points.push(ep);
+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
+ let remove = s.state.edit_points.iter().any(|e| same_edge(seq, e, &ep));
+ let mut selected: Vec<_> = s.state.edit_points.iter().copied().filter(|e| !points.iter().any(|p| same_edge(seq, e, p))).collect();
+ if !remove {
+ selected.extend(points);
}
+ s.state.edit_points = selected;
} else {
- s.state.edit_points = vec![ep];
+ s.state.edit_points = points;
}
s.state.selection.clear();
s.state.gap_selection = None;
@@ -125,7 +154,7 @@ pub fn select_nearest(s: &mut Session, p: &Value) -> Result<Value> {
let targeted = s.state.active_sequence.and_then(|id| s.state.targeting.get(&id)).map(|t| t.targeted.clone()).unwrap_or_default();
let mut points = Vec::new();
for tr in seq.video_tracks.iter().chain(seq.audio_tracks.iter()) {
- if !targeted.is_empty() && !targeted.contains(&tr.id) {
+ if tr.locked || (!targeted.is_empty() && !targeted.contains(&tr.id)) {
continue;
}
// nearest edge on this track
@@ -147,11 +176,11 @@ pub fn select_nearest(s: &mut Session, p: &Value) -> Result<Value> {
}
}
if let Some((_, ep)) = best {
- // one roll point per edge: skip the partner's mirror of an edge already chosen
- if kind == TrimKind::Roll && points.iter().any(|e: &EditPoint| roll_pair(seq, e) == roll_pair(seq, &ep)) {
- continue;
+ for point in linked_points(s, ep) {
+ if !points.iter().any(|e| same_edge(seq, e, &point)) {
+ points.push(point);
+ }
}
- points.push(ep);
}
}
s.state.edit_points = points;
@@ -204,19 +233,27 @@ fn trim_all_raw(s: &mut Session, delta_for: &dyn Fn(&Sequence, &EditPoint) -> Op
}
let pts = s.state.edit_points.clone();
let mut applied = Vec::new();
+ let mut edited = Vec::new();
for ep in &pts {
let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
+ if edited.iter().any(|e| same_edge(seq, e, ep)) {
+ continue;
+ }
let Some(delta) = delta_for(seq, ep) else { continue };
+ // Each timeline command clamps and edits its linked group together. Do not dispatch it
+ // again for the group's other selected edges (which would also ripple later clips twice).
+ let group = linked_points(s, *ep);
let r = match ep.kind {
TrimKind::Roll => {
let Some((l, r)) = roll_pair(seq, ep) else { continue };
- s.execute("timeline.roll", json!({"left": l.0, "right": r.0, "delta": delta.0, "followLinks": false}))?
+ s.execute("timeline.roll", json!({"left": l.0, "right": r.0, "delta": delta.0}))?
}
k => s.execute(
"timeline.trim",
json!({"clip": ep.clip.0, "edge": if ep.out { "out" } else { "in" }, "mode": if k == TrimKind::Ripple { "ripple" } else { "regular" }, "delta": delta.0}),
)?,
};
+ edited.extend(group);
applied.push(r.get("delta").cloned().unwrap_or(Value::Null));
}
Ok(applied)
diff --git a/crates/engine/src/trim_tests.rs b/crates/engine/src/trim_tests.rs
index cb3d32ccd..1ae2dc005 100644
--- a/crates/engine/src/trim_tests.rs
+++ b/crates/engine/src/trim_tests.rs
@@ -3,6 +3,185 @@
use super::*;
use serde_json::json;
+/// Two adjacent linked A/V clips with handles on both sides of their cut.
+fn linked_cut() -> (Session, [(ClipId, ClipId); 2]) {
+ let mut s = demo();
+ s.execute("file.newSequence", json!({"name": "Linked trim", "video": 1, "audio": 1})).unwrap();
+ let rate = s.sequence_rate();
+ let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).unwrap().id;
+ for n in 0..2 {
+ s.execute("timeline.place", json!({"item": item.0, "frame": 48 * n, "sourceIn": rate.tick_of(48).0, "duration": rate.tick_of(48).0})).unwrap();
+ }
+ let q = s.active_sequence().unwrap();
+ let clips = [0, 1].map(|n| (q.video_tracks[0].items[n].id, q.audio_tracks[0].items[n].id));
+ (s, clips)
+}
+
+/// #3085: selecting either side of a picture cut also selects its linked sound edge.
+#[test]
+fn linked_edit_point_selection_and_shift_toggle() {
+ for kind in ["trim", "ripple", "roll"] {
+ for edge in ["in", "out"] {
+ let (mut s, clips) = linked_cut();
+ let (video, audio) = clips[usize::from(edge == "in")];
+ let p = json!({"clip": video.0, "edge": edge, "kind": kind});
+ s.execute("trim.selectEditPoint", p.clone()).unwrap();
+ assert_eq!(s.state.edit_points.iter().map(|e| e.clip).collect::<Vec<_>>(), vec![video, audio], "{kind} {edge}");
+ s.execute("trim.selectEditPoint", json!({"clip": audio.0, "edge": edge, "kind": kind, "add": true})).unwrap();
+ assert!(s.state.edit_points.is_empty(), "Shift-click removes the linked group");
+ s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
+ s.execute("trim.selectEditPoint", p).unwrap();
+ assert_eq!(s.state.edit_points.len(), 1);
+ }
+ }
+}
+
+/// #3085: Trim Monitor rolls picture and sound once, with one undo/redo step.
+#[test]
+fn trim_mode_roll_moves_linked_audio_once() {
+ for edge in ["in", "out"] {
+ let (mut s, clips) = linked_cut();
+ let selected = clips[usize::from(edge == "in")].0;
+ s.execute("trim.selectEditPoint", json!({"clip": selected.0, "edge": edge, "kind": "roll"})).unwrap();
+ let before = s.project.clone();
+ let undo = s.history.undo.len();
+ s.execute("trim.nudge", json!({"frames": 3})).unwrap();
+ let q = s.active_sequence().unwrap();
+ for clip in [clips[0].0, clips[0].1] {
+ assert_eq!(q.find_item(clip).unwrap().1.end(), s.sequence_rate().tick_of(51));
+ }
+ for clip in [clips[1].0, clips[1].1] {
+ assert_eq!(q.find_item(clip).unwrap().1.start, s.sequence_rate().tick_of(51));
+ }
+ assert_eq!(s.history.undo.len(), undo + 1);
+ let after = s.project.clone();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, *before);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(*s.project, *after);
+ }
+}
+
+/// Explicitly selected partners must not run the same linked trim twice, including ripple shifts.
+#[test]
+fn selected_linked_regular_and_ripple_edges_move_once() {
+ for kind in ["trim", "ripple"] {
+ for out in [false, true] {
+ let (mut s, clips) = linked_cut();
+ let pair = clips[usize::from(!out)];
+ s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
+ for (n, clip) in [pair.0, pair.1].into_iter().enumerate() {
+ s.execute("trim.selectEditPoint", json!({"clip": clip.0, "edge": if out { "out" } else { "in" }, "kind": kind, "add": n != 0})).unwrap();
+ }
+ s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
+ let before = s.project.clone();
+ s.execute("trim.nudge", json!({"frames": if out { -3 } else { 3 }})).unwrap();
+ let q = s.active_sequence().unwrap();
+ let f = |n| s.sequence_rate().tick_of(n);
+ for clip in [pair.0, pair.1] {
+ let it = q.find_item(clip).unwrap().1;
+ let expected = if out {
+ (0, 45)
+ } else if kind == "ripple" {
+ (48, 93)
+ } else {
+ (51, 96)
+ };
+ assert_eq!((it.start, it.end()), (f(expected.0), f(expected.1)), "{kind} out={out}");
+ }
+ if out {
+ for clip in [clips[1].0, clips[1].1] {
+ assert_eq!(q.find_item(clip).unwrap().1.start, f(if kind == "ripple" { 45 } else { 48 }), "{kind}");
+ }
+ }
+ let after = s.project.clone();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, *before);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(*s.project, *after);
+ }
+ }
+}
+
+/// Nearest-edge selection follows links even when only the video track is targeted, without
+/// duplicating the sound when it is targeted too. Dynamic trimming uses the same grouped edit.
+#[test]
+fn nearest_linked_roll_and_dynamic_trim() {
+ let (mut s, clips) = linked_cut();
+ let rate = s.sequence_rate();
+ s.execute("timeline.setTargeting", json!({"track": "A1", "targeted": false})).unwrap();
+ s.execute("playhead.set", json!({"frame": 48})).unwrap();
+ s.execute("trim.selectNearest", json!({"kind": "roll"})).unwrap();
+ assert_eq!(s.state.edit_points.len(), 2);
+ assert!(s.state.edit_points.iter().any(|e| e.clip == clips[0].1));
+ s.execute("timeline.setTargeting", json!({"track": "A1", "targeted": true})).unwrap();
+ s.execute("trim.selectNearest", json!({"kind": "roll"})).unwrap();
+ assert_eq!(s.state.edit_points.len(), 2);
+ let before = s.project.clone();
+ s.execute("trim.shuttle", json!({"direction": "forward", "clock": 0.0})).unwrap();
+ s.execute("trim.shuttleStop", json!({"clock": 0.25})).unwrap();
+ let expected = rate.tick_of(48 + frames(&s, 0.25));
+ for clip in [clips[0].0, clips[0].1] {
+ assert_eq!(s.active_sequence().unwrap().find_item(clip).unwrap().1.end(), expected);
+ }
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, *before);
+}
+
+/// The shorter audio handle limits the picture too; separately applying the two cuts desyncs them.
+#[test]
+fn linked_trim_roll_uses_the_shortest_handle() {
+ let (mut s, clips) = linked_cut();
+ let rate = s.sequence_rate();
+ s.edit_sequence("Short audio handle", |q, _, _| {
+ q.find_item_mut(clips[1].1).unwrap().1.source_in = rate.tick_of(2);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("trim.selectEditPoint", json!({"clip": clips[0].0.0, "edge": "out", "kind": "roll"})).unwrap();
+ s.execute("trim.nudge", json!({"frames": -10})).unwrap();
+ for clip in [clips[0].0, clips[0].1] {
+ assert_eq!(s.active_sequence().unwrap().find_item(clip).unwrap().1.end(), rate.tick_of(46));
+ }
+}
+
+/// Locked partners are neither selected nor changed; directly trimming a locked primary fails.
+#[test]
+fn linked_trim_respects_locked_tracks() {
+ for kind in ["trim", "ripple", "roll"] {
+ let (mut s, clips) = linked_cut();
+ s.execute("timeline.setTrack", json!({"track": "A1", "locked": true})).unwrap();
+ s.execute("trim.selectEditPoint", json!({"clip": clips[0].0.0, "edge": "out", "kind": kind})).unwrap();
+ assert_eq!(s.state.edit_points.len(), 1);
+ let audio = s.active_sequence().unwrap().audio_tracks[0].clone();
+ s.execute("trim.nudge", json!({"frames": -3})).unwrap();
+ assert_eq!(s.active_sequence().unwrap().audio_tracks[0], audio);
+ s.execute("trim.selectEditPoint", json!({"clip": clips[0].1.0, "edge": "out", "kind": kind})).unwrap();
+ let before = s.project.clone();
+ assert!(s.execute("trim.nudge", json!({"frames": -3})).is_err());
+ assert_eq!(*s.project, *before);
+ }
+}
+
+/// A split audio cut stays separate from a picture roll; linked selection off also edits one cut.
+#[test]
+fn split_or_disabled_linked_roll_leaves_audio_alone() {
+ for split in [false, true] {
+ let (mut s, clips) = linked_cut();
+ s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
+ if split {
+ s.execute("timeline.roll", json!({"left": clips[0].1.0, "right": clips[1].1.0, "deltaFrames": -4})).unwrap();
+ s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
+ }
+ let audio = s.active_sequence().unwrap().audio_tracks[0].clone();
+ s.execute("trim.selectEditPoint", json!({"clip": clips[0].0.0, "edge": "out", "kind": "roll"})).unwrap();
+ assert_eq!(s.state.edit_points.len(), 1);
+ s.execute("trim.nudge", json!({"frames": 3})).unwrap();
+ assert_eq!(s.active_sequence().unwrap().audio_tracks[0], audio);
+ assert_eq!(s.active_sequence().unwrap().find_item(clips[0].0).unwrap().1.end(), s.sequence_rate().tick_of(51));
+ }
+}
+
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
@@ -206,9 +385,10 @@ fn trim_monitor_sides_and_shift_counters() {
assert_eq!(s.execute("trim.monitor", json!({})).unwrap()["inShift"], json!(0));
// Apply Default Transitions to Selection at the edit point
let r = s.execute("trim.applyDefaultTransition", json!({})).unwrap();
- assert_eq!(r["transitions"].as_array().unwrap().len(), 1, "{r}");
+ assert_eq!(r["transitions"].as_array().unwrap().len(), 2, "picture and linked sound: {r}");
let seq = s.execute("sequence.inspect", json!({})).unwrap();
assert!(!seq["video"][0]["transitions"].as_array().unwrap().is_empty());
+ assert!(!seq["audio"][0]["transitions"].as_array().unwrap().is_empty());
}
#[test]
diff --git a/crates/ui-egui/tests/it/edit_point_menu_ui.rs b/crates/ui-egui/tests/it/edit_point_menu_ui.rs
index afe545975..7632e6acf 100644
--- a/crates/ui-egui/tests/it/edit_point_menu_ui.rs
+++ b/crates/ui-egui/tests/it/edit_point_menu_ui.rs
@@ -112,14 +112,21 @@ fn right_clicking_a_cut_opens_the_edit_point_menu() {
}
assert!(!d.has("timeline.clipMenu.edit.cut"), "not the clip menu");
let eps = d.harness.state_mut().session.state.edit_points.clone();
- assert_eq!(eps.len(), 1, "the cut is selected as an edit point");
+ assert_eq!(eps.len(), 2, "the picture cut and its linked sound are selected");
assert!((eps[0].clip == a && eps[0].out) || (eps[0].clip == b && !eps[0].out), "{eps:?}");
+ let seq = d.seq();
+ let picture = seq.find_item(eps[0].clip).unwrap().1;
+ let (track, sound) = seq.find_item(eps[1].clip).unwrap();
+ assert!(seq.audio_tracks.iter().any(|t| t.id == track));
+ assert!(picture.link.is_some());
+ assert_eq!(sound.link, picture.link);
// Trim In: the incoming clip's In edge, as a regular trim
d.click("timeline.editPointMenu.trimIn");
let ep = d.harness.state_mut().session.state.edit_points.clone();
- assert_eq!(ep.len(), 1);
+ assert_eq!(ep.len(), 2);
assert_eq!((ep[0].clip, ep[0].out, serde_json::to_value(ep[0].kind).unwrap()), (b, false, json!("trim")));
+ assert_eq!((ep[1].out, ep[1].kind), (ep[0].out, ep[0].kind), "sound has the same trim edge and kind");
// Apply Default Transitions puts a transition on the cut
d.right_click(b, 0.0);
diff --git a/crates/ui-egui/tests/it/timeline_trim_ui.rs b/crates/ui-egui/tests/it/timeline_trim_ui.rs
index a72802dd7..8e859c09a 100644
--- a/crates/ui-egui/tests/it/timeline_trim_ui.rs
+++ b/crates/ui-egui/tests/it/timeline_trim_ui.rs
@@ -275,6 +275,49 @@ fn a_wobbly_click_on_an_edge_selects_the_edit_point() {
assert!(!st.selection.contains(&ClipId(city)), "the clip is not selected");
}
+/// Click a real rolling edge, then the Trim Monitor's +1 button: linked sound follows exactly once.
+fn linked_trim_monitor() -> Driver {
+ let mut d = Driver::demo();
+ let rate = d.app().session.sequence_rate();
+ let video = ClipId(d.v1_clip(CITY));
+ let q = d.app().session.active_sequence().unwrap();
+ let picture = q.find_item(video).unwrap().1;
+ let audio = q.audio_tracks[0].items.iter().find(|i| i.link.is_some() && i.link == picture.link).unwrap().id;
+ let cut = picture.end();
+ d.exec("tool.rolling", json!({}));
+ d.frames(4);
+ let (_, x, y) = d.edges(video.0);
+ d.drag(pos2(x - 2.0, y), pos2(x - 2.0, y), 1);
+ let points = &d.app().session.state.edit_points;
+ assert_eq!(points.len(), 2, "both linked edges selected: {points:?}");
+ assert!(points.iter().any(|e| e.clip == audio));
+ let before = d.app().session.project.clone();
+ d.ok("ui.click", json!({"id": "trimMonitor.forward"}));
+ d.frames(4);
+ for clip in [video, audio] {
+ assert_eq!(d.span(clip.0).1, (cut + rate.frame_duration()).0);
+ }
+ let after = d.app().session.project.clone();
+ d.exec("edit.undo", json!({}));
+ assert_eq!(*d.app().session.project, *before);
+ d.exec("edit.redo", json!({}));
+ assert_eq!(*d.app().session.project, *after);
+ d
+}
+
+/// #3085: the timeline gesture and Trim Monitor button keep picture and sound synchronized.
+#[test]
+fn trim_monitor_button_rolls_linked_audio_once() {
+ linked_trim_monitor();
+}
+
+/// Visual check of the linked edit brackets and Trim Monitor after one frame of rolling.
+#[test]
+#[ignore = "renders a screenshot; requires a GPU"]
+fn screenshot_linked_trim_monitor() {
+ linked_trim_monitor().screenshot("linked-trim-monitor");
+}
+
/// A moved clip stays under the point it was grabbed by. It used to lag behind the pointer by the
/// distance egui waits before it calls a press a drag.
#[test]
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index c21746922..1dfd6498b 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -150,7 +150,12 @@ the new clips as `copied`, they are selected, and copies of linked clips are lin
**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
-it shows. Dynamic trimming takes an explicit clock (seconds) so it is deterministic: `trim.shuttle
+it shows. With Linked Selection on, selecting an edge includes its unlocked linked partners, even
+on untargeted tracks; `add: true` (Shift-click) toggles the group. Regular/ripple trims select the
+corresponding In/Out edges. Rolls include only matching linked cuts at the same time, leaving split
+audio cuts separate. Each linked group moves once and shares its tightest trim limit; turning
+Linked Selection off allows individual edges to be selected and edited.
+Dynamic trimming takes an explicit clock (seconds) so it is deterministic: `trim.shuttle
{direction, slow?, clock}` (J/L), `trim.tick {clock}`, `trim.shuttleStop {clock?}` (K, one undo step),
`trim.cancelDynamic` (Esc), `trim.playAround {clock, loop?}` (Space / Shift+K).