Skip to content

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

timeline, monitors: drag the current-time timecode to scrub, click to type a time (#554)

ReReddoab9e4e6cebf1
diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rs
index 39034bfaa..42e8a6e60 100644
--- a/crates/ui-egui/src/panels/monitor.rs
+++ b/crates/ui-egui/src/panels/monitor.rs
@@ -305,8 +305,19 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
// ---- controls row: timecode | zoom | res | wrench | duration
let row1 = Rect::from_min_size(pos2(rect.min.x + 14.0, rect.max.y - controls_h + 2.0), vec2(rect.width() - 28.0, 26.0));
let tc = format_time(time, rate, drop_frame, TimeDisplay::Timecode, 48000);
- ui.painter().text(pos2(row1.min.x, row1.center().y), Align2::LEFT_CENTER, &tc, Tokens::timecode(), t.timecode);
- app.auto.add(&format!("{prefix}.timecode"), Rect::from_min_size(row1.min, vec2(110.0, row1.height())), &tc);
+ let tc_rect = Rect::from_min_size(row1.min, vec2(110.0, row1.height()));
+ let min = if which == Which::Program { Tick::ZERO } else { origin };
+ match crate::widgets::timecode_field(ui, egui::Id::new((prefix, "timecode")), tc_rect, &tc, time, min, rate, drop_frame, t.timecode) {
+ Some(Ok(to)) => {
+ let cmd = if which == Which::Program { "playhead.set" } else { "source.setPlayhead" };
+ if let Err(e) = app.session.execute(cmd, json!({"time": to.0})) {
+ app.ui.status = e.to_string();
+ }
+ }
+ Some(Err(e)) => app.ui.status = e,
+ None => {}
+ }
+ app.auto.add(&format!("{prefix}.timecode"), tc_rect, &tc);
let dur_tc = format_time(mark_out.map(|o| o + rate.frame_duration()).unwrap_or(duration) - range_start, rate, drop_frame, TimeDisplay::Timecode, 48000);
ui.painter().text(pos2(row1.max.x, row1.center().y), Align2::RIGHT_CENTER, &dur_tc, Tokens::timecode(), t.text_dim);
// zoom + resolution dropdowns centred-ish
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 811a75eea..8e186ac1d 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -1108,7 +1108,16 @@ fn draw_top(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, seq: &Sequenc
// current timecode: Premiere's big blue timecode
let tc = format_time(app.session.playhead(), rate, seq.settings.drop_frame, TimeDisplay::Timecode, seq.settings.sample_rate as i64);
let tc_rect = Rect::from_min_size(pos2(rect.min.x + 14.0, rect.min.y + 4.0), vec2(hw - 20.0, 20.0));
- p.text(pos2(tc_rect.min.x, tc_rect.center().y), Align2::LEFT_CENTER, &tc, Tokens::timecode(), t.timecode);
+ let tc_id = egui::Id::new(("timeline-tc", seq_id));
+ match crate::widgets::timecode_field(ui, tc_id, tc_rect, &tc, app.session.playhead(), Tick::ZERO, rate, seq.settings.drop_frame, t.timecode) {
+ Some(Ok(time)) => {
+ if let Err(e) = app.session.execute("playhead.set", json!({"time": time.0})) {
+ app.ui.status = e.to_string();
+ }
+ }
+ Some(Err(e)) => app.ui.status = e,
+ None => {}
+ }
app.auto.add("timeline.timecode", tc_rect, &tc);
// toolbar: 30 × 30 buttons, "on" = #4b4b4b fill
let mut x = rect.min.x + 12.0;
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 26b5fe677..d57b01ebe 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -1,6 +1,7 @@
//! Small custom widgets in Premiere's visual language.
use egui::{Align2, Color32, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
+use filmcraft_time::{FrameRate, Tick, parse_timecode};
use crate::icons::{self, Icon};
use crate::theme::Tokens;
@@ -58,11 +59,108 @@ pub fn hot_number(ui: &mut Ui, id: egui::Id, value: f64, speed: f64, range: (f64
(resp, out)
}
-/// A large blue timecode readout (monitors/timeline). Click to type a new time.
-pub fn timecode_label(ui: &mut Ui, rect: Rect, text: &str, size: f32, color: Color32, align: Align2) -> Response {
- let resp = ui.interact(rect, ui.id().with(("tc", rect.min.x as i32, rect.min.y as i32)), Sense::click_and_drag());
- ui.painter().text(align.pos_in_rect(&rect), align, text, Tokens::mono(size), color);
- resp
+/// A large blue timecode readout (monitors/timeline) that moves its playhead: drag horizontally to
+/// scrub (1 frame per point, Shift ×10), click to type a time (Enter or clicking away commits,
+/// Escape cancels). Returns the time to go to (never before `min`), or why a typed time is invalid.
+#[allow(clippy::too_many_arguments)]
+pub fn timecode_field(
+ ui: &mut Ui,
+ id: egui::Id,
+ rect: Rect,
+ text: &str,
+ time: Tick,
+ min: Tick,
+ rate: FrameRate,
+ drop_frame: bool,
+ color: Color32,
+) -> Option<Result<Tick, String>> {
+ let editing_id = id.with("editing");
+ let edit_id = id.with("edit");
+ let select_all_id = id.with("select-all");
+ if let Some(mut buf) = ui.data(|d| d.get_temp::<String>(editing_id)) {
+ // Left/Right on the whole selected value start from its last digit (egui would jump to the start)
+ let arrow = ui.input(|i| i.modifiers.is_none() && (i.key_pressed(egui::Key::ArrowLeft) || i.key_pressed(egui::Key::ArrowRight)));
+ if arrow && let Some(mut st) = egui::text_edit::TextEditState::load(ui.ctx(), edit_id) {
+ let len = buf.chars().count();
+ let all = [egui::text::CCursor::new(0), egui::text::CCursor::new(len)];
+ if len > 0 && st.cursor.char_range().is_some_and(|c| c.sorted_cursors() == all) {
+ st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(len))));
+ st.store(ui.ctx(), edit_id);
+ }
+ }
+ let r = ui.put(rect, egui::TextEdit::singleline(&mut buf).id(edit_id).font(Tokens::timecode()).desired_width(rect.width()));
+ if r.lost_focus() {
+ ui.data_mut(|d| d.remove::<String>(editing_id));
+ if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
+ return None;
+ }
+ let typed = parse_timecode(&buf, rate, drop_frame, rate.frame_at(time));
+ return Some(typed.map(|f| rate.tick_of(f).max(min)).map_err(|e| e.to_string()));
+ }
+ // select the whole value once the field has focus: egui collapses a selection to a caret
+ // in a field that does not have it yet
+ let selected_now = r.has_focus() && ui.data_mut(|d| d.remove_temp::<bool>(select_all_id)).is_some();
+ if selected_now {
+ let mut st = egui::text_edit::TextEditState::load(ui.ctx(), edit_id).unwrap_or_default();
+ st.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(buf.chars().count()))));
+ st.store(ui.ctx(), edit_id);
+ }
+ // the focus and the selection show on the next frame, which nothing else would trigger
+ if !r.has_focus() || selected_now {
+ ui.ctx().request_repaint();
+ }
+ ui.data_mut(|d| d.insert_temp(editing_id, buf));
+ // only until it has focus: `request_focus` resets the field's focus-lock filter, and the
+ // arrow keys would then move focus out of the field (committing it) instead of the caret
+ if !r.has_focus() {
+ r.request_focus();
+ }
+ return None;
+ }
+ let resp = ui.interact(rect, id, Sense::click_and_drag());
+ ui.painter().text(pos2(rect.min.x, rect.center().y), Align2::LEFT_CENTER, text, Tokens::timecode(), color);
+ // (frame at the press, frames dragged so far, where the pointer was pressed)
+ let drag_id = id.with("drag");
+ let mult = if ui.input(|i| i.modifiers.shift) { 10.0 } else { 1.0 };
+ if resp.drag_started() {
+ let origin = ui.input(|i| i.pointer.press_origin()).unwrap_or(rect.center());
+ let now = resp.interact_pointer_pos().unwrap_or(origin);
+ // egui reports a drag only past its click threshold: count the movement before that,
+ // less this frame's delta, which the `dragged` branch below adds
+ let early = f64::from(now.x - origin.x - resp.drag_delta().x) * mult;
+ ui.data_mut(|d| d.insert_temp(drag_id, (rate.frame_at(time), early, origin)));
+ }
+ let mut out = None;
+ if resp.dragged() {
+ // hidden while scrubbing, put back where it was pressed on release (below)
+ ui.ctx().set_cursor_icon(egui::CursorIcon::None);
+ if let Some((start, acc, origin)) = ui.data(|d| d.get_temp::<(i64, f64, egui::Pos2)>(drag_id)) {
+ // held at `min` so dragging back moves again at once
+ let acc = (acc + f64::from(resp.drag_delta().x) * mult).max((rate.frame_at(min) - start) as f64);
+ ui.data_mut(|d| d.insert_temp(drag_id, (start, acc, origin)));
+ let target = rate.tick_of(start.saturating_add(acc.trunc() as i64)).max(min);
+ if target != time {
+ out = Some(Ok(target));
+ }
+ }
+ } else if resp.hovered() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
+ }
+ if resp.drag_stopped()
+ && let Some((_, _, origin)) = ui.data_mut(|d| d.remove_temp::<(i64, f64, egui::Pos2)>(drag_id))
+ {
+ ui.ctx().send_viewport_cmd(egui::ViewportCommand::CursorPosition(origin));
+ }
+ if resp.clicked() {
+ // the field asks for focus itself next frame: asking now, before it exists, leaves the
+ // accessibility tree focused on a node it does not have
+ ui.data_mut(|d| {
+ d.insert_temp(editing_id, text.to_string());
+ d.insert_temp(select_all_id, true);
+ });
+ ui.ctx().request_repaint();
+ }
+ out
}
/// A twirl-down section header (Effect Controls / Lumetri style). Returns open state.
diff --git a/crates/ui-egui/tests/timecode_ui.rs b/crates/ui-egui/tests/timecode_ui.rs
new file mode 100644
index 000000000..badc35365
--- /dev/null
+++ b/crates/ui-egui/tests/timecode_ui.rs
@@ -0,0 +1,176 @@
+//! The Timeline's and monitors' current-time timecodes, driven headless through the control
+//! channel: dragging scrubs the playhead (1 frame per point, never before the start), a click
+//! turns the timecode into a field where Enter goes to the typed time and Escape cancels.
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_time::{FrameRate, parse_timecode};
+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 demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ session.execute("source.open", json!({"item": 5})).expect("source clip");
+ 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_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 {
+ 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(r) = reply.try_recv() {
+ assert_eq!(r["ok"], true, "{method} {params}: {r}");
+ self.frames(2);
+ return r["result"].clone();
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+ /// Centre of an element, from `ui.elements`.
+ fn centre(&mut self, id: &str) -> (f64, f64) {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("no element {id}")).clone();
+ let r: Vec<f64> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
+ }
+ fn label(&mut self, id: &str) -> String {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ v.as_array().unwrap().iter().find(|e| e["id"] == id).and_then(|e| e["label"].as_str()).unwrap_or_default().to_string()
+ }
+ fn drag_by(&mut self, id: &str, dx: f64) {
+ let (x, y) = self.centre(id);
+ self.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + dx, "y": y}}));
+ }
+ fn type_into(&mut self, id: &str, text: &str, key: &str) {
+ self.ok("ui.click", json!({"id": id}));
+ self.ok("ui.type", json!({"text": text}));
+ self.ok("ui.key", json!({"key": key}));
+ }
+ fn frame(&self) -> i64 {
+ let s = &self.harness.state().session;
+ s.sequence_rate().frame_at(s.playhead())
+ }
+ fn source_rate(&self) -> FrameRate {
+ filmcraft_engine::clip_ops::source_view(&self.harness.state().session, filmcraft_project::ItemId(5)).unwrap().rate
+ }
+ fn source_frame(&self) -> i64 {
+ self.source_rate().frame_at(self.harness.state().session.state.source_playhead)
+ }
+ fn set_frame(&mut self, f: i64) {
+ self.harness.state_mut().session.execute("playhead.set", json!({"frame": f})).unwrap();
+ self.frames(2);
+ }
+}
+
+#[test]
+fn dragging_the_timeline_timecode_scrubs_and_stops_at_the_start() {
+ let mut d = Driver::demo();
+ let before = d.harness.state().session.project.to_json();
+ d.set_frame(30);
+ d.drag_by("timeline.timecode", 20.0);
+ assert_eq!(d.frame(), 50, "1 frame per point");
+ d.drag_by("timeline.timecode", -12.0);
+ assert_eq!(d.frame(), 38);
+ d.drag_by("timeline.timecode", -300.0);
+ assert_eq!(d.frame(), 0, "never before the start");
+ assert_eq!(d.harness.state().session.project.to_json(), before, "scrubbing does not edit the project");
+}
+
+#[test]
+fn typing_in_the_timeline_timecode_goes_to_that_time() {
+ let mut d = Driver::demo();
+ d.set_frame(30);
+ d.type_into("timeline.timecode", "1000", "Enter");
+ let (rate, df) = {
+ let s = &d.harness.state().session;
+ (s.sequence_rate(), s.active_sequence().unwrap().settings.drop_frame)
+ };
+ assert_eq!(d.frame(), parse_timecode("1000", rate, df, 0).unwrap(), "the whole value was selected and replaced");
+ d.type_into("timeline.timecode", "+15", "Enter");
+ assert_eq!(d.frame(), parse_timecode("1000", rate, df, 0).unwrap() + 15, "relative to the current time");
+}
+
+#[test]
+fn arrow_keys_move_the_caret_instead_of_committing() {
+ let mut d = Driver::demo();
+ let (rate, df) = {
+ let s = &d.harness.state().session;
+ (s.sequence_rate(), s.active_sequence().unwrap().settings.drop_frame)
+ };
+ // Left on the selected value lands before its last digit: Delete removes that digit
+ d.set_frame(30);
+ let tc = d.label("timeline.timecode");
+ d.ok("ui.click", json!({"id": "timeline.timecode"}));
+ d.ok("ui.key", json!({"key": "Left"}));
+ assert_eq!(d.frame(), 30, "Left neither commits nor steps the playhead");
+ d.ok("ui.key", json!({"key": "Delete"}));
+ d.ok("ui.key", json!({"key": "Enter"}));
+ let mut expect = tc.clone();
+ expect.pop();
+ assert_eq!(d.frame(), parse_timecode(&expect, rate, df, 0).unwrap(), "{tc} without its last digit");
+ // Right goes to the end: Backspace removes the last digit, then a new one is typed
+ d.set_frame(30);
+ d.ok("ui.click", json!({"id": "timeline.timecode"}));
+ d.ok("ui.key", json!({"key": "Right"}));
+ d.ok("ui.key", json!({"key": "Backspace"}));
+ d.ok("ui.type", json!({"text": "9"}));
+ d.ok("ui.key", json!({"key": "Enter"}));
+ let mut expect = tc.clone();
+ expect.pop();
+ expect.push('9');
+ assert_eq!(d.frame(), parse_timecode(&expect, rate, df, 0).unwrap(), "{tc} with its last digit replaced");
+}
+
+#[test]
+fn escape_cancels_and_a_bad_time_is_reported_without_moving() {
+ let mut d = Driver::demo();
+ d.set_frame(30);
+ d.type_into("timeline.timecode", "1000", "Escape");
+ assert_eq!(d.frame(), 30, "Escape cancels");
+ d.type_into("timeline.timecode", "abc", "Enter");
+ assert_eq!(d.frame(), 30);
+ assert!(d.harness.state().ui.status.contains("timecode"), "status: {}", d.harness.state().ui.status);
+ // after a cancel or an error the readout scrubs again
+ d.drag_by("timeline.timecode", 10.0);
+ assert_eq!(d.frame(), 40);
+}
+
+#[test]
+fn the_program_and_source_timecodes_move_their_own_playheads() {
+ let mut d = Driver::demo();
+ d.set_frame(30);
+ d.drag_by("program.timecode", 20.0);
+ assert_eq!(d.frame(), 50);
+ let program = d.harness.state().session.playhead();
+ let source = d.source_frame();
+ d.drag_by("source.timecode", 20.0);
+ assert_eq!(d.source_frame(), source + 20);
+ assert_eq!(d.harness.state().session.playhead(), program, "the Source timecode leaves the sequence alone");
+ d.type_into("source.timecode", "100", "Enter");
+ assert_eq!(d.source_frame(), parse_timecode("100", d.source_rate(), false, 0).unwrap(), "1 s at the clip's own rate");
+ assert_eq!(d.harness.state().session.playhead(), program);
+}