Skip to content

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

#201: Speed/Duration opens its dialog; dragging an effect parameter is one undo step

carlitosteso370aa66158610
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 96cfc22ac..acdccda75 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -2224,7 +2224,7 @@ fn build() -> Vec<CommandSpec> {
"Set Effect Parameter",
[],
None,
- r##"{"clip":id,"effect":"motion"|index,"param":str,"mask":n?,"value":num|[x,y]|"#rrggbb"|bool|path,"time":ticks?}"##,
+ r##"{"clip":id,"effect":"motion"|index,"param":str,"mask":n?,"value":num|[x,y]|"#rrggbb"|bool|path,"time":ticks?,"merge":bool?,"begin":bool?}"##,
has_seq,
|s, p| {
let c = clip_p(p, "clip").ok_or_else(|| bad("effects.setParam", "need `clip`"))?;
@@ -2234,7 +2234,12 @@ fn build() -> Vec<CommandSpec> {
let ph = s.playhead();
let tl = time_p(s, p, "").unwrap_or(ph);
let pq = p.clone();
- s.edit_sequence("Change Effect Parameter", |q, _, _| {
+ // `merge`: a drag of one parameter is one undo step (#201); `begin` starts a new one
+ let merge = bool_p(p, "merge").unwrap_or(false).then(|| format!("setParam:{}:{eff}:{pid}:{}", c.0, p.get("mask").unwrap_or(&Value::Null)));
+ if bool_p(p, "begin").unwrap_or(false) {
+ s.history.merge_key = None;
+ }
+ s.edit_sequence_as("Change Effect Parameter", merge.as_deref(), |q, _, _| {
let (_, it) = q.find_item_mut(c).ok_or(filmcraft_edit::EditError::NoItem(c))?;
let mt = it.source_time_at(tl.clamp(it.start, (it.end() - Tick(1)).max(it.start)));
let e = match &eff {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 833c1d613..922ebdd41 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -781,9 +781,20 @@ impl Session {
/// Edit the active sequence with the edit-algebra context.
pub fn edit_sequence<R>(&mut self, label: &str, f: impl FnOnce(&mut Sequence, &mut EditCtx, &mut EditorState) -> Result<R>) -> Result<R> {
+ self.edit_sequence_as(label, None, f)
+ }
+
+ /// [`Session::edit_sequence`] that shares one undo step with the previous edit of the same
+ /// `merge` key, like [`Session::edit_merged`] (a drag is one undoable change).
+ pub fn edit_sequence_as<R>(
+ &mut self,
+ label: &str,
+ merge: Option<&str>,
+ f: impl FnOnce(&mut Sequence, &mut EditCtx, &mut EditorState) -> Result<R>,
+ ) -> Result<R> {
let seq_id = self.state.active_sequence.ok_or(EngineError::NoSequence)?;
let media = self.media.clone();
- self.edit(label, move |p, st| {
+ let body = move |p: &mut Project, st: &mut EditorState| {
let project_snapshot = std::sync::Arc::new(p.clone());
let snap = project_snapshot.clone();
let durations = move |id: ItemId| -> Option<Tick> { media_duration(&project_snapshot, &media, id) };
@@ -800,7 +811,11 @@ impl Session {
s.check().map_err(EngineError::Other)?;
}
Ok(r)
- })
+ };
+ match merge {
+ Some(key) => self.edit_merged(label, key, body),
+ None => self.edit(label, body),
+ }
}
pub fn undo(&mut self) -> Option<String> {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 8c72fa99f..4193afe93 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -501,3 +501,31 @@ fn empty_items_do_not_panic_keyframe_commands() {
let error = result.unwrap().unwrap_err();
assert!(error.to_string().contains("non-positive duration"), "expected the ordinary invariant error, got: {error}");
}
+
+/// #201: a drag of an effect parameter (`merge`, starting with `begin`) is one undo step, and the
+/// next drag is another.
+#[test]
+fn dragging_an_effect_parameter_is_one_undo_step() {
+ let mut s = demo_unlocked();
+ let id = v1(&s)[0].0;
+ let opacity = |s: &Session| {
+ let q = s.active_sequence().unwrap();
+ let it = q.find_item(ClipId(id)).unwrap().1;
+ let e = it.effects.iter().find(|e| e.effect == "opacity").unwrap();
+ e.params["opacity"].value.as_f64().unwrap()
+ };
+ let start = opacity(&s);
+ let set = |s: &mut Session, v: f64, begin: bool| {
+ s.execute("effects.setParam", json!({"clip": id, "effect": "opacity", "param": "opacity", "value": v, "merge": true, "begin": begin})).unwrap();
+ };
+ set(&mut s, 90.0, true);
+ set(&mut s, 70.0, false);
+ set(&mut s, 30.0, false);
+ set(&mut s, 50.0, true); // a second drag
+ set(&mut s, 60.0, false);
+ assert_eq!(opacity(&s), 60.0);
+ s.undo();
+ assert_eq!(opacity(&s), 30.0, "undo takes back the whole second drag");
+ s.undo();
+ assert_eq!(opacity(&s), start, "and then the whole first one");
+}
diff --git a/crates/ui-egui/src/panels/clip_dialogs.rs b/crates/ui-egui/src/panels/clip_dialogs.rs
index cbdb5e1df..a205e1ce6 100644
--- a/crates/ui-egui/src/panels/clip_dialogs.rs
+++ b/crates/ui-egui/src/panels/clip_dialogs.rs
@@ -1,6 +1,7 @@
//! Edit / Clip / File menu dialogs (M3.10): Paste Attributes, Remove Attributes, Offline File,
//! Make Subclip, Edit Subclip, Modify ▸ Audio Channels, Modify ▸ Timecode, Frame Hold Options,
-//! Field Options, Nest… (Nested Sequence Name), and the Close Project "save changes?" prompt.
+//! Field Options, Clip Speed / Duration, Nest… (Nested Sequence Name), and the Close Project
+//! "save changes?" prompt.
//!
//! The open dialog lives in `UiState::clip_dialog` (serde): the engine command it runs and the
//! parameters being edited — the same JSON the command takes — so agents can open a dialog from
@@ -23,6 +24,8 @@
//! - Frame Hold Options `frameHold.*`: `enabled`, `holdOn.<in|out|playhead|sourceTimecode|sequenceTime>`,
//! `timecode`, `holdFilters`;
//! - Field Options `fieldOptions.*`: `reverseFieldDominance`, `processing.<none|alwaysDeinterlace|flickerRemoval>`;
+//! - Clip Speed / Duration `speedDuration.*`: `speed`, `reverse`, `ripple`,
+//! `interpolation.<frameSampling|frameBlending|opticalFlow>`;
//! - Close Project `closeProject.save`, `closeProject.dontSave`, `closeProject.cancel`.
use egui::{Align2, RichText};
@@ -51,6 +54,7 @@ fn meta(command: &str) -> Option<(&'static str, &'static str)> {
"clip.modifyTimecode" => ("Modify Clip: Timecode", "timecode"),
"clip.frameHoldOptions" => ("Frame Hold Options", "frameHold"),
"clip.fieldOptions" => ("Field Options", "fieldOptions"),
+ "clip.speedDuration" => ("Clip Speed / Duration", "speedDuration"),
"file.closeProject" => ("Save Project", "closeProject"),
_ => return None,
})
@@ -182,6 +186,18 @@ fn defaults(app: &FilmcraftApp, id: &str) -> (Value, Value) {
(json!({"enabled": enabled, "holdOn": "in", "timecode": tc, "holdFilters": hold_filters}), Value::Null)
}
"clip.fieldOptions" => (json!({"reverseFieldDominance": false, "processing": "none"}), Value::Null),
+ "clip.speedDuration" => {
+ // the first selected clip's current speed; its duration at that speed for the readout
+ let q = s.active_sequence();
+ let it = q.and_then(|q| s.state.selection.iter().find_map(|c| q.find_item(*c).map(|x| x.1.clone())));
+ let fps = q.map(|q| q.settings.frame_rate.as_f64()).unwrap_or(24.0);
+ let speed = it.as_ref().map_or(1.0, |i| i.speed);
+ let interp = it.as_ref().map_or(filmcraft_project::TimeInterpolation::default(), |i| i.time_interpolation);
+ (
+ json!({"speed": (speed.abs() * 100.0 * 100.0).round() / 100.0, "reverse": speed < 0.0, "ripple": false, "interpolation": interp.name()}),
+ json!({"duration": it.as_ref().map_or(0, |i| i.duration.0), "speed": speed.abs(), "fps": fps}),
+ )
+ }
_ => (json!({}), Value::Null),
}
}
@@ -464,6 +480,31 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
}
}
}
+ "clip.speedDuration" => {
+ number(ui, &mut elems, pre, p, "speed", "Speed:", 0.01..=100_000.0, " %");
+ // Duration follows the speed: the media shown stays the same
+ let (dur, was, fps) =
+ (d.info["duration"].as_i64().unwrap_or(0), d.info["speed"].as_f64().unwrap_or(1.0), d.info["fps"].as_f64().unwrap_or(24.0));
+ let now = p["speed"].as_f64().unwrap_or(100.0) / 100.0;
+ if dur > 0 && now > 0.0 {
+ let rate = filmcraft_time::FrameRate::from_f64(if fps > 0.0 { fps } else { 24.0 });
+ let ticks = filmcraft_time::Tick((dur as f64 * was / now).round() as i64);
+ ui.horizontal(|ui| {
+ ui.label("Duration:");
+ ui.label(RichText::new(filmcraft_time::format_timecode_frames(rate.frame_at(ticks), rate, false)).monospace());
+ });
+ }
+ check(ui, &mut elems, pre, p, "reverse", "Reverse Speed", true);
+ check(ui, &mut elems, pre, p, "ripple", "Ripple Edit, Shifting Trailing Clips", true);
+ ui.label(RichText::new("Time Interpolation").strong());
+ for m in filmcraft_project::TimeInterpolation::ALL {
+ let r = ui.radio(p["interpolation"].as_str() == Some(m.name()), m.label());
+ push(&mut elems, format!("{pre}.interpolation.{}", m.name()), &r, m.label());
+ if r.clicked() {
+ p["interpolation"] = json!(m.name());
+ }
+ }
+ }
"file.closeProject" => {
ui.label(format!("Save changes to “{project_name}” before closing?"));
ui.add_space(8.0);
diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs
index 0397d3ad4..9d49e2f12 100644
--- a/crates/ui-egui/src/panels/effect_controls.rs
+++ b/crates/ui-egui/src/panels/effect_controls.rs
@@ -169,11 +169,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
// footer timecode
let tc = filmcraft_time::format_time(ph, seq.settings.frame_rate, seq.settings.drop_frame, filmcraft_time::TimeDisplay::Timecode, 48000);
ui.painter().text(pos2(rect.min.x + 10.0, rect.max.y - 13.0), Align2::LEFT_CENTER, tc, Tokens::mono(13.0), t.timecode);
- for (cmd, p) in actions {
- if let Err(e) = app.session.execute(&cmd, p) {
- app.ui.status = e.to_string();
- }
- }
+ run(app, ui.ctx(), actions);
}
/// Premiere's "Custom Setup ▸ Edit…" row: opens the effect's Clip Fx Editor window.
@@ -528,11 +524,7 @@ pub fn lumetri_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
});
- for a in actions {
- if let Err(e) = app.session.execute("effects.setParam", a) {
- app.ui.status = e.to_string();
- }
- }
+ run(app, ui.ctx(), actions.into_iter().map(|a| ("effects.setParam".to_string(), a)).collect());
}
/// Properties panel (Premiere 26): a compact inspector for the selected clip.
@@ -710,7 +702,18 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
bui.painter().rect_filled(br, 4.0, if bresp.hovered() { t.hover } else { t.panel_bg });
bui.painter().rect_stroke(br, 4.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Inside);
bui.painter().text(br.center(), Align2::CENTER_CENTER, format!("Speed {:.0}%", it.speed * 100.0), Tokens::ui(12.0), t.text);
- for (cmd, p) in actions {
+ run(app, ui.ctx(), actions);
+}
+
+/// Run the panel's actions. Parameter changes made while the mouse button is down (a drag) share
+/// one undo step, starting at the press (#201); typed values and clicks stay separate steps.
+fn run(app: &mut FilmcraftApp, ctx: &egui::Context, actions: Vec<(String, Value)>) {
+ let (down, pressed) = ctx.input(|i| (i.pointer.any_down(), i.pointer.any_pressed()));
+ for (cmd, mut p) in actions {
+ if cmd == "effects.setParam" && down {
+ p["merge"] = json!(true);
+ p["begin"] = json!(pressed);
+ }
if let Err(e) = app.session.execute(&cmd, p) {
app.ui.status = e.to_string();
}
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 872b4e301..0172243c0 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -2108,10 +2108,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let r = ui.add_enabled(!sel.is_empty() && app.session.is_enabled(cmd), egui::Button::new(label));
app.auto.add(&format!("timeline.clipMenu.{cmd}"), r.rect, label);
if r.clicked() {
- if cmd == "clip.speedDuration" {
- app.dialog = None;
- let _ = app.session.execute(cmd, json!({"speed": 50.0}));
- } else if let Err(e) = crate::menus::invoke(app, &ctx, cmd, json!({})) {
+ if let Err(e) = crate::menus::invoke(app, &ctx, cmd, json!({})) {
app.ui.status = e;
}
ui.close();
diff --git a/crates/ui-egui/tests/clip_dialogs_ui.rs b/crates/ui-egui/tests/clip_dialogs_ui.rs
index d70e57198..d02c16667 100644
--- a/crates/ui-egui/tests/clip_dialogs_ui.rs
+++ b/crates/ui-egui/tests/clip_dialogs_ui.rs
@@ -239,3 +239,33 @@ fn subclip_in_the_source_monitor_and_project_menu() {
panic!("subclip row not shown: {:?}", d.ok("ui.elements", json!({"prefix": "project.item."})));
}
}
+
+/// #201: the clip's right-click Speed/Duration… opens the dialog instead of applying 50%; OK
+/// applies the speed typed there, Cancel leaves the clip alone.
+#[test]
+fn speed_duration_from_the_clip_menu_opens_the_dialog() {
+ let mut d = Driver::new();
+ let c = d.v1(0);
+ d.exec("timeline.select", json!({"clips": [c.id.0]}));
+ d.ok("ui.click", json!({"id": format!("timeline.clip.{}", c.id.0), "button": "right"}));
+ d.frames(3);
+ d.click("timeline.clipMenu.clip.speedDuration");
+ assert_eq!(d.v1(0).speed, 1.0, "nothing applied yet");
+ let dlg = d.app().ui.clip_dialog.clone().expect("the dialog opened");
+ assert_eq!(dlg.command, "clip.speedDuration");
+ assert_eq!(dlg.params["speed"], json!(100.0), "starts at the clip's speed");
+ assert!(d.has("speedDuration.reverse") && d.has("speedDuration.interpolation.frameBlending"));
+ d.click("speedDuration.cancel");
+ assert!(d.app().ui.clip_dialog.is_none());
+ assert_eq!(d.v1(0).speed, 1.0, "Cancel leaves it");
+
+ d.menu("clip.speedDuration");
+ if let Some(dlg) = d.app().ui.clip_dialog.as_mut() {
+ dlg.params["speed"] = json!(200.0);
+ }
+ d.click("speedDuration.interpolation.frameBlending");
+ d.click("speedDuration.ok");
+ let got = d.v1(0);
+ assert_eq!(got.speed, 2.0);
+ assert_eq!(got.time_interpolation, filmcraft_project::TimeInterpolation::FrameBlending);
+}