FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#648, #668: select a gap and close it with Delete or Ripple Delete
Oskarc8f85af5a1c5
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 0b3a9f8a6..390cc2366 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -82,16 +82,20 @@ pub(crate) fn has_selection(s: &Session) -> std::result::Result<(), String> {/// Clips or captions selected (Clear / Ripple Delete work on either).fn has_any_selection(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;- if s.state.selection.is_empty() && s.state.caption_selection.is_empty() && s.state.transition_selection.is_empty() {+ if s.state.selection.is_empty() && s.state.caption_selection.is_empty() && s.state.transition_selection.is_empty() && s.state.gap_selection.is_none() {Err("nothing selected".into())} else {Ok(())}}-/// Clips or captions selected (Ripple Delete: a transition has no length of its own to close).+/// Clips, captions or a gap selected (Ripple Delete: a transition has no length of its own to close).fn has_clip_or_caption_selection(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;- if s.state.selection.is_empty() && s.state.caption_selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }+ if s.state.selection.is_empty() && s.state.caption_selection.is_empty() && s.state.gap_selection.is_none() {+ Err("nothing selected".into())+ } else {+ Ok(())+ }}fn has_source(s: &Session) -> std::result::Result<(), String> {has_seq(s)?;@@ -1218,6 +1222,12 @@ fn build() -> Vec<CommandSpec> {let ids = s.state.transition_selection.clone();return remove_transitions(s, &ids, "Clear");}+ // a selected gap closes, as in Premiere Pro (#648, #668)+ if s.state.caption_selection.is_empty()+ && let Some(g) = s.state.gap_selection+ {+ return ripple_delete_gap(s, g);+ }let caps = s.state.caption_selection.clone();return crate::captions::delete(s, &caps, false);}@@ -1231,6 +1241,11 @@ fn build() -> Vec<CommandSpec> {}),cmd!("edit.rippleDelete", "Ripple Delete", ["Edit"], Some("Shift+Delete"), r#"{"clips":[id]?}"#, has_clip_or_caption_selection, |s, p| {if p.get("clips").is_none() && p.get("clip").is_none() && s.state.selection.is_empty() {+ if s.state.caption_selection.is_empty()+ && let Some(g) = s.state.gap_selection+ {+ return ripple_delete_gap(s, g);+ }let caps = s.state.caption_selection.clone();return crate::captions::delete(s, &caps, true);}@@ -1250,11 +1265,13 @@ fn build() -> Vec<CommandSpec> {cmd!("edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{}", has_seq, |s, _| {let all: Vec<ClipId> = s.active_sequence().map(|q| q.all_tracks().flat_map(|t| t.items.iter().map(|i| i.id)).collect()).unwrap_or_default();s.state.selection = all;+ s.state.gap_selection = None;Ok(json!({"selected": s.state.selection.len()}))}),cmd!("edit.deselectAll", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always, |s, _| {s.state.selection.clear();s.state.caption_selection.clear();+ s.state.gap_selection = None;Ok(Value::Null)}),cmd!("edit.duplicate", "Duplicate", ["Edit"], Some("Cmd+Shift+/"), "{}", has_project_selection, |s, _| {@@ -1648,21 +1665,7 @@ fn build() -> Vec<CommandSpec> {cmd!("sequence.closeGap", "Close Gap", ["Sequence"], None, r#"{"track":"V1"|id,"time":ticks}"#, has_seq, |s, p| {let tr = track_p(s, p, "track", "sequence.closeGap")?.ok_or_else(|| bad("sequence.closeGap", "need `track`"))?;let t = time_p(s, p, "").unwrap_or(s.playhead());- s.edit_sequence("Ripple Delete", |q, _, st| {- let before: Vec<(ClipId, Tick)> = q.track(tr).map(|x| x.items.iter().map(|i| (i.id, i.start)).collect()).unwrap_or_default();- edit::close_gap(q, tr, t)?;- if st.ripple_sequence_markers {- // the gap ended where the first clip that moved started- let moved = before- .iter()- .filter_map(|(id, old)| q.find_item(*id).filter(|(_, i)| i.start != *old).map(|(_, i)| (*old, *old - i.start)))- .min_by_key(|m| m.0);- if let Some((end, len)) = moved {- crate::sequence_tools::ripple_markers(&mut q.markers, end, -len);- }- }- Ok(())- })?;+ close_gap(s, tr, t)?;Ok(Value::Null)}),cmd!("sequence.snap", "Snap in Timeline", ["Sequence"], Some("S"), r#"{"on":bool?}"#, always, |s, p| {@@ -2146,8 +2149,9 @@ fn build() -> Vec<CommandSpec> {// selecting clips leaves trim mode (Premiere: clip and edit point selections are exclusive)s.state.edit_points.clear();s.state.trim_shift = Default::default();- // and a clip selection replaces a transition one+ // and a clip selection replaces a transition or gap ones.state.transition_selection.clear();+ s.state.gap_selection = None;if bool_p(p, "toggle").unwrap_or(false) {for c in clips {if let Some(i) = s.state.selection.iter().position(|x| *x == c) {@@ -2168,6 +2172,7 @@ fn build() -> Vec<CommandSpec> {}Ok(json!({"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}))}),+ cmd!("timeline.selectGap", "Select Gap", [], None, r#"{"track":"V1"|id,"time":ticks|"frame":n|"seconds":f}"#, has_seq, select_gap),cmd!("timeline.move","Move Clips",@@ -3350,6 +3355,7 @@ fn select_transitions(s: &mut Session, ids: &Value, add: bool, toggle: bool) ->}s.state.selection.clear();s.state.caption_selection.clear();+ s.state.gap_selection = None;s.state.edit_points.clear();s.state.trim_shift = Default::default();Ok(json!({"selection": [], "transitionSelection": s.state.transition_selection.iter().map(|t| t.0).collect::<Vec<_>>()}))@@ -3366,6 +3372,59 @@ fn remove_transitions(s: &mut Session, ids: &[TransitionId], label: &str) -> ResOk(json!({"removed": n}))}+/// `timeline.selectGap`: select the gap on `track` at `time` (clicking empty space between+/// clips, #648, #668). It replaces the clip, transition, caption and edit point selections, as+/// in Premiere Pro. Empty time after a track's last clip is not a gap.+fn select_gap(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "timeline.selectGap";+ let track = track_p(s, p, "track", CMD)?.ok_or_else(|| bad(CMD, "need `track`"))?;+ let t = time_p(s, p, "").ok_or_else(|| bad(CMD, "need `time`, `frame` or `seconds`"))?;+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let tr = q.track(track).ok_or_else(|| bad(CMD, format!("no track {}", track.0)))?;+ if tr.locked {+ return Err(EngineError::Edit(edit::EditError::Locked));+ }+ let range = edit::through::track_gaps(tr).into_iter().find(|g| g.contains(t)).ok_or_else(|| bad(CMD, "there is no gap there"))?;+ s.state.gap_selection = Some(crate::GapSelection { track, range });+ s.state.selection.clear();+ s.state.caption_selection.clear();+ s.state.transition_selection.clear();+ s.state.edit_points.clear();+ s.state.trim_shift = Default::default();+ Ok(json!({"track": track.0, "start": range.start.0, "end": range.end().0}))+}++/// Close the selected gap (Delete, Backspace or Ripple Delete on a gap).+fn ripple_delete_gap(s: &mut Session, g: crate::GapSelection) -> Result<Value> {+ let still = s.active_sequence().and_then(|q| q.track(g.track)).is_some_and(|tr| edit::through::track_gaps(tr).contains(&g.range));+ if !still {+ s.state.gap_selection = None;+ return Err(EngineError::Other("the selected gap is no longer there".into()));+ }+ close_gap(s, g.track, g.range.start)?;+ s.state.gap_selection = None;+ Ok(json!({"closed": g.range.duration.0}))+}++/// `sequence.closeGap`: ripple the gap on `track` at `t` closed (one undo step, "Ripple Delete").+fn close_gap(s: &mut Session, tr: TrackId, t: Tick) -> Result<()> {+ s.edit_sequence("Ripple Delete", |q, _, st| {+ let before: Vec<(ClipId, Tick)> = q.track(tr).map(|x| x.items.iter().map(|i| (i.id, i.start)).collect()).unwrap_or_default();+ edit::close_gap(q, tr, t)?;+ if st.ripple_sequence_markers {+ // the gap ended where the first clip that moved started+ let moved = before+ .iter()+ .filter_map(|(id, old)| q.find_item(*id).filter(|(_, i)| i.start != *old).map(|(_, i)| (*old, *old - i.start)))+ .min_by_key(|m| m.0);+ if let Some((end, len)) = moved {+ crate::sequence_tools::ripple_markers(&mut q.markers, end, -len);+ }+ }+ Ok(())+ })+}+/// `sequence.setTransition`: edit an applied transition (Effect Controls, the Timeline): its/// settings, Reverse, and where it sits. `duration` / `frames` resize it the way its alignment/// says (Center at Cut and Custom Start: both ends; Start at Cut: the end; End at Cut: the@@ -3588,6 +3647,7 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence"audio": q.audio_tracks.iter().map(tr).collect::<Vec<_>>(),"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>(),"transitionSelection": s.state.transition_selection.iter().map(|t| t.0).collect::<Vec<_>>(),+ "gapSelection": s.state.gap_selection.map(|g| json!({"track": g.track.0, "start": g.range.start.0, "end": g.range.end().0})),})}diff --git a/crates/engine/src/gap_selection_tests.rs b/crates/engine/src/gap_selection_tests.rsnew file mode 100644index 000000000..66f1d2d95--- /dev/null+++ b/crates/engine/src/gap_selection_tests.rs@@ -0,0 +1,174 @@+//! Selecting a gap between clips and closing it with Delete / Backspace / Ripple Delete (#648, #668):+//! `timeline.selectGap` selects the empty time on one track, `edit.clear` and `edit.rippleDelete`+//! close it as one "Ripple Delete" undo step.++use filmcraft_project::ClipId;+use filmcraft_time::Tick;+use serde_json::json;++use crate::{GapSelection, Session};++fn range(s: &Session, c: ClipId) -> (Tick, Tick) {+ s.active_sequence().unwrap().find_item(c).map(|(_, i)| (i.start, i.end())).unwrap()+}++/// Two 48-frame clips (pictures on V1, linked sounds on A1) placed at `frames`.+fn two_clips(s: &mut Session, frames: [i64; 2]) -> [(ClipId, ClipId); 2] {+ s.execute("file.openDemoProject", json!({})).unwrap();+ s.execute("file.newSequence", json!({"name": "Gaps", "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()).map(|i| i.id).unwrap();+ for f in frames {+ s.execute("timeline.place", json!({"item": item.0, "frame": f, "sourceIn": rate.tick_of(48).0, "duration": rate.tick_of(48).0})).unwrap();+ }+ s.execute("edit.deselectAll", json!({})).unwrap();+ let q = s.active_sequence().unwrap();+ [0, 1].map(|n| (q.video_tracks[0].items[n].id, q.audio_tracks[0].items[n].id))+}++#[test]+fn clicking_between_two_clips_selects_the_gap_and_delete_closes_it() {+ let mut s = Session::default();+ let [(picture1, _), (picture2, sound2)] = two_clips(&mut s, [0, 96]);+ let rate = s.sequence_rate();+ let f = |n: i64| rate.tick_of(n);+ let (f48, f60, f96) = (f(48), f(60), f(96));+ s.execute("timeline.select", json!({"clips": [picture1.0]})).unwrap();+ let before = s.project.clone();++ let r = s.execute("timeline.selectGap", json!({"track": "V1", "time": f60.0})).unwrap();+ assert_eq!(r, json!({"track": s.active_sequence().unwrap().video_tracks[0].id.0, "start": f48.0, "end": f96.0}));+ assert!(s.state.selection.is_empty(), "the gap replaces the clip selection");+ assert!(s.is_enabled("edit.clear") && s.is_enabled("edit.rippleDelete"), "Delete and Ripple Delete apply to the gap");++ // Delete / Backspace+ s.execute("edit.clear", json!({})).unwrap();+ assert_eq!(range(&s, picture2), (f48, f96), "the next clip moves up into the gap");+ assert_eq!(range(&s, sound2), (f48, f96), "and its sound with it");+ assert_eq!(range(&s, picture1).0, Tick::ZERO, "the clip before stays");+ assert!(s.state.gap_selection.is_none(), "the gap is gone");+ s.active_sequence().unwrap().check().unwrap();++ assert_eq!(s.undo().as_deref(), Some("Ripple Delete"), "one undo step");+ assert_eq!(*s.project, *before);+}++#[test]+fn ripple_delete_closes_a_selected_gap_too() {+ let mut s = Session::default();+ let [_, (picture2, _)] = two_clips(&mut s, [0, 96]);+ let rate = s.sequence_rate();+ let f = |n: i64| rate.tick_of(n);+ s.execute("timeline.selectGap", json!({"track": "A1", "frame": 50})).unwrap();+ s.execute("edit.rippleDelete", json!({})).unwrap();+ assert_eq!(range(&s, picture2).0, f(48));+}++#[test]+fn the_empty_time_before_the_first_clip_is_a_gap() {+ let mut s = Session::default();+ let [(picture1, _), (picture2, _)] = two_clips(&mut s, [24, 72]);+ let rate = s.sequence_rate();+ let f = |n: i64| rate.tick_of(n);+ let r = s.execute("timeline.selectGap", json!({"track": "V1", "frame": 5})).unwrap();+ assert_eq!((r["start"].clone(), r["end"].clone()), (json!(0), json!(f(24).0)));+ s.execute("edit.clear", json!({})).unwrap();+ assert_eq!((range(&s, picture1).0, range(&s, picture2).0), (Tick::ZERO, f(48)));+}++#[test]+fn empty_time_after_the_last_clip_is_not_a_gap() {+ let mut s = Session::default();+ two_clips(&mut s, [0, 96]);+ assert!(s.execute("timeline.selectGap", json!({"track": "V1", "frame": 400})).is_err());+ assert!(s.execute("timeline.selectGap", json!({"track": "V1", "frame": 10})).is_err(), "inside a clip");+ assert!(s.state.gap_selection.is_none());+ assert!(!s.is_enabled("edit.clear"), "nothing to delete");+}++#[test]+fn selecting_a_clip_or_deselecting_all_drops_the_gap() {+ let mut s = Session::default();+ let [(picture1, _), _] = two_clips(&mut s, [0, 96]);+ s.execute("timeline.selectGap", json!({"track": "V1", "frame": 60})).unwrap();+ s.execute("timeline.select", json!({"clips": [picture1.0]})).unwrap();+ assert!(s.state.gap_selection.is_none());+ s.execute("timeline.selectGap", json!({"track": "V1", "frame": 60})).unwrap();+ s.execute("edit.deselectAll", json!({})).unwrap();+ assert!(s.state.gap_selection.is_none());+}++/// An edit that fills the gap leaves no gap selected; Delete then removes nothing it should not.+#[test]+fn an_edit_that_changes_the_gap_drops_it() {+ let mut s = Session::default();+ let [(picture1, _), (picture2, _)] = two_clips(&mut s, [0, 96]);+ let rate = s.sequence_rate();+ let f = |n: i64| rate.tick_of(n);+ s.execute("timeline.selectGap", json!({"track": "V1", "frame": 60})).unwrap();+ s.execute("timeline.trim", json!({"clip": picture1.0, "edge": "out", "mode": "regular", "deltaFrames": 12})).unwrap();+ assert!(s.state.gap_selection.is_none(), "the gap changed");+ assert!(s.execute("edit.clear", json!({})).is_err());+ assert_eq!(range(&s, picture2).0, f(96), "nothing moved");+}++/// A stale selection (set from outside, as the control channel can) is refused, not acted on.+#[test]+fn a_stale_gap_is_refused() {+ let mut s = Session::default();+ let [_, (picture2, _)] = two_clips(&mut s, [0, 96]);+ let rate = s.sequence_rate();+ let f = |n: i64| rate.tick_of(n);+ let track = s.active_sequence().unwrap().video_tracks[0].id;+ s.state.gap_selection = Some(GapSelection { track, range: filmcraft_time::TimeRange::from_bounds(f(10), f(20)) });+ assert!(s.execute("edit.clear", json!({})).is_err());+ assert!(s.state.gap_selection.is_none());+ assert_eq!(range(&s, picture2).0, f(96));+}++#[test]+fn a_gap_on_a_locked_track_cannot_be_selected_or_closed() {+ let mut s = Session::default();+ let [_, (picture2, _)] = two_clips(&mut s, [0, 96]);+ let rate = s.sequence_rate();+ let f = |n: i64| rate.tick_of(n);+ s.execute("timeline.setTrack", json!({"track": "V1", "locked": true})).unwrap();+ assert!(s.execute("timeline.selectGap", json!({"track": "V1", "frame": 60})).is_err());+ // Sequence ▸ Close Gap moved the other tracks while the locked one stayed put+ assert!(s.execute("sequence.closeGap", json!({"track": "V1", "frame": 60})).is_err());+ assert_eq!(range(&s, picture2).0, f(96));+ let sound2 = s.active_sequence().unwrap().audio_tracks[0].items[1].id;+ assert_eq!(range(&s, sound2).0, f(96), "the unlocked sound stays in sync");+}++#[test]+fn hostile_select_gap_parameters_are_errors() {+ let mut s = Session::default();+ assert!(s.execute("timeline.selectGap", json!({"track": "V1", "frame": 1})).is_err(), "no sequence");+ two_clips(&mut s, [0, 96]);+ for p in [+ json!({}),+ json!({"track": "V1"}),+ json!({"frame": 60}),+ json!({"track": "V99", "frame": 60}),+ json!({"track": 999_999, "frame": 60}),+ json!({"track": "V1", "time": i64::MAX}),+ json!({"track": "V1", "time": i64::MIN}),+ json!({"track": "V1", "frame": i64::MAX}),+ json!({"track": "V1", "seconds": f64::MAX}),+ json!({"track": [], "frame": "x"}),+ ] {+ let _ = s.execute("timeline.selectGap", p);+ }+ assert!(s.state.gap_selection.is_none());+}++#[test]+fn the_gap_selection_is_part_of_the_ui_state() {+ let mut s = Session::default();+ two_clips(&mut s, [0, 96]);+ s.execute("timeline.selectGap", json!({"track": "V1", "frame": 60})).unwrap();+ let v = serde_json::to_value(&s.state).unwrap();+ let back: crate::EditorState = serde_json::from_value(v).unwrap();+ assert_eq!(back.gap_selection, s.state.gap_selection);+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex eea55b32a..0d48e26c5 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -57,7 +57,7 @@ use std::sync::Arc;use filmcraft_edit::EditCtx;use filmcraft_project::{ClipId, ItemId, Project, Sequence, TrackId, TrackKind};-use filmcraft_time::{FrameRate, Tick};+use filmcraft_time::{FrameRate, Tick, TimeRange};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -221,6 +221,13 @@ pub struct Targeting {pub audio_dest: Option<TrackId>,}+/// A gap on one track of the active sequence (see [`EditorState::gap_selection`]).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct GapSelection {+ pub track: TrackId,+ pub range: TimeRange,+}+/// Editing state that commands depend on (not project data, but headless-relevant).#[derive(Clone, Debug, Default, Serialize, Deserialize)]pub struct EditorState {@@ -266,6 +273,12 @@ pub struct EditorState {/// them. Selecting clips clears it and selecting transitions clears the clip selection.#[serde(default)]pub transition_selection: Vec<filmcraft_project::TransitionId>,+ /// The selected gap (#648, #668): empty time on one track, clicked in the Timeline, from the+ /// end of a clip (or the sequence start) up to the next clip. Delete, Backspace and Ripple+ /// Delete close it. Selecting clips, transitions or edit points clears it, and so does an edit+ /// that changes the gap.+ #[serde(default)]+ pub gap_selection: Option<GapSelection>,/// Selected layers (indices among the graphic layers, 0 = back) of the selected graphic clip.#[serde(default)]pub graphic_layers: Vec<usize>,@@ -776,6 +789,7 @@ impl Session {self.history.redo.clear();self.history.merge_key = None;self.state = st;+ self.drop_stale_gap();self.bump();Ok(r)}@@ -795,6 +809,7 @@ impl Session {self.refuse_self_nesting(&p)?;self.project = Arc::new(p);self.state = st;+ self.drop_stale_gap();self.bump();Ok(r)}@@ -888,6 +903,17 @@ impl Session {self.state.caption_selection.clear();}self.state.project_selection.retain(|i| p.item(*i).is_some());+ self.drop_stale_gap();+ }++ /// Forget the selected gap when it is no longer a gap of the active sequence (a clip moved+ /// into it or next to it, its track went, another sequence became the active one).+ fn drop_stale_gap(&mut self) {+ if let Some(g) = self.state.gap_selection+ && !self.active_sequence().and_then(|q| q.track(g.track)).is_some_and(|tr| filmcraft_edit::through::track_gaps(tr).contains(&g.range))+ {+ self.state.gap_selection = None;+ }}fn bump(&mut self) {@@ -1058,6 +1084,8 @@ mod export_tests;#[cfg(test)]mod file_tests;#[cfg(test)]+mod gap_selection_tests;+#[cfg(test)]mod image_sequence_tests;#[cfg(test)]mod interchange_auto_points_tests;diff --git a/crates/engine/src/trim.rs b/crates/engine/src/trim.rsindex dda7a4d14..951a873c8 100644--- a/crates/engine/src/trim.rs+++ b/crates/engine/src/trim.rs@@ -104,6 +104,7 @@ pub fn select(s: &mut Session, p: &Value) -> Result<Value> {s.state.edit_points = vec![ep];}s.state.selection.clear();+ s.state.gap_selection = None;reset_shift(s);Ok(json!({"editPoints": s.state.edit_points}))}@@ -155,6 +156,7 @@ pub fn select_nearest(s: &mut Session, p: &Value) -> Result<Value> {}s.state.edit_points = points;s.state.selection.clear();+ s.state.gap_selection = None;reset_shift(s);Ok(json!({"editPoints": s.state.edit_points}))}