FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#219: right-clicking a cut opens the edit point menu
MrCloudy2fcdcc07359c1
diff --git a/crates/edit/src/through.rs b/crates/edit/src/through.rsindex 0905149a7..547ae7852 100644--- a/crates/edit/src/through.rs+++ b/crates/edit/src/through.rs@@ -59,6 +59,11 @@ pub fn through_edits(seq: &Sequence) -> Vec<ThroughEdit> {/// piece is listed. The left piece absorbs the right one (keeping its own effects and attributes);/// a transition sitting on the cut is removed. Returns the number of edits joined.pub fn join_through_edits(seq: &mut Sequence, only: &[ClipId]) -> usize {+ join_through_edits_where(seq, |a, b| only.is_empty() || only.contains(&a) || only.contains(&b))+}++/// Join the through edits on unlocked tracks whose (left, right) pieces `wanted` accepts.+pub fn join_through_edits_where(seq: &mut Sequence, wanted: impl Fn(ClipId, ClipId) -> bool) -> usize {let mut n = 0;for tr in seq.all_tracks_mut() {if tr.locked {@@ -67,8 +72,7 @@ pub fn join_through_edits(seq: &mut Sequence, only: &[ClipId]) -> usize {let mut i = 0;while i + 1 < tr.items.len() {let (a, b) = (&tr.items[i], &tr.items[i + 1]);- let wanted = only.is_empty() || only.contains(&a.id) || only.contains(&b.id);- if !(wanted && is_through_edit(a, b)) {+ if !(wanted(a.id, b.id) && is_through_edit(a, b)) {i += 1;continue;}diff --git a/crates/engine/src/sequence_tools.rs b/crates/engine/src/sequence_tools.rsindex 5183c10e4..e66c5001d 100644--- a/crates/engine/src/sequence_tools.rs+++ b/crates/engine/src/sequence_tools.rs@@ -8,7 +8,7 @@//! | `sequence.goToNextGapInTrack` / `sequence.goToPrevGapInTrack` | Sequence ▸ Go to Gap ▸ Next / Previous in Track | |//! | `sequence.selectionFollowsPlayhead` | Sequence ▸ Selection Follows Playhead | |//! | `sequence.showThroughEdits` | Sequence ▸ Show Through Edits | |-//! | `sequence.joinThroughEdits` | (clip context menu) Join Through Edits | |+//! | `sequence.joinThroughEdits` | (clip and edit point context menus) Join Through Edits | |//! | `sequence.throughEdits` | query: the through edits of the active sequence | |//! | `sequence.makeSubsequence` | Sequence ▸ Make Subsequence | Shift+U |//! | `sequence.deleteTracks` | Sequence ▸ Delete Tracks… | |@@ -103,7 +103,15 @@ fn groups() -> Vec<(&'static str, Vec<CommandSpec>)> {s.state.show_through_edits = bool_p(p, "on").unwrap_or(!s.state.show_through_edits);Ok(json!({"showThroughEdits": s.state.show_through_edits}))}),- spec("sequence.joinThroughEdits", "Join Through Edits", &[], None, r#"{"clips":[id]?,"all":bool?}"#, has_seq, join_through_edits),+ spec(+ "sequence.joinThroughEdits",+ "Join Through Edits",+ &[],+ None,+ r#"{"clips":[id]?,"cut":[id,id]?,"all":bool?}"#,+ has_seq,+ join_through_edits,+ ),query("sequence.throughEdits", "List Through Edits", "{}", |s, _| {let q = s.active_sequence().ok_or(EngineError::NoSequence)?;Ok(Value::Array(@@ -326,6 +334,9 @@ fn go_to_gap(s: &mut Session, p: &Value, next: bool, in_track: bool) -> Result<V// ---------- through edits ----------fn join_through_edits(s: &mut Session, p: &Value) -> Result<Value> {+ if let Some(cut) = p.get("cut") {+ return join_through_edit_at(s, cut);+ }let all = bool_p(p, "all").unwrap_or(false) || (p.get("clips").is_none() && p.get("clip").is_none() && s.state.selection.is_empty());let only = if all { Vec::new() } else { with_links(s, &clips_p(s, p)) };let q = s.active_sequence().ok_or(EngineError::NoSequence)?;@@ -343,6 +354,26 @@ fn join_through_edits(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"joined": n}))}+/// `sequence.joinThroughEdits {cut: [left, right]}`: join just that one cut (the edit point menu,+/// #219), with the cuts between the same pieces' linked partners when linked selection is on.+fn join_through_edit_at(s: &mut Session, cut: &Value) -> Result<Value> {+ let ids: Vec<ClipId> = cut.as_array().map(|a| a.iter().filter_map(|v| v.as_u64().map(ClipId)).collect()).unwrap_or_default();+ let [left, right] = ids[..] else {+ return Err(EngineError::Other("sequence.joinThroughEdits: `cut` needs two clip ids, [left, right]".into()));+ };+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;+ if !edit::through::through_edits(q).iter().any(|e| e.left == left && e.right == right) {+ return Err(EngineError::Other("that cut is not a through edit".into()));+ }+ let (lefts, rights) = (with_links(s, &[left]), with_links(s, &[right]));+ let n = s.edit_sequence("Join Through Edits", |q, _, st| {+ let n = edit::through::join_through_edits_where(q, |a, b| lefts.contains(&a) && rights.contains(&b));+ st.selection.retain(|c| q.find_item(*c).is_some());+ Ok(n)+ })?;+ Ok(json!({"joined": n}))+}+// ---------- subsequence ----------/// Sequence ▸ Make Subsequence: a new sequence (same settings and track layout) holding copies of thediff --git a/crates/engine/src/sequence_tools_tests.rs b/crates/engine/src/sequence_tools_tests.rsindex d9df881f4..a592abe72 100644--- a/crates/engine/src/sequence_tools_tests.rs+++ b/crates/engine/src/sequence_tools_tests.rs@@ -142,6 +142,41 @@ fn through_edits_show_and_join() {assert_eq!(s.execute("sequence.throughEdits", json!({})).unwrap().as_array().unwrap().len(), n - 2);}+/// `cut: [left, right]` (the timeline's edit point menu, #219) joins exactly that cut and its+/// linked partner, even when one of its pieces is also part of another through edit.+#[test]+fn join_one_through_edit_by_its_cut() {+ let mut s = demo();+ let v1 = s.active_sequence().unwrap().video_tracks[0].id.0;+ for frame in [30, 40] {+ s.execute("playhead.set", json!({"frame": frame})).unwrap();+ s.execute("sequence.addEditAllTracks", json!({})).unwrap();+ }+ let te = s.execute("sequence.throughEdits", json!({})).unwrap();+ let on_v1: Vec<&Value> = te.as_array().unwrap().iter().filter(|e| e["track"] == json!(v1)).collect();+ assert_eq!(on_v1.len(), 2);+ // the second cut: its left piece is also the right piece of the first one+ let (second, first) = (on_v1[1], on_v1[0]);+ assert_eq!(second["left"], first["right"]);+ let n = te.as_array().unwrap().len();+ let r = s.execute("sequence.joinThroughEdits", json!({"cut": [second["left"], second["right"]]})).unwrap();+ assert_eq!(r["joined"], json!(2), "V1 + linked A1");+ let te = s.execute("sequence.throughEdits", json!({})).unwrap();+ assert_eq!(te.as_array().unwrap().len(), n - 2);+ assert!(te.as_array().unwrap().iter().any(|e| e["left"] == first["left"] && e["right"] == first["right"]), "the first cut stays");+}++#[test]+fn join_by_cut_rejects_hostile_parameters() {+ let mut s = demo();+ let items = s.active_sequence().unwrap().video_tracks[0].items.clone();+ let before = s.active_sequence().unwrap().clone();+ for cut in [json!([]), json!([1]), json!([1, 2, 3]), json!("x"), json!([-1, 2]), json!([u64::MAX, 0]), json!([items[0].id.0, items[1].id.0])] {+ assert!(s.execute("sequence.joinThroughEdits", json!({"cut": cut})).is_err(), "{cut}");+ }+ assert_eq!(s.active_sequence().unwrap(), &before, "nothing changed");+}+#[test]fn make_subsequence_from_in_out_and_from_selection() {let mut s = demo();diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rsindex 0172243c0..e1f6b4508 100644--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@ -1620,6 +1620,84 @@ const CLIP_MENU: &[&[(&str, &str)]] = &[&[("Reveal in Project", "clip.revealInProject"), ("Join Through Edits", "sequence.joinThroughEdits")],];+/// The cut right-clicked on a track (#219): the clip ending there and the clip starting there,+/// either missing at the ends of a gap. Its menu offers the edit point's trim types, Apply Default+/// Transitions and Join Through Edits, like Premiere's edit point menu.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct EditPointTarget {+ left: Option<ClipId>,+ right: Option<ClipId>,+}++impl EditPointTarget {+ fn at(seq: &Sequence, track: TrackId, clip: ClipId, edge: filmcraft_edit::Edge) -> Option<Self> {+ let tr = seq.track(track)?;+ let it = tr.item(clip)?;+ Some(match edge {+ filmcraft_edit::Edge::Out => Self { left: Some(clip), right: tr.items.iter().find(|x| x.start == it.end()).map(|x| x.id) },+ filmcraft_edit::Edge::In => Self { left: tr.items.iter().find(|x| x.end() == it.start).map(|x| x.id), right: Some(clip) },+ })+ }+}++/// The edit point menu's trim types: label, id (`timeline.editPointMenu.<id>`), trim kind, and+/// which side of the cut it selects (the incoming clip's In or the outgoing clip's Out).+const EDIT_POINT_TYPES: &[(&str, &str, &str, filmcraft_edit::Edge)] = &[+ ("Ripple Trim In", "rippleIn", "ripple", filmcraft_edit::Edge::In),+ ("Ripple Trim Out", "rippleOut", "ripple", filmcraft_edit::Edge::Out),+ ("Roll Edit", "roll", "roll", filmcraft_edit::Edge::Out),+ ("Trim In", "trimIn", "trim", filmcraft_edit::Edge::In),+ ("Trim Out", "trimOut", "trim", filmcraft_edit::Edge::Out),+];++/// The edit point context menu (#219).+fn edit_point_menu(app: &mut FilmcraftApp, ctx: &egui::Context, ui: &mut egui::Ui, seq: &Sequence, target: EditPointTarget) {+ let selected = app.session.state.edit_points.first().copied();+ for &(label, id, kind, edge) in EDIT_POINT_TYPES {+ let clip = match edge {+ filmcraft_edit::Edge::In => target.right,+ filmcraft_edit::Edge::Out => target.left,+ };+ // a roll needs a clip on both sides of the cut+ let clip = clip.filter(|_| kind != "roll" || (target.left.is_some() && target.right.is_some()));+ let out = edge == filmcraft_edit::Edge::Out;+ let current = selected.is_some_and(|ep| Some(ep.clip) == clip && ep.out == out && serde_json::to_value(ep.kind).ok() == Some(json!(kind)));+ let text = if current { format!("✓ {label}") } else { label.to_string() };+ let r = ui.add_enabled(clip.is_some(), egui::Button::new(text));+ app.auto.add(&format!("timeline.editPointMenu.{id}"), r.rect, label);+ if r.clicked()+ && let Some(c) = clip+ {+ let e = if out { "out" } else { "in" };+ if let Err(e) = app.session.execute("trim.selectEditPoint", json!({"clip": c.0, "edge": e, "kind": kind})) {+ app.ui.status = e.to_string();+ }+ ui.close();+ }+ }+ ui.separator();+ let r = ui.add_enabled(app.session.is_enabled("trim.applyDefaultTransition"), egui::Button::new("Apply Default Transitions"));+ app.auto.add("timeline.editPointMenu.applyDefaultTransitions", r.rect, "Apply Default Transitions");+ if r.clicked() {+ if let Err(e) = crate::menus::invoke(app, ctx, "trim.applyDefaultTransition", json!({})) {+ app.ui.status = e;+ }+ ui.close();+ }+ // only this cut (and its linked partners), and only when it is a through edit+ let through = filmcraft_edit::through::through_edits(seq).iter().any(|e| Some(e.left) == target.left && Some(e.right) == target.right);+ let r = ui.add_enabled(through, egui::Button::new("Join Through Edits"));+ app.auto.add("timeline.editPointMenu.joinThroughEdits", r.rect, "Join Through Edits");+ if r.clicked()+ && let (Some(left), Some(right)) = (target.left, target.right)+ {+ if let Err(e) = app.session.execute("sequence.joinThroughEdits", json!({"cut": [left.0, right.0]})) {+ app.ui.status = e.to_string();+ }+ ui.close();+ }+}+/// The clip menu's Multi-Camera submenu: Enable, Flatten, and the cameras of the selected nested/// sequence clips (greyed out when none of the selected clips is a nested sequence).fn multicam_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, picked: &[&TrackItem]) {@@ -2065,16 +2143,39 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &}}- // ---- context menu on clips (right-clicking an unselected clip selects it first)+ // ---- context menu on clips (right-clicking an unselected clip selects it first); on a clip's+ // edge, the edit point menu instead (right-clicking an unselected edit point selects it first)+ let edit_point_menu_id = egui::Id::new("timeline.editPointMenu.target");if resp.secondary_clicked()&& let Some(p) = resp.interact_pointer_pos()- && let Hit::Clip { clip, .. } = hit(seq, layout, p)- && !app.session.state.selection.contains(&clip)+ && let Hit::Clip { clip, edge, track } = hit(seq, layout, p){- let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));+ let target = edge.and_then(|e| EditPointTarget::at(seq, track, clip, e).map(|t| (t, e)));+ ctx.data_mut(|d| d.insert_temp(edit_point_menu_id, target.map(|(t, _)| t)));+ if let Some((t, e)) = target {+ let on_it = app.session.state.edit_points.iter().any(|ep| (ep.out && Some(ep.clip) == t.left) || (!ep.out && Some(ep.clip) == t.right));+ if !on_it {+ let kind = match tool {+ Tool::Rolling => "roll",+ Tool::Ripple => "ripple",+ _ => {+ let (dist, neighbour) = edge_geometry(seq, layout, track, clip, e, p.x);+ selection_trim_kind(app.session.prefs.trim.selection_tool_roll_ripple, false, false, dist, neighbour)+ }+ };+ let edge = if e == filmcraft_edit::Edge::In { "in" } else { "out" };+ let _ = app.session.execute("trim.selectEditPoint", json!({"clip": clip.0, "edge": edge, "kind": kind}));+ }+ } else if !app.session.state.selection.contains(&clip) {+ let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));+ }}resp.context_menu(|ui| {ui.set_min_width(220.0);+ if let Some(target) = ctx.data(|d| d.get_temp::<Option<EditPointTarget>>(edit_point_menu_id)).flatten() {+ edit_point_menu(app, &ctx, ui, seq, target);+ return;+ }let sel = app.session.state.selection.clone();let picked: Vec<&filmcraft_project::TrackItem> = sel.iter().filter_map(|c| seq.find_item(*c).map(|(_, it)| it)).collect();let all_enabled = !picked.is_empty() && picked.iter().all(|it| it.enabled);diff --git a/crates/ui-egui/tests/edit_point_menu_ui.rs b/crates/ui-egui/tests/edit_point_menu_ui.rsnew file mode 100644index 000000000..d4e259b50--- /dev/null+++ b/crates/ui-egui/tests/edit_point_menu_ui.rs@@ -0,0 +1,160 @@+//! Headless UI test of the timeline's edit point menu (#219): right-clicking a cut between two+//! clips offers its trim types, Apply Default Transitions and Join Through Edits, as in Premiere;+//! right-clicking the body of a clip still opens the clip menu.++use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_engine::project::{ClipId, Sequence};+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 new() -> Self {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ let (tx, rx) = channel();+ let app = FilmcraftApp::new(s).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 {+ // the control channel's clicks and keys enter through the input hook+ 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 click(&mut self, id: &str) {+ self.ok("ui.click", json!({"id": id}));+ self.frames(3);+ }++ fn has(&mut self, id: &str) -> bool {+ let v = self.ok("ui.elements", json!({"prefix": id}));+ v.as_array().unwrap().iter().any(|e| e["id"] == json!(id))+ }++ fn seq(&mut self) -> Sequence {+ self.harness.state_mut().session.active_sequence().unwrap().clone()+ }++ /// Right-click `clip` at `fx` of its width (0.0 = its In edge, 0.5 = its middle).+ fn right_click(&mut self, clip: ClipId, fx: f64) {+ self.ok("ui.click", json!({"id": format!("timeline.clip.{}", clip.0), "fx": fx, "button": "right"}));+ self.frames(3);+ }++ /// Two different clips on V1 that touch, with no transition on the cut (a cut, not a through+ /// edit): (outgoing, incoming).+ fn cut_on_v1(&mut self) -> (ClipId, ClipId) {+ let seq = self.seq();+ let tr = &seq.video_tracks[0];+ let bare = |a: ClipId, b: ClipId| !tr.transitions.iter().any(|t| t.from == Some(a) || t.to == Some(b));+ tr.items+ .windows(2)+ .find(|w| w[0].end() == w[1].start && w[0].item != w[1].item && bare(w[0].id, w[1].id))+ .map(|w| (w[0].id, w[1].id))+ .expect("two touching clips on V1")+ }+}++#[test]+fn right_clicking_a_cut_opens_the_edit_point_menu() {+ let mut d = Driver::new();+ let (a, b) = d.cut_on_v1();+ d.right_click(b, 0.0);+ for id in ["rippleIn", "rippleOut", "roll", "trimIn", "trimOut", "applyDefaultTransitions", "joinThroughEdits"] {+ assert!(d.has(&format!("timeline.editPointMenu.{id}")), "{id}");+ }+ 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!((eps[0].clip == a && eps[0].out) || (eps[0].clip == b && !eps[0].out), "{eps:?}");++ // 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[0].clip, ep[0].out, serde_json::to_value(ep[0].kind).unwrap()), (b, false, json!("trim")));++ // Apply Default Transitions puts a transition on the cut+ d.right_click(b, 0.0);+ let before = d.seq().video_tracks[0].transitions.len();+ d.click("timeline.editPointMenu.applyDefaultTransitions");+ assert_eq!(d.seq().video_tracks[0].transitions.len(), before + 1, "a transition was added");+}++#[test]+fn the_body_of_a_clip_still_opens_the_clip_menu() {+ let mut d = Driver::new();+ let (_, b) = d.cut_on_v1();+ d.right_click(b, 0.0);+ d.ok("ui.key", json!({"key": "Escape"}));+ d.frames(3);+ d.right_click(b, 0.5);+ assert!(d.has("timeline.clipMenu.edit.cut"), "the clip menu");+ assert!(!d.has("timeline.editPointMenu.rippleIn"), "not the edit point menu");+ assert!(d.harness.state_mut().session.state.selection.contains(&b), "the clip is selected");+}++#[test]+fn join_through_edits_joins_only_the_right_clicked_cut() {+ let mut d = Driver::new();+ let first = d.seq().video_tracks[0].items[0].clone();+ // two through edits inside the first clip on V1+ let secs = |t: i64| t as f64 / filmcraft_time::TICKS_PER_SECOND as f64;+ let (start, len) = (secs(first.start.0), secs(first.duration.0));+ for f in [0.3, 0.6] {+ d.exec("playhead.set", json!({"seconds": start + len * f}));+ assert_eq!(d.exec("timeline.razor", json!({"track": "V1"}))["cuts"], json!(1));+ }+ d.frames(2);+ let n = d.seq().video_tracks[0].items.len();+ let pieces: Vec<ClipId> = d.seq().video_tracks[0].items.iter().take(3).map(|i| i.id).collect();+ // the cut between the 2nd and 3rd pieces+ d.right_click(pieces[2], 0.0);+ d.click("timeline.editPointMenu.joinThroughEdits");+ let items = d.seq().video_tracks[0].items.clone();+ assert_eq!(items.len(), n - 1, "one cut joined");+ assert_eq!((items[0].id, items[1].id), (pieces[0], pieces[1]), "the other through edit is still there");++ // a cut between two different clips is not a through edit+ let (_, b) = d.cut_on_v1();+ d.right_click(b, 0.0);+ assert!(d.has("timeline.editPointMenu.joinThroughEdits"));+ let before = d.seq().video_tracks[0].items.len();+ d.click("timeline.editPointMenu.joinThroughEdits");+ assert_eq!(d.seq().video_tracks[0].items.len(), before, "disabled: nothing joined");+}