FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M3.2: trim mode engine — edit point selection (nearest as ripple/roll/trim), Toggle Trim Type (Ctrl+T), Trim Forward/Backward (Alt+arrows, ×5 with Shift), Extend to Playhead (E), Q/W and Alt+Q/W as extract/lift on targeted tracks; linked partners ripple-trim as one group (fixes SyncLockConflict when shortening linked clips)
Brandon Thomas8800bb37d51f
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rsindex bcf70a053..79fc5d181 100644--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@ -503,6 +503,82 @@ pub fn trim(seq: &mut Sequence, clip: ClipId, edge: Edge, mode: TrimMode, delta:Ok(d)}+/// Ripple-trim one edge of a group of linked items (e.g. a clip and its audio partners) as a single+/// edit: every member's edge moves by the same delta, later material on the members' tracks and on+/// sync-locked tracks shifts by the change. Only tracks without a group member can block the edit+/// (a sync-locked track whose material would be overwritten).+pub fn ripple_trim_group(seq: &mut Sequence, clips: &[ClipId], edge: Edge, delta: Tick, ctx: &mut EditCtx) -> Result<Tick> {+ let Some(&first) = clips.first() else { return Ok(Tick::ZERO) };+ let mut d = delta;+ for c in clips {+ let x = clamp_trim(seq, *c, edge, TrimMode::Ripple, d, ctx)?;+ if x.abs() < d.abs() {+ d = x;+ }+ }+ if d == Tick::ZERO {+ return Ok(d);+ }+ let mut work = seq.clone();+ // track → shift origin for the members on it+ let mut origins: Vec<(TrackId, Tick)> = Vec::new();+ for c in clips {+ let (tid, it) = work.find_item_mut(*c).ok_or(EditError::NoItem(*c))?;+ let speed = it.speed.abs();+ let from = match edge {+ Edge::In => it.start + Tick(1),+ Edge::Out => it.end(),+ };+ match edge {+ Edge::In => {+ if !it.reverse && it.frame_hold.is_none() {+ it.source_in += src_of(d, speed);+ }+ it.duration -= d;+ }+ Edge::Out => {+ if it.reverse {+ it.source_in -= src_of(d, speed);+ }+ it.duration += d;+ }+ }+ if !origins.iter().any(|(t, _)| *t == tid) {+ origins.push((tid, from));+ }+ }+ let main_from = {+ let (tid, _) = seq.find_item(first).ok_or(EditError::NoItem(first))?;+ origins.iter().find(|(t, _)| *t == tid).map(|o| o.1).unwrap_or_default()+ };+ let shift = if edge == Edge::In { -d } else { d };+ for tr in work.all_tracks_mut() {+ if tr.locked {+ continue;+ }+ let member = origins.iter().find(|(t, _)| *t == tr.id).map(|o| o.1);+ if member.is_none() && !tr.sync_lock {+ continue;+ }+ let from = member.unwrap_or(main_from);+ if member.is_none() && shift < Tick::ZERO {+ let at = if edge == Edge::In { from - Tick(1) } else { from };+ if !track_range_empty(tr, TimeRange::new(at + shift, -shift)) {+ return Err(EditError::SyncLockConflict);+ }+ }+ for i in &mut tr.items {+ if !clips.contains(&i.id) && i.start >= from {+ i.start += shift;+ }+ }+ tr.sort();+ }+ work.check().map_err(EditError::Other)?;+ *seq = work;+ Ok(d)+}+/// Rolling edit between two adjacent items on one track: moves the cut by `delta`.pub fn roll(seq: &mut Sequence, left: ClipId, right: ClipId, delta: Tick, ctx: &mut EditCtx) -> Result<Tick> {let (_, l) = seq.find_item(left).ok_or(EditError::NoItem(left))?;diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 34298a8c8..23c8d5969 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -60,6 +60,11 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {fn always(_: &Session) -> std::result::Result<(), String> {Ok(())}+fn has_edit_points(s: &Session) -> std::result::Result<(), String> {+ has_seq(s)?;+ if s.state.edit_points.is_empty() { Err("no edit points selected".into()) } else { Ok(()) }+}+fn has_seq(s: &Session) -> std::result::Result<(), String> {s.active_sequence().map(|_| ()).ok_or_else(|| "no sequence is open".into())}@@ -1212,13 +1217,10 @@ fn build() -> Vec<CommandSpec> {}}if mode == TrimMode::Ripple {- edit::trim(q, c, edge, mode, dd, ctx)?;- for o in clips.iter().filter(|o| **o != c) {- // partners on other tracks were already shifted by sync lock; trim their edge in place- let (_, it) = q.find_item(*o).ok_or(filmcraft_edit::EditError::NoItem(*o))?;- let _ = it;- edit::trim(q, *o, edge, TrimMode::Regular, if edge == Edge::In { Tick::ZERO } else { dd }, ctx).ok();- }+ // the clip and its linked partners ripple as one edit+ let mut group = vec![c];+ group.extend(clips.iter().copied().filter(|o| *o != c));+ dd = edit::ripple_trim_group(q, &group, edge, dd, ctx)?;} else {for c in &clips {edit::trim(q, *c, edge, mode, dd, ctx)?;@@ -1229,6 +1231,50 @@ fn build() -> Vec<CommandSpec> {Ok(json!({"delta": applied.0}))}),+ // ================= Trim mode =================+ cmd!("trim.selectEditPoint", "Select Edit Point", [], None, r#"{"clip":id,"edge":"in|out","kind":"trim|ripple|roll","add":bool?}"#, has_seq, |s, p| {+ crate::trim::select(s, p)+ }),+ cmd!("trim.selectNearest", "Select Nearest Edit Point", [], None, r#"{"kind":"rippleIn|rippleOut|roll|trimIn|trimOut"}"#, has_seq, |s, p| {+ crate::trim::select_nearest(s, p)+ }),+ cmd!("trim.edit", "Trim Edit", ["Sequence"], Some("Shift+T"), "{}", has_seq, |s, _| {+ if s.state.edit_points.is_empty() {+ crate::trim::select_nearest(s, &json!({"kind": "roll"}))+ } else {+ Ok(json!({"editPoints": s.state.edit_points}))+ }+ }),+ cmd!("trim.clear", "Clear Edit Point Selection", [], None, "{}", has_edit_points, |s, _| {+ s.state.edit_points.clear();+ Ok(Value::Null)+ }),+ cmd!("trim.toggleType", "Toggle Trim Type", [], Some("Ctrl+T"), "{}", has_edit_points, |s, _| crate::trim::toggle_type(s)),+ cmd!("trim.backward", "Trim Backward", [], Some("Alt+Left"), "{}", has_edit_points, |s, _| crate::trim::nudge(s, &json!({"frames": -1}))),+ cmd!("trim.forward", "Trim Forward", [], Some("Alt+Right"), "{}", has_edit_points, |s, _| crate::trim::nudge(s, &json!({"frames": 1}))),+ cmd!("trim.backwardMany", "Trim Backward Many", [], Some("Alt+Shift+Left"), "{}", has_edit_points, |s, _| crate::trim::nudge(+ s,+ &json!({"frames": -5})+ )),+ cmd!("trim.forwardMany", "Trim Forward Many", [], Some("Alt+Shift+Right"), "{}", has_edit_points, |s, _| crate::trim::nudge(s, &json!({"frames": 5}))),+ cmd!("trim.nudge", "Trim by Frames", [], None, r#"{"frames":i64}"#, has_edit_points, |s, p| crate::trim::nudge(s, p)),+ cmd!("trim.extendToPlayhead", "Extend Selected Edit to Playhead", [], Some("E"), "{}", has_edit_points, |s, _| { crate::trim::extend_to_playhead(s) }),+ cmd!("trim.ripplePrevious", "Ripple Trim Previous Edit to Playhead", [], Some("Q"), "{}", has_seq, |s, _| crate::trim::to_playhead(+ s,+ &json!({"side": "previous", "ripple": true})+ )),+ cmd!("trim.rippleNext", "Ripple Trim Next Edit to Playhead", [], Some("W"), "{}", has_seq, |s, _| crate::trim::to_playhead(+ s,+ &json!({"side": "next", "ripple": true})+ )),+ cmd!("trim.previous", "Trim Previous Edit to Playhead", [], Some("Alt+Q"), "{}", has_seq, |s, _| crate::trim::to_playhead(+ s,+ &json!({"side": "previous", "ripple": false})+ )),+ cmd!("trim.next", "Trim Next Edit to Playhead", [], Some("Alt+W"), "{}", has_seq, |s, _| crate::trim::to_playhead(+ s,+ &json!({"side": "next", "ripple": false})+ )),cmd!("timeline.roll", "Rolling Edit", [], None, r#"{"left":id,"right":id,"delta":ticks|"deltaFrames":i64}"#, has_seq, |s, p| {let (l, r) = (clip_p(p, "left").ok_or_else(|| bad("timeline.roll", "need `left`"))?,diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex e3a6e9d4e..16b3343fe 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -11,6 +11,7 @@pub mod commands;pub mod demo;pub mod media_pool;+pub mod trim;use std::sync::Arc;@@ -118,6 +119,9 @@ pub struct EditorState {pub clipboard: Vec<(TrackKind, usize, filmcraft_project::TrackItem)>,pub default_video_transition: String,pub default_audio_transition: String,+ /// Selected edit points (trim mode).+ #[serde(default)]+ pub edit_points: Vec<trim::EditPoint>,}/// Events for frontends (drained each frame).diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex dceb63161..20f4235c2 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -139,3 +139,69 @@ fn save_and_open_roundtrip() {assert!(t.render_program(0.1).is_some());std::fs::remove_dir_all(dir).ok();}++/// Demo project with sync lock off on every track except V1/A1 (the A2 score spans every cut).+fn demo_unlocked() -> Session {+ let mut s = demo();+ for t in ["V2", "V3", "A2", "A3"] {+ let _ = s.execute("timeline.setTrack", json!({"track": t, "syncLock": false}));+ }+ s+}++fn v1(s: &Session) -> Vec<(u64, Tick, Tick)> {+ s.active_sequence().unwrap().video_tracks[0].items.iter().map(|i| (i.id.0, i.start, i.end())).collect()+}++#[test]+fn trim_mode_roll_ripple_and_toggle() {+ let mut s = demo_unlocked();+ let rate = s.sequence_rate();+ let clips = v1(&s);+ // park near the first V1 cut and pick it as a roll+ let cut = clips[0].2;+ s.execute("playhead.set", json!({"time": (cut + rate.tick_of(2)).0})).unwrap();+ let r = s.execute("trim.selectNearest", json!({"kind": "roll"})).unwrap();+ assert!(!r["editPoints"].as_array().unwrap().is_empty());+ let dur_before = s.active_sequence().unwrap().duration();+ s.execute("trim.forwardMany", json!({})).unwrap();+ let after = v1(&s);+ let left = after.iter().find(|c| c.0 == clips[0].0).unwrap();+ assert_eq!(left.2, cut + rate.tick_of(5), "roll moved the cut 5 frames later");+ assert_eq!(s.active_sequence().unwrap().duration(), dur_before, "roll keeps the duration");+ // toggle Roll -> Trim -> Ripple; ripple backward shortens the sequence+ s.execute("trim.toggleType", json!({})).unwrap();+ s.execute("trim.toggleType", json!({})).unwrap();+ assert_eq!(s.state.edit_points[0].kind, crate::trim::TrimKind::Ripple);+ let d0 = s.active_sequence().unwrap().duration();+ s.execute("trim.backward", json!({})).unwrap();+ assert!(s.active_sequence().unwrap().duration() <= d0, "ripple trim back must not lengthen");+ s.execute("trim.clear", json!({})).unwrap();+ assert!(s.execute("trim.forward", json!({})).is_err(), "disabled without edit points");+}++#[test]+fn ripple_trim_to_playhead_q_w() {+ let mut s = demo_unlocked();+ let rate = s.sequence_rate();+ let clips = v1(&s);+ let (id, start, end) = clips[1];+ let d0 = s.active_sequence().unwrap().duration();+ // W: ripple trim the end of the clip under the playhead to the playhead+ let ph = start + rate.tick_of(10);+ s.execute("playhead.set", json!({"time": ph.0})).unwrap();+ s.execute("trim.rippleNext", json!({})).unwrap();+ let c = v1(&s).into_iter().find(|c| c.0 == id).unwrap();+ assert_eq!(c.2, ph, "clip now ends at the playhead");+ assert_eq!(s.active_sequence().unwrap().duration(), d0 - (end - ph), "later material rippled left");+ // Q: ripple trim the start of the (new) clip under the playhead to the playhead+ let (_, start2, end2) = v1(&s)[2];+ let d1 = s.active_sequence().unwrap().duration();+ let ph2 = start2 + rate.tick_of(6);+ s.execute("playhead.set", json!({"time": ph2.0})).unwrap();+ s.execute("trim.ripplePrevious", json!({})).unwrap();+ let c2 = v1(&s).into_iter().find(|c| c.1 == start2).expect("a clip still starts at the old edit");+ assert_eq!(c2.2, end2 - rate.tick_of(6), "its head (6 frames) was removed");+ assert_eq!(s.active_sequence().unwrap().duration(), d1 - rate.tick_of(6));+ assert_eq!(s.playhead(), start2, "playhead parks on the new edit");+}diff --git a/crates/engine/src/trim.rs b/crates/engine/src/trim.rsnew file mode 100644index 000000000..aa8494827--- /dev/null+++ b/crates/engine/src/trim.rs@@ -0,0 +1,229 @@+//! Trim mode: selected edit points and keyboard trimming (Premiere's trim workflow).+//!+//! 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.++use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use filmcraft_project::{ClipId, Sequence, TrackId};+use filmcraft_time::{Tick, TimeRange};++use crate::{EngineError, Result, Session};++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum TrimKind {+ /// Regular trim: the edge moves, leaving a gap or covering a neighbour's gap.+ Trim,+ /// Ripple: the edge moves and later material shifts to close/open the difference.+ Ripple,+ /// Roll: the shared edge between two adjacent clips moves; duration is unchanged.+ Roll,+}++impl TrimKind {+ fn next(self) -> Self {+ match self {+ TrimKind::Ripple => TrimKind::Roll,+ TrimKind::Roll => TrimKind::Trim,+ TrimKind::Trim => TrimKind::Ripple,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct EditPoint {+ pub clip: ClipId,+ /// The clip's Out edge (else its In edge).+ pub out: bool,+ pub kind: TrimKind,+}++/// Time of an edit point in the sequence.+pub fn edit_time(seq: &Sequence, ep: &EditPoint) -> Option<Tick> {+ let (_, it) = seq.find_item(ep.clip)?;+ Some(if ep.out { it.end() } else { it.start })+}++/// The (left, right) clips of a roll at this edit point.+pub fn roll_pair(seq: &Sequence, ep: &EditPoint) -> Option<(ClipId, ClipId)> {+ let (tid, it) = seq.find_item(ep.clip)?;+ let track = seq.track(tid)?;+ if ep.out {+ let right = track.items.iter().find(|o| o.start == it.end())?;+ Some((it.id, right.id))+ } else {+ let left = track.items.iter().find(|o| o.end() == it.start)?;+ Some((left.id, it.id))+ }+}++fn kind_p(p: &Value) -> Option<TrimKind> {+ serde_json::from_value(p.get("kind")?.clone()).ok()+}++/// `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()))?;+ let out = p.get("edge").and_then(Value::as_str) != Some("in");+ 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 };+ 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);+ }+ } else {+ s.state.edit_points = vec![ep];+ }+ s.state.selection.clear();+ Ok(json!({"editPoints": s.state.edit_points}))+}++/// `trim.selectNearest {kind: "rippleIn"|"rippleOut"|"roll"|"trimIn"|"trimOut"}`: the edit point+/// nearest the playhead on each targeted track (all tracks when none are targeted).+pub fn select_nearest(s: &mut Session, p: &Value) -> Result<Value> {+ let which = p.get("kind").and_then(Value::as_str).unwrap_or("roll");+ let (kind, want_out) = match which {+ "rippleIn" => (TrimKind::Ripple, Some(false)),+ "rippleOut" => (TrimKind::Ripple, Some(true)),+ "trimIn" => (TrimKind::Trim, Some(false)),+ "trimOut" => (TrimKind::Trim, Some(true)),+ _ => (TrimKind::Roll, None),+ };+ let ph = s.playhead();+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ 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) {+ continue;+ }+ // nearest edge on this track+ let mut best: Option<(i64, EditPoint)> = None;+ for it in &tr.items {+ for out in [false, true] {+ if want_out.is_some_and(|w| w != out) {+ continue;+ }+ let t = if out { it.end() } else { it.start };+ let ep = EditPoint { clip: it.id, out, kind };+ if kind == TrimKind::Roll && roll_pair(seq, &ep).is_none() {+ continue;+ }+ let d = (t - ph).0.abs();+ if best.is_none_or(|(bd, _)| d < bd) {+ best = Some((d, ep));+ }+ }+ }+ 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;+ }+ points.push(ep);+ }+ }+ s.state.edit_points = points;+ s.state.selection.clear();+ Ok(json!({"editPoints": s.state.edit_points}))+}++/// `trim.toggleType`: cycle Ripple → Roll → Trim for every selected edit point.+pub fn toggle_type(s: &mut Session) -> Result<Value> {+ for e in s.state.edit_points.iter_mut() {+ e.kind = e.kind.next();+ }+ Ok(json!({"editPoints": s.state.edit_points}))+}++/// Trim every selected edit point by `delta` (edit point movement; positive = later).+fn trim_all(s: &mut Session, delta: Tick) -> Result<Value> {+ if s.state.edit_points.is_empty() {+ return Err(EngineError::Other("no edit points selected".into()));+ }+ let pts = s.state.edit_points.clone();+ let mut applied = Vec::new();+ for ep in &pts {+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ 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}))?+ }+ 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}),+ )?,+ };+ applied.push(r.get("delta").cloned().unwrap_or(Value::Null));+ }+ Ok(json!({"applied": applied}))+}++/// `trim.nudge {frames}`: Trim Forward/Backward (±1), Many (±5 by default).+pub fn nudge(s: &mut Session, p: &Value) -> Result<Value> {+ let frames = p.get("frames").and_then(Value::as_i64).unwrap_or(1);+ let d = s.sequence_rate().tick_of(frames);+ trim_all(s, d)+}++/// `trim.extendToPlayhead`: move each selected edit point to the playhead.+pub fn extend_to_playhead(s: &mut Session) -> Result<Value> {+ let ph = s.playhead();+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let first = s.state.edit_points.first().and_then(|e| edit_time(seq, e)).ok_or_else(|| EngineError::Other("no edit points selected".into()))?;+ trim_all(s, ph - first)+}++/// `trim.toPlayhead {side: "previous"|"next", ripple}` (Q/W, ⌥Q/⌥W): remove the material between+/// the playhead and the previous (Q) or next (W) edit point on the targeted tracks. Ripple variants+/// extract the range (later material moves left, sync locks respected); the others lift it.+pub fn to_playhead(s: &mut Session, p: &Value) -> Result<Value> {+ let next = p.get("side").and_then(Value::as_str) == Some("next");+ let ripple = p.get("ripple").and_then(Value::as_bool).unwrap_or(true);+ let ph = s.playhead();+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let targeted = s.targeting().targeted;+ let tracks: Vec<TrackId> = seq+ .video_tracks+ .iter()+ .chain(seq.audio_tracks.iter())+ .filter(|t| targeted.contains(&t.id) && !t.locked && t.items.iter().any(|i| i.start < ph && ph < i.end()))+ .map(|t| t.id)+ .collect();+ if tracks.is_empty() {+ return Err(EngineError::Other("no clip under the playhead on the targeted tracks".into()));+ }+ // nearest edit point on those tracks+ let edits =+ seq.video_tracks.iter().chain(seq.audio_tracks.iter()).filter(|t| tracks.contains(&t.id)).flat_map(|t| t.items.iter().flat_map(|i| [i.start, i.end()]));+ let edge = if next { edits.filter(|e| *e > ph).min() } else { edits.filter(|e| *e < ph).max() };+ let edge = edge.ok_or_else(|| EngineError::Other("no edit point".into()))?;+ let range = if next { TimeRange::from_bounds(ph, edge) } else { TimeRange::from_bounds(edge, ph) };+ let label = match (next, ripple) {+ (true, true) => "Ripple Trim Next Edit to Playhead",+ (false, true) => "Ripple Trim Previous Edit to Playhead",+ (true, false) => "Trim Next Edit to Playhead",+ (false, false) => "Trim Previous Edit to Playhead",+ };+ s.edit_sequence(label, |q, ctx, _| {+ if ripple {+ filmcraft_edit::extract(q, &tracks, range, ctx);+ } else {+ filmcraft_edit::lift(q, &tracks, range, ctx);+ }+ Ok(())+ })?;+ if !next && ripple {+ // the head before the playhead was removed; park on the new edit (as Premiere does)+ s.set_playhead(edge);+ }+ Ok(json!({"range": [range.start.0, range.end().0]}))+}