Skip to content

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

Timeline: the Razor tool cuts captions (#3039)

Tex Jernigana5c2a73cbd3c
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 33c243762..5e9c666b8 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -1775,7 +1775,7 @@ fn vertical_scrollbar(ui: &mut egui::Ui, bar: Rect, value: &mut f32, max: f32, i
}
/// Snap `t` to nearby candidates (edits, playhead, markers, in/out). Returns snapped tick.
-fn snap(app: &mut FilmcraftApp, seq: &Sequence, layout: &Layout, t: Tick, exclude: &[ClipId]) -> Tick {
+pub(super) fn snap(app: &mut FilmcraftApp, seq: &Sequence, layout: &Layout, t: Tick, exclude: &[ClipId]) -> Tick {
snap_to(app, seq, layout, t, exclude, true)
}
diff --git a/crates/ui-egui/src/panels/timeline_captions.rs b/crates/ui-egui/src/panels/timeline_captions.rs
index 6b93456ae..75cf0e71a 100644
--- a/crates/ui-egui/src/panels/timeline_captions.rs
+++ b/crates/ui-egui/src/panels/timeline_captions.rs
@@ -1,7 +1,8 @@
//! Caption track rows of the Timeline: drawn in their own area above the video tracks (Premiere's
//! layout). Each row has a header (C1…, name, format, output eye, lock) and caption blocks in a
//! distinct colour showing their text. Click selects (Cmd/Shift adds), dragging the body moves,
-//! dragging an edge trims, double-click opens the Text panel's Captions tab. Every gesture ends in
+//! dragging an edge trims, the Razor tool splits (Shift: every caption track), double-click opens
+//! the Text panel's Captions tab. Every gesture ends in
//! one `captions.*` command; every element registers an automation id (`timeline.caption.*`,
//! `timeline.captionTrack.C1.*`).
@@ -14,6 +15,7 @@ use super::timeline::Layout;
use crate::FilmcraftApp;
use crate::dock::PanelKind;
use crate::icons::Icon;
+use crate::state::Tool;
use crate::theme::Tokens;
/// Height of one caption track row.
@@ -182,12 +184,55 @@ pub fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, area:
if r.width() <= 0.0 {
continue;
}
- interact_block(app, ui, tr, c, r, rate, &mut actions);
+ if app.ui.tool == Tool::Razor {
+ razor_block(app, ui, seq, layout, tr, c, r, row, &mut actions);
+ } else {
+ interact_block(app, ui, tr, c, r, rate, &mut actions);
+ }
}
}
run(app, ui, actions);
}
+/// The Razor tool over a caption: a white line where it would cut, and a click splits the caption
+/// there (Shift: every caption on an unlocked caption track at that time), as it cuts clips.
+#[allow(clippy::too_many_arguments)]
+fn razor_block(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ seq: &Sequence,
+ layout: &Layout,
+ tr: &CaptionTrack,
+ c: &filmcraft_project::Caption,
+ r: Rect,
+ row: Rect,
+ actions: &mut Vec<(String, Value)>,
+) {
+ let ctx = ui.ctx().clone();
+ let resp = ui.interact(r, egui::Id::new(("caption-block", c.id.0)), Sense::click_and_drag());
+ if tr.locked {
+ return;
+ }
+ let rate = seq.settings.frame_rate;
+ let at = |app: &mut FilmcraftApp, x: f32| super::timeline::snap(app, seq, layout, rate.snap_nearest(layout.tick_at(x)), &[]);
+ if let Some(p) = resp.hover_pos() {
+ ctx.set_cursor_icon(CursorIcon::Crosshair);
+ let x = layout.x_of(at(app, p.x));
+ ui.painter().with_clip_rect(layout.content).line_segment([pos2(x, row.min.y), pos2(x, row.max.y)], Stroke::new(1.0, Color32::WHITE));
+ }
+ // a press that starts a drag cuts as well, as on clips
+ if (resp.clicked() || resp.drag_started())
+ && let Some(p) = ctx.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
+ {
+ let t = at(app, p.x);
+ if ctx.input(|i| i.modifiers.shift) {
+ actions.push(("captions.split".into(), json!({"time": t.0})));
+ } else if c.start < t && t < c.end() {
+ actions.push(("captions.split".into(), json!({"caption": c.id.0, "time": t.0})));
+ }
+ }
+}
+
fn interact_block(
app: &mut FilmcraftApp,
ui: &mut egui::Ui,
diff --git a/crates/ui-egui/tests/it/caption_razor_ui.rs b/crates/ui-egui/tests/it/caption_razor_ui.rs
new file mode 100644
index 000000000..114c68d25
--- /dev/null
+++ b/crates/ui-egui/tests/it/caption_razor_ui.rs
@@ -0,0 +1,116 @@
+//! The Razor tool (C) on a caption in the Timeline cuts it, as it cuts clips. The real
+//! `FilmcraftApp` under `egui_kittest` with the demo project.
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui::{Modifiers, Pos2, Rect, pos2};
+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 {
+ /// The demo project with snapping off, so drags land where the pointer goes; frames 1/60 s
+ /// apart, as on a display.
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ session.execute("sequence.snap", json!({"on": false})).expect("snapping off");
+ 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_step_dt(1.0 / 60.0).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx };
+ d.frames(4);
+ d.ok("ui.elements", json!({"prefix": "timeline.clip."}));
+ 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).expect("control channel");
+ 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) -> Option<Rect> {
+ self.frames(2);
+ let els = self.ok("ui.elements", json!({"prefix": id}));
+ let el = els.as_array()?.iter().find(|e| e["id"] == id)?.clone();
+ let r: Vec<f32> = el["rect"].as_array()?.iter().filter_map(|v| v.as_f64().map(|v| v as f32)).collect();
+ Some(Rect::from_min_size(pos2(*r.first()?, *r.get(1)?), egui::vec2(*r.get(2)?, *r.get(3)?)))
+ }
+
+ /// (start, end, text) of every caption on C1.
+ fn captions(&mut self) -> Vec<(i64, i64, String)> {
+ let r = self.exec("captions.list", json!({}));
+ r["tracks"][0]["captions"]
+ .as_array()
+ .expect("captions")
+ .iter()
+ .map(|c| (c["start"].as_i64().expect("start"), c["end"].as_i64().expect("end"), c["text"].as_str().expect("text").to_string()))
+ .collect()
+ }
+
+ /// Press at `from`, move to `to` over `steps` frames with `mods` held, release.
+ fn drag_with(&mut self, from: Pos2, to: Pos2, steps: usize, mods: Modifiers) {
+ let push = |d: &mut Self, e: egui::Event| d.harness.input_mut().events.push(e);
+ push(self, egui::Event::ModifiersChanged(mods));
+ push(self, egui::Event::PointerMoved(from));
+ self.frames(1);
+ push(self, egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: mods });
+ self.frames(1);
+ for i in 1..=steps {
+ push(self, egui::Event::PointerMoved(from + (to - from) * (i as f32 / steps as f32)));
+ self.frames(1);
+ }
+ push(self, egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: mods });
+ self.frames(2);
+ push(self, egui::Event::ModifiersChanged(Modifiers::NONE));
+ self.frames(1);
+ }
+
+ fn click(&mut self, at: Pos2) {
+ self.drag_with(at, at, 0, Modifiers::NONE);
+ }
+}
+
+/// With the Razor tool (C), a click on a caption in the Timeline cuts it in two there. The
+/// caption blocks took the click for selecting and moving whatever the tool, so it did nothing.
+#[test]
+fn razor_tool_splits_a_caption() {
+ let mut d = Driver::demo();
+ let id = d.exec("captions.add", json!({"seconds": 2.0, "durationSeconds": 4.0, "text": "cut me"}))["caption"].as_u64().expect("id");
+ d.ok("ui.set", json!({"tool": "razor"}));
+ let r = d.rect(&format!("timeline.caption.{id}")).expect("caption block");
+ d.click(r.center());
+ let caps = d.captions();
+ assert_eq!(caps.len(), 2, "the caption was cut: {caps:?}");
+ assert_eq!(caps[0].1, caps[1].0, "the halves meet at the cut");
+ assert!(caps.iter().all(|c| c.2 == "cut me"));
+}
diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs
index c5a3437d2..d585570c7 100644
--- a/crates/ui-egui/tests/it/main.rs
+++ b/crates/ui-egui/tests/it/main.rs
@@ -1,6 +1,7 @@
mod audio51_ui;
mod audio_fx_editor_ui;
mod caption_properties_ui;
+mod caption_razor_ui;
mod captions_font_ui;
mod chrome_ui;
mod clip_audio_ui;
diff --git a/docs/captions.md b/docs/captions.md
index 871427d48..d54cc4dac 100644
--- a/docs/captions.md
+++ b/docs/captions.md
@@ -40,7 +40,7 @@ Details of each format and the SCC encoder are in [`crates/captions/README.md`](
| `captions.add` | Sequence ▸ Captions ▸ Add Caption at Playhead (⌥⌘C) | `track`, `text`, `time`, `durationSeconds` (3) |
| `captions.next` / `captions.previous` | Sequence ▸ Captions ▸ Go to Next/Previous Caption Segment (⌥⌘↓/↑) | |
| `captions.showAll` / `captions.hideAll` | Sequence ▸ Captions | |
-| `captions.split` | Text panel ✂ | `caption`, `time` (default: every caption under the playhead) |
+| `captions.split` | Text panel ✂; Razor tool on a caption (⇧: every caption track) | `caption`, `time` (default: every caption under the playhead) |
| `captions.merge` | Text panel | `captions` (consecutive, one track) |
| `captions.setText` | Text panel text field | `caption`, `text`, `speaker` |
| `captions.setTimes` | Text panel in/out fields | `caption`, `start…`/`end…` (`Time` ticks, `Frame`, `Seconds`, `Timecode`) |
@@ -62,8 +62,8 @@ also splits captions.
## Timeline and Text panel
- Caption rows: header with `C1…` badge, lock, output eye, name and format; caption blocks in
- violet showing their text (Arabic and Hebrew in reading order from the block's right edge). Click selects (⌘/⇧ adds), drag moves, edge drag trims, double-click
- opens the Text panel. Automation ids: `timeline.caption.<id>`,
+ violet showing their text (Arabic and Hebrew in reading order from the block's right edge). Click selects (⌘/⇧ adds), drag moves, edge drag trims, the Razor tool cuts,
+ double-click opens the Text panel. Automation ids: `timeline.caption.<id>`,
`timeline.captionTrack.C1[.locked|.enabled]`.
- **Text panel ▸ Captions**: search, track picker (also creates tracks of each format), add /
split / merge / delete / export buttons, the list of segments with editable in/out timecodes