Skip to content

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

#430, #224: select a transition, edit it in Effect Controls, Delete it, drag its ends or middle

swillunderscoreefd62f7bdafc
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index a39dc82ea..a5c296e6b 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -3480,3 +3480,5 @@
New Sequence Nueva secuencia
Tracks Pistas
tracks pistas
+ Clear Transition Borrar transición
+ Set Transition Duration Establecer duración de la transición
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 83d18261e..e88c57c21 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -162,6 +162,8 @@ pub enum Dialog {
AddTracks,
/// Sequence ▸ Sequence Settings….
SequenceSettings,
+ /// Set Transition Duration (double-click a transition in the Timeline).
+ TransitionDuration,
}
#[derive(Default)]
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index e82e2c3cf..eed8fd28f 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -67,6 +67,12 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
}
return;
}
+ Dialog::TransitionDuration => {
+ if !crate::panels::transition_controls::duration_dialog(app, ctx) && app.dialog == Some(d) {
+ app.dialog = None;
+ }
+ return;
+ }
Dialog::SequenceSettings => {
if !crate::panels::sequence_settings::show(app, ctx) && app.dialog == Some(d) {
app.dialog = None;
diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs
index e3ae049c4..905089f18 100644
--- a/crates/ui-egui/src/panels/effect_controls.rs
+++ b/crates/ui-egui/src/panels/effect_controls.rs
@@ -46,6 +46,11 @@ fn selected_clip(app: &FilmcraftApp) -> Option<(ClipId, TrackItem, filmcraft_pro
pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let Some((clip, it, kind)) = selected_clip(app) else {
+ // a transition clicked in the Timeline (#430)
+ if let Some(id) = crate::panels::transition_controls::selected(app) {
+ crate::panels::transition_controls::effect_controls(app, ui, rect, id);
+ return;
+ }
crate::dock::placeholder(ui, rect, &t, tl!("(no clip selected)"));
return;
};
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index e19bbce39..5591f357e 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -47,6 +47,7 @@ pub mod timeline_automation;
pub mod timeline_captions;
pub mod timeline_hit;
pub mod tools;
+pub mod transition_controls;
pub mod trim_monitor;
pub mod voiceover;
pub mod workspaces;
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 811a75eea..a826e9a43 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -128,6 +128,16 @@ pub enum Drag {
/// As in [`Drag::Trim`].
from: Tick,
},
+ /// A transition dragged by an end (`edge`: its duration) or its middle (slides it over the
+ /// cut); `start` / `duration` are where it is shown now, committed on release (#224).
+ Transition {
+ id: filmcraft_project::TransitionId,
+ edge: Option<filmcraft_edit::Edge>,
+ /// As in [`Drag::Trim`].
+ from: Tick,
+ start: Tick,
+ duration: Tick,
+ },
Pan {
last: Pos2,
},
@@ -411,13 +421,22 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
// selected edit points (trim mode): red brackets for ripple, yellow for roll / regular trim
super::trim_monitor::paint_edit_points(app, &p, &seq, tr, r, &layout);
- // transitions
+ // transitions (one being dragged where the drag puts it; the selected ones outlined)
for trn in &tr.transitions {
- let x0 = layout.x_of(trn.start);
- let x1 = layout.x_of(trn.end());
+ let (start, end) = match &app.tl.drag {
+ Some(Drag::Transition { id, start, duration, .. }) if *id == trn.id => (*start, *start + *duration),
+ _ => (trn.start, trn.end()),
+ };
+ let x0 = layout.x_of(start);
+ let x1 = layout.x_of(end);
let tr_rect = Rect::from_min_max(pos2(x0, r.rect.min.y + 17.0), pos2(x1, r.rect.max.y - 1.0));
- draw_transition(&p, tr_rect, trn, &t);
+ let selected = app.session.state.transition_selection.contains(&trn.id);
+ draw_transition(&p, tr_rect, trn, selected, &t);
app.auto.add(&format!("timeline.transition.{}", trn.id.0), tr_rect, &trn.effect.effect);
+ // its ends, for dragging the duration (the same zones as the hit test)
+ let zone = super::timeline_hit::EDGE_PX.min(tr_rect.width() / 3.0);
+ app.auto.add(&format!("timeline.transition.{}.in", trn.id.0), Rect::from_min_max(tr_rect.min, pos2(x0 + zone, tr_rect.max.y)), "start");
+ app.auto.add(&format!("timeline.transition.{}.out", trn.id.0), Rect::from_min_max(pos2(x1 - zone, tr_rect.min.y), tr_rect.max), "end");
}
}
@@ -896,7 +915,7 @@ fn paint_hatch(p: &egui::Painter, r: Rect) {
}
}
-fn draw_transition(p: &egui::Painter, r: Rect, trn: &filmcraft_project::Transition, _t: &Tokens) {
+fn draw_transition(p: &egui::Painter, r: Rect, trn: &filmcraft_project::Transition, selected: bool, t: &Tokens) {
let cp = p.with_clip_rect(r.intersect(p.clip_rect()));
cp.rect_filled(r, 0.0, Color32::from_black_alpha(90));
paint_hatch(p, r);
@@ -918,6 +937,9 @@ fn draw_transition(p: &egui::Painter, r: Rect, trn: &filmcraft_project::Transiti
cp.add(egui::Shape::line(b, Stroke::new(1.0, Color32::WHITE)));
}
cp.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_rgb(0xeb, 0xeb, 0xeb)), StrokeKind::Inside);
+ if selected {
+ cp.rect_stroke(r, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
+ }
if r.width() > 34.0 && !audio {
let name = trn.effect.def().map(|d| d.name).unwrap_or(&trn.effect.effect);
let tr = Rect::from_min_size(r.min + vec2(2.0, 2.0), vec2((r.width() - 4.0).min(80.0), 13.0));
@@ -1460,7 +1482,7 @@ pub fn hit_json(app: &FilmcraftApp, pos: Pos2, mods: egui::Modifiers) -> Value {
Hit::Clip { track, clip, edge } => {
json!({"hit": "clip", "track": track.0, "clip": clip.0, "edge": edge.map(|e| format!("{e:?}")), "kind": kind, "time": t.0})
}
- Hit::Transition { track, id } => json!({"hit": "transition", "track": track.0, "transition": id.0}),
+ Hit::Transition { track, id, edge } => json!({"hit": "transition", "track": track.0, "transition": id.0, "edge": edge.map(|e| format!("{e:?}"))}),
Hit::Empty { track } => json!({"hit": "empty", "track": track.0, "time": t.0}),
Hit::None => json!({"hit": "none"}),
}
@@ -1730,6 +1752,8 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let g = grab_at(seq, layout, p, tool, mods, roll_ripple);
let cur = match (tool, g) {
(_, Grab::Edge { .. }) => CursorIcon::ResizeColumn,
+ (Tool::Selection, Grab::Other(Hit::Transition { edge: Some(_), .. })) => CursorIcon::ResizeColumn,
+ (Tool::Selection, Grab::Other(Hit::Transition { edge: None, .. })) => CursorIcon::Grab,
(Tool::Razor, Grab::Other(Hit::Clip { .. })) => CursorIcon::Crosshair,
(Tool::Slip | Tool::Slide, Grab::Other(Hit::Clip { .. })) => CursorIcon::ResizeHorizontal,
(Tool::Hand, _) => CursorIcon::Grab,
@@ -1834,6 +1858,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
} else if !sel.contains(&clip) {
if mods.alt {
app.session.state.selection = vec![clip];
+ app.session.state.transition_selection.clear();
} else {
let _ = app.session.execute("timeline.select", json!({"clips": [clip.0]}));
}
@@ -1845,6 +1870,21 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
None
}
}
+ // click a transition to select it (Shift adds / removes); drag an end to change its
+ // duration or its middle to slide it over the cut (#430, #224)
+ (Tool::Selection, Grab::Other(Hit::Transition { id, edge, .. })) => {
+ if !(app.session.state.transition_selection.contains(&id) && !mods.shift && resp.drag_started()) {
+ let r = app.session.execute("timeline.select", json!({"transitions": [id.0], "toggle": mods.shift}));
+ if let Err(e) = r {
+ app.ui.status = e.to_string();
+ }
+ }
+ let span = seq.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == id)).map(|x| (x.start, x.duration));
+ match span {
+ Some((start, duration)) if resp.drag_started() => Some(Drag::Transition { id, edge, from: t, start, duration }),
+ _ => None,
+ }
+ }
(_, Grab::Other(Hit::Transition { .. })) => None,
(_, Grab::Other(Hit::Empty { .. })) => {
if resp.drag_started() {
@@ -1852,6 +1892,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
} else {
app.session.state.selection.clear();
app.session.state.edit_points.clear();
+ app.session.state.transition_selection.clear();
None
}
}
@@ -1939,6 +1980,17 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let origin = ctx.input(|i| i.pointer.press_origin()).map(|o| layout.tick_at(o.x)).unwrap_or(t_here);
Some(Drag::Slide { clip, delta: rate.snap_nearest(t_here - origin) })
}
+ Drag::Transition { id, edge, from, start, duration } => {
+ let delta = rate.snap_nearest(t_here - from);
+ let span = seq.all_tracks().find_map(|tr| {
+ tr.transitions
+ .iter()
+ .find(|x| x.id == id)
+ .and_then(|x| filmcraft_edit::transitions::drag_span(tr, x, edge, delta, rate.frame_duration(), |t| rate.snap(t)))
+ });
+ let (start, duration) = span.unwrap_or((start, duration));
+ Some(Drag::Transition { id, edge, from, start, duration })
+ }
Drag::Marquee { start } => {
let r = Rect::from_two_pos(start, p);
ui.painter().rect_filled(r, 0.0, Color32::from_white_alpha(18));
@@ -1985,6 +2037,10 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
Drag::Roll { left, right, delta, .. } if delta != Tick::ZERO => Some(app.session.execute("timeline.roll", json!({"left": left.0, "right": right.0, "delta": delta.0}))),
Drag::Slip { clip, delta } if delta != Tick::ZERO => Some(app.session.execute("timeline.slip", json!({"clip": clip.0, "delta": delta.0}))),
Drag::Slide { clip, delta } if delta != Tick::ZERO => Some(app.session.execute("timeline.slide", json!({"clip": clip.0, "delta": delta.0}))),
+ Drag::Transition { id, start, duration, .. } => {
+ let moved = seq.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == id)).is_some_and(|x| (x.start, x.duration) != (start, duration));
+ moved.then(|| app.session.execute("sequence.setTransition", json!({"transition": id.0, "start": start.0, "duration": duration.0})))
+ }
Drag::Marquee { start } => {
if let Some(end) = resp.interact_pointer_pos() {
let r = Rect::from_two_pos(start, end);
@@ -2008,6 +2064,15 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
}
}
+ // ---- double-click a transition: Set Transition Duration (Premiere)
+ if resp.double_clicked()
+ && tool == Tool::Selection
+ && let Some(p) = resp.interact_pointer_pos()
+ && let Hit::Transition { id, .. } = hit(seq, layout, p)
+ {
+ crate::panels::transition_controls::open_duration(app, id);
+ }
+
// ---- double-click a nested sequence clip: open it in its own Timeline tab
if resp.double_clicked()
&& tool == Tool::Selection
diff --git a/crates/ui-egui/src/panels/timeline_hit.rs b/crates/ui-egui/src/panels/timeline_hit.rs
index fa536c774..efc1dad01 100644
--- a/crates/ui-egui/src/panels/timeline_hit.rs
+++ b/crates/ui-egui/src/panels/timeline_hit.rs
@@ -50,9 +50,21 @@ pub(crate) fn edge_geometry(seq: &Sequence, layout: &Layout, track: TrackId, cli
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Hit {
Ruler,
- Clip { track: TrackId, clip: ClipId, edge: Option<Edge> },
- Transition { track: TrackId, id: TransitionId },
- Empty { track: TrackId },
+ Clip {
+ track: TrackId,
+ clip: ClipId,
+ edge: Option<Edge>,
+ },
+ /// A transition; `edge` is its start (`In`) or end (`Out`) when the press is on one of its
+ /// ends (dragging it changes the duration), `None` on its middle (dragging slides it).
+ Transition {
+ track: TrackId,
+ id: TransitionId,
+ edge: Option<Edge>,
+ },
+ Empty {
+ track: TrackId,
+ },
None,
}
@@ -69,7 +81,16 @@ pub fn hit(seq: &Sequence, layout: &Layout, pos: Pos2) -> Hit {
let x0 = layout.x_of(trn.start);
let x1 = layout.x_of(trn.end());
if pos.x >= x0 && pos.x <= x1 && pos.y > row.rect.min.y + 17.0 {
- return Hit::Transition { track: row.track, id: trn.id };
+ // the ends are edge zones, narrower on a short transition so its middle stays grabbable
+ let zone = EDGE_PX.min((x1 - x0) / 3.0);
+ let edge = if pos.x - x0 <= zone {
+ Some(Edge::In)
+ } else if x1 - pos.x <= zone {
+ Some(Edge::Out)
+ } else {
+ None
+ };
+ return Hit::Transition { track: row.track, id: trn.id, edge };
}
}
if let Some((clip, edge)) = edge_at(tr, layout, pos.x) {
diff --git a/crates/ui-egui/src/panels/transition_controls.rs b/crates/ui-egui/src/panels/transition_controls.rs
new file mode 100644
index 000000000..80a8a0d4a
--- /dev/null
+++ b/crates/ui-egui/src/panels/transition_controls.rs
@@ -0,0 +1,305 @@
+//! A selected transition (#430): its Effect Controls (Duration, Alignment, Reverse and its own
+//! settings, as Premiere's Change transition settings / Align transitions / Change transition
+//! duration pages describe them) and the Set Transition Duration dialog a double-click on it in
+//! the Timeline opens. Every change is one `sequence.setTransition`; dragging a value is one undo
+//! step.
+//!
+//! Not here yet: the A/B preview thumbnails with their Start / End sliders, Show Actual Sources,
+//! and dragging the transition in Effect Controls' own time ruler (the Timeline does that).
+//!
+//! Automation ids: `effectControls.transition.duration`, `.alignment` (+ `.alignment.option.<center|
+//! start|end>` while open), `.reverse`, `.reset`, `.param.<id>` (a point's are `.param.<id>.x` /
+//! `.y`; a list's entries `.param.<id>.option.<n>` while open); the dialog's
+//! `transitionDuration.value`, `.ok`, `.cancel`.
+
+use egui::{Rect, RichText, vec2};
+use filmcraft_edit::transitions::{self as trn, Alignment};
+use filmcraft_project::{ParamKind, ParamValue, Transition, TransitionId};
+use filmcraft_time::FrameRate;
+use serde_json::{Value, json};
+
+use crate::FilmcraftApp;
+use crate::state::TransitionDurationDraft;
+
+type Elems = Vec<(String, Rect, String)>;
+
+/// The selected transition, when it still exists, with its alignment and how many frames it may
+/// last at most (the clips it joins).
+fn lookup(app: &FilmcraftApp, id: TransitionId) -> Option<(Transition, Alignment, i64)> {
+ let seq = app.session.active_sequence()?;
+ let rate = seq.settings.frame_rate.sane();
+ seq.all_tracks().find_map(|tr| {
+ let x = tr.transitions.iter().find(|x| x.id == id)?;
+ let (lo, cut, hi) = trn::bounds(tr, x)?;
+ let max = rate.frame_at(hi - lo).max(1);
+ Some((x.clone(), trn::alignment(x, cut, rate.frame_duration()), max))
+ })
+}
+
+/// The first selected transition that still exists.
+pub fn selected(app: &FilmcraftApp) -> Option<TransitionId> {
+ app.session.state.transition_selection.iter().copied().find(|id| lookup(app, *id).is_some())
+}
+
+fn timecode(frames: f64, rate: FrameRate, drop_frame: bool) -> String {
+ filmcraft_time::format_timecode_frames(frames.round() as i64, rate, drop_frame)
+}
+
+/// A duration field in frames that reads and takes timecode (or a plain frame count).
+fn duration_field(ui: &mut egui::Ui, frames: &mut i64, max: i64, rate: FrameRate, drop_frame: bool) -> egui::Response {
+ ui.add(egui::DragValue::new(frames).range(1..=max.max(1)).speed(0.25).custom_formatter(move |v, _| timecode(v, rate, drop_frame)).custom_parser(move |s| {
+ match s.trim().parse::<i64>() {
+ Ok(n) => Some(n as f64),
+ Err(_) => filmcraft_time::parse_timecode(s, rate, drop_frame, 0).ok().map(|n| n as f64),
+ }
+ }))
+}
+
+/// Effect Controls for a selected transition. `rect` is the panel.
+pub fn effect_controls(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, id: TransitionId) {
+ let t = app.tokens;
+ let Some((x, align, max_frames)) = lookup(app, id) else {
+ crate::dock::placeholder(ui, rect, &t, tl!("(no clip selected)"));
+ return;
+ };
+ let Some(seq) = app.session.active_sequence() else { return };
+ let (rate, drop_frame) = (seq.settings.frame_rate.sane(), seq.settings.drop_frame);
+ let (fw, fh) = (f64::from(seq.settings.width), f64::from(seq.settings.height));
+ let seq_name = app.session.state.active_sequence.and_then(|i| app.session.project.item(i)).map(|i| i.name.clone()).unwrap_or_default();
+ let def = x.effect.def();
+ let name = def.map_or(x.effect.effect.as_str(), |d| d.name).to_string();
+ let one_sided = x.from.is_none() || x.to.is_none();
+ let mut changes: Vec<Value> = Vec::new();
+ let mut elems: Elems = Vec::new();
+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(10.0, 6.0))).id_salt(("tr-ec", id.0)));
+ child.label(RichText::new(format!("{seq_name} · {name}")).color(t.text_dim));
+ child.add_space(4.0);
+ egui::ScrollArea::vertical().id_salt(("tr-ec-scroll", id.0)).auto_shrink([false, false]).show(&mut child, |ui| {
+ egui::Grid::new(("tr-ec-grid", id.0)).num_columns(2).spacing([14.0, 8.0]).show(ui, |ui| {
+ ui.label(tl!("Duration"));
+ let mut frames = rate.frame_at(x.duration).max(1);
+ let r = duration_field(ui, &mut frames, max_frames, rate, drop_frame);
+ elems.push(("effectControls.transition.duration".into(), r.rect, timecode(frames as f64, rate, drop_frame)));
+ if r.changed() {
+ changes.push(json!({"frames": frames, "merge": true, "begin": r.drag_started() || !r.dragged()}));
+ }
+ ui.end_row();
+
+ ui.label(tl!("Alignment"));
+ let shown = align.label();
+ let r = ui
+ .add_enabled_ui(!one_sided, |ui| {
+ egui::ComboBox::from_id_salt(("tr-align", id.0))
+ .selected_text(shown)
+ .width(170.0)
+ .show_ui(ui, |ui| {
+ for a in Alignment::MENU {
+ let o = ui.selectable_label(a == align, a.label());
+ if o.clicked() && a != align {
+ changes.push(json!({"align": a.id()}));
+ }
+ elems.push((format!("effectControls.transition.alignment.option.{}", a.id()), o.rect, a.label().to_string()));
+ }
+ })
+ .response
+ })
+ .inner;
+ elems.push(("effectControls.transition.alignment".into(), r.rect, shown.to_string()));
+ ui.end_row();
+
+ ui.label(tl!("Reverse"));
+ let mut rev = x.reverse;
+ let r = ui.checkbox(&mut rev, "");
+ elems.push(("effectControls.transition.reverse".into(), r.rect, rev.to_string()));
+ if r.changed() {
+ changes.push(json!({"reverse": rev}));
+ }
+ ui.end_row();
+
+ for pd in def.map(|d| d.params.as_slice()).unwrap_or(&[]) {
+ let value = x.effect.params.get(pd.id).map_or(&pd.default, |p| &p.value);
+ ui.label(crate::i18n::t(pd.label));
+ if let Some(v) = param_widget(ui, &mut elems, pd.id, &pd.kind, value, (fw, fh)) {
+ changes.push(v);
+ }
+ ui.end_row();
+ }
+ });
+ ui.add_space(8.0);
+ let r = ui.button(tl!("Reset"));
+ elems.push(("effectControls.transition.reset".into(), r.rect, "Reset".into()));
+ if r.clicked() {
+ changes.push(json!({"reset": true}));
+ }
+ });
+ for (eid, r, l) in elems {
+ app.auto.add(&eid, r, &l);
+ }
+ for mut c in changes {
+ c["transition"] = json!(id.0);
+ if let Err(e) = app.session.execute("sequence.setTransition", c) {
+ app.ui.status = e.to_string();
+ }
+ }
+}
+
+/// One of a transition's own settings. Returns the change, as `sequence.setTransition` params.
+fn param_widget(ui: &mut egui::Ui, elems: &mut Elems, pid: &str, kind: &ParamKind, value: &ParamValue, frame: (f64, f64)) -> Option<Value> {
+ let eid = format!("effectControls.transition.param.{pid}");
+ let drag = |r: &egui::Response| json!({"merge": true, "begin": r.drag_started() || !r.dragged()});
+ match (kind, value) {
+ (ParamKind::Float { min, max, soft_min, soft_max, unit, decimals }, ParamValue::Float(v)) => {
+ let mut v = *v;
+ let speed = ((soft_max - soft_min) / 200.0).max(0.001);
+ let r = ui.add(egui::DragValue::new(&mut v).range(*min..=*max).speed(speed).max_decimals(usize::from(*decimals)).suffix(*unit));
+ elems.push((eid, r.rect, format!("{v}")));
+ r.changed().then(|| {
+ let mut c = drag(&r);
+ c["params"] = json!({ pid: v });
+ c
+ })
+ }
+ (ParamKind::Angle, ParamValue::Float(v)) => {
+ let mut v = *v;
+ let r = ui.add(egui::DragValue::new(&mut v).speed(0.5).suffix("°"));
+ elems.push((eid, r.rect, format!("{v}")));
+ r.changed().then(|| {
+ let mut c = drag(&r);
+ c["params"] = json!({ pid: v });
+ c
+ })
+ }
+ (ParamKind::Bool, ParamValue::Bool(b)) => {
+ let mut b = *b;
+ let r = ui.checkbox(&mut b, "");
+ elems.push((eid, r.rect, b.to_string()));
+ r.changed().then(|| json!({"params": { pid: b }}))
+ }
+ (ParamKind::Choice(opts), ParamValue::Choice(c)) => {
+ let shown = opts.get(*c as usize).copied().unwrap_or("");
+ let mut picked = None;
+ let mut options = Vec::new();
+ let r = egui::ComboBox::from_id_salt(("tr-param", pid.to_string())).selected_text(crate::i18n::t(shown)).show_ui(ui, |ui| {
+ for (i, o) in opts.iter().enumerate() {
+ let r = ui.selectable_label(i == *c as usize, crate::i18n::t(o));
+ if r.clicked() && i != *c as usize {
+ picked = Some(i);
+ }
+ options.push((format!("{eid}.option.{i}"), r.rect, o.to_string()));
+ }
+ });
+ elems.extend(options);
+ elems.push((eid, r.response.rect, shown.to_string()));
+ picked.map(|i| json!({"params": { pid: i }}))
+ }
+ (ParamKind::Color, ParamValue::Color(c)) => {
+ let mut c = *c;
+ let r = ui.color_edit_button_rgba_unmultiplied(&mut c);
+ elems.push((eid, r.rect, format!("{c:?}")));
+ r.changed().then(|| {
+ let mut v = drag(&r);
+ v["params"] = json!({ pid: [c[0], c[1], c[2], c[3]] });
+ v
+ })
+ }
+ (ParamKind::Point, ParamValue::Vec2(p)) => {
+ // an automatic point (NaN) is the frame's centre until it is moved
+ let (mut px, mut py) = (if p.x.is_nan() { frame.0 / 2.0 } else { p.x }, if p.y.is_nan() { frame.1 / 2.0 } else { p.y });
+ let mut out = None;
+ ui.horizontal(|ui| {
+ let rx = ui.add(egui::DragValue::new(&mut px).speed(1.0).prefix("x "));
+ let ry = ui.add(egui::DragValue::new(&mut py).speed(1.0).prefix("y "));
+ elems.push((format!("{eid}.x"), rx.rect, format!("{px}")));
+ elems.push((format!("{eid}.y"), ry.rect, format!("{py}")));
+ for r in [&rx, &ry] {
+ if r.changed() {
+ let mut v = drag(r);
+ v["params"] = json!({ pid: [px, py] });
+ out = Some(v);
+ }
+ }
+ });
+ out
+ }
+ (_, v) => {
+ let r = ui.label(RichText::new(format!("{v:?}")).weak());
+ elems.push((eid, r.rect, String::new()));
+ None
+ }
+ }
+}
+
+/// Double-click a transition in the Timeline: Set Transition Duration.
+pub fn open_duration(app: &mut FilmcraftApp, id: TransitionId) {
+ let Some((x, ..)) = lookup(app, id) else { return };
+ let rate = app.session.active_sequence().map(|q| q.settings.frame_rate.sane()).unwrap_or_default();
+ app.ui.transition_duration = TransitionDurationDraft { transition: id.0, frames: rate.frame_at(x.duration).max(1) };
+ let _ = app.session.execute("timeline.select", json!({"transitions": [id.0]}));
+ app.dialog = Some(crate::Dialog::TransitionDuration);
+}
+
+/// The Set Transition Duration dialog. Returns whether it stays open.
+pub fn duration_dialog(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {
+ let mut d = app.ui.transition_duration.clone();
+ let id = TransitionId(d.transition);
+ let Some((_, _, max_frames)) = lookup(app, id) else { return false };
+ let Some(seq) = app.session.active_sequence() else { return false };
+ let (rate, drop_frame) = (seq.settings.frame_rate.sane(), seq.settings.drop_frame);
+ let accent = app.tokens.accent;
+ let (mut keep, mut apply) = (true, false);
+ let mut elems: Elems = Vec::new();
+ egui::Window::new(tl!("Set Transition Duration"))
+ .collapsible(false)
+ .resizable(false)
+ .default_width(260.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ ui.label(tl!("Duration:"));
+ let r = duration_field(ui, &mut d.frames, max_frames, rate, drop_frame);
+ elems.push(("transitionDuration.value".into(), r.rect, timecode(d.frames as f64, rate, drop_frame)));
+ });
+ ui.add_space(8.0);
+ // one row high: a right-to-left layout would otherwise take the window's whole height
+ let row = egui::vec2(ui.available_width().max(220.0), ui.spacing().interact_size.y);
+ ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let o = ui.add(egui::Button::new(RichText::new(tl!("OK")).color(egui::Color32::WHITE)).fill(accent));
+ elems.push(("transitionDuration.ok".into(), o.rect, "OK".into()));
+ apply |= o.clicked();
+ let c = ui.button(tl!("Cancel"));
+ elems.push(("transitionDuration.cancel".into(), c.rect, "Cancel".into()));
+ keep &= !c.clicked();
+ });
+ });
+ for (eid, r, l) in elems {
+ app.auto.add(&eid, r, &l);
+ }
+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ keep = false;
+ }
+ if ctx.input(|i| i.key_pressed(egui::Key::Enter)) && !ctx.egui_wants_keyboard_input() {
+ apply = true;
+ }
+ if apply {
+ let cur = lookup(app, id).map(|(x, ..)| rate.frame_at(x.duration));
+ if cur != Some(d.frames)
+ && let Err(e) = app.session.execute("sequence.setTransition", json!({"transition": id.0, "frames": d.frames}))
+ {
+ app.ui.status = e.to_string();
+ }
+ keep = false;
+ }
+ app.ui.transition_duration = d;
+ keep
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn durations_read_as_timecode() {
+ assert_eq!(timecode(24.0, FrameRate::FPS_24, false), "00:00:01:00");
+ assert_eq!(timecode(30.0, FrameRate::FPS_29_97, true), "00;00;01;00");
+ }
+}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 140d60ccc..b8baf5a31 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -441,6 +441,9 @@ pub struct UiState {
/// Sequence Settings dialog draft.
#[serde(default)]
pub sequence_settings: SequenceSettingsDraft,
+ /// Set Transition Duration dialog draft (double-click a transition).
+ #[serde(default)]
+ pub transition_duration: TransitionDurationDraft,
/// On-monitor text editing (Type tool / double-click on a text layer).
#[serde(default)]
pub gfx_edit: Option<GfxEdit>,
@@ -744,6 +747,15 @@ impl Default for AddTracksDraft {
}
}
+/// The Set Transition Duration dialog (double-click a transition in the Timeline): which
+/// transition, and its duration in frames.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct TransitionDurationDraft {
+ pub transition: u64,
+ pub frames: i64,
+}
+
/// The Sequence Settings dialog (Sequence ▸ Sequence Settings…), filled from the active sequence
/// when it opens (`panels::sequence_settings::open`). `tab`: `general`, `color` or `vr`; the
/// timebase is `fps_num`/`fps_den`; `mix`: `Stereo`, `Mono`, `5.1` or `Adaptive`; `working_space`:
@@ -890,6 +902,7 @@ impl Default for UiState {
add_tracks: AddTracksDraft::default(),
delete_tracks: DeleteTracksDraft::default(),
sequence_settings: SequenceSettingsDraft::default(),
+ transition_duration: TransitionDurationDraft::default(),
gfx_edit: None,
pen_points: vec![],
link_media: None,
diff --git a/crates/ui-egui/tests/transitions_ui.rs b/crates/ui-egui/tests/transitions_ui.rs
new file mode 100644
index 000000000..0cd4db431
--- /dev/null
+++ b/crates/ui-egui/tests/transitions_ui.rs
@@ -0,0 +1,275 @@
+//! Headless UI tests of applied transitions in the Timeline (#430, #224): click one to select it
+//! and see it in Effect Controls, Delete it, drag its end or its middle, double-click it for Set
+//! Transition Duration. The real `FilmcraftApp` under `egui_kittest`, driven over the control
+//! channel by automation id.
+//!
+//! Set `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` to also render the window offscreen with wgpu and write
+//! `transition-*.png` there; without it no GPU is needed.
+
+use std::sync::mpsc::{Sender, channel};
+
+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>,
+ snapshots: Option<std::path::PathBuf>,
+}
+
+/// The demo's first video transition between two clips.
+#[derive(Clone, Copy, Debug)]
+struct Crossing {
+ id: u64,
+ start: i64,
+ duration: i64,
+ cut: i64,
+}
+
+impl Driver {
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let app = FilmcraftApp::new(session).with_control(rx);
+ let snapshots = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").map(std::path::PathBuf::from);
+ // 60 fps steps, so a double-click's two clicks fall within egui's double-click time
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000);
+ if snapshots.is_some() {
+ b = b.wgpu();
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, snapshots };
+ d.frames(4);
+ d.ok("ui.panel.show", json!({"panel": "EffectControls"}));
+ d.frames(3);
+ 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 call(&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() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let v = self.call(method, params.clone());
+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");
+ v["result"].clone()
+ }
+
+ fn exec(&mut self, command: &str, params: Value) -> Value {
+ self.ok("engine.execute", json!({"command": command, "params": params}))
+ }
+
+ fn find(&mut self, id: &str) -> Option<(f64, f64, f64, f64, String)> {
+ self.frames(2);
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id)?.clone();
+ let r: Vec<f64> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ Some((r[0], r[1], r[2], r[3], e["label"].as_str().unwrap_or_default().to_string()))
+ }
+
+ /// With `FILMCRAFT_UI_SNAPSHOT_DIR` set, render the whole window offscreen to `<name>.png`.
+ fn snapshot(&mut self, name: &str) {
+ let Some(dir) = self.snapshots.clone() else { return };
+ self.frames(2);
+ match self.harness.render() {
+ Ok(img) => {
+ std::fs::create_dir_all(&dir).unwrap();
+ img.save(dir.join(format!("{name}.png"))).unwrap();
+ }
+ Err(e) => eprintln!("snapshot {name} skipped: {e}"),
+ }
+ }
+
+ fn label(&mut self, id: &str) -> String {
+ self.find(id).unwrap_or_else(|| panic!("no element {id}")).4
+ }
+
+ fn click(&mut self, id: &str) {
+ self.find(id).unwrap_or_else(|| panic!("no element {id}"));
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(3);
+ }
+
+ fn crossing(&mut self) -> Crossing {
+ let q = self.exec("sequence.inspect", json!({}));
+ for tr in q["video"].as_array().unwrap() {
+ for x in tr["transitions"].as_array().unwrap() {
+ if let (Some(_), Some(to)) = (x["from"].as_u64(), x["to"].as_u64()) {
+ let cut = tr["items"].as_array().unwrap().iter().find(|i| i["clip"] == to).unwrap()["start"].as_i64().unwrap();
+ return Crossing { id: x["id"].as_u64().unwrap(), start: x["start"].as_i64().unwrap(), duration: x["duration"].as_i64().unwrap(), cut };
+ }
+ }
+ }
+ panic!("the demo has a transition between two clips");
+ }
+
+ fn transition(&mut self, id: u64) -> Option<Value> {
+ let q = self.exec("sequence.inspect", json!({}));
+ q["video"].as_array().unwrap().iter().flat_map(|t| t["transitions"].as_array().unwrap().clone()).find(|x| x["id"] == id)
+ }
+
+ fn rate(&mut self) -> (i64, i64) {
+ let q = self.exec("sequence.inspect", json!({}));
+ (q["settings"]["frame_rate"]["num"].as_i64().unwrap(), q["settings"]["frame_rate"]["den"].as_i64().unwrap())
+ }
+}
+
+/// Ticks in one frame of `rate`.
+fn frame_ticks((num, den): (i64, i64)) -> i64 {
+ 254_016_000_000 * den / num
+}
+
+/// Clicking a transition selects it (and only it) and opens it in Effect Controls; Delete removes
+/// it, leaving its clips; undo brings it back.
+#[test]
+fn click_selects_a_transition_and_delete_removes_it() {
+ let mut d = Driver::demo();
+ let c = d.crossing();
+ let tid = format!("timeline.transition.{}", c.id);
+ d.click(&tid);
+ let q = d.exec("sequence.inspect", json!({}));
+ assert_eq!(q["transitionSelection"], json!([c.id]), "{q}");
+ assert_eq!(q["selection"], json!([]), "a transition replaces the clip selection");
+ // Effect Controls shows it: duration as timecode, its alignment, Reverse
+ let (num, den) = d.rate();
+ let rate = filmcraft_engine::time::FrameRate { num, den };
+ let frames = c.duration / frame_ticks((num, den));
+ assert_eq!(d.label("effectControls.transition.duration"), filmcraft_engine::time::format_timecode_frames(frames, rate, false));
+ assert_eq!(d.label("effectControls.transition.alignment"), "Center at Cut");
+ assert_eq!(d.label("effectControls.transition.reverse"), "false");
+ d.snapshot("transition-selected");
+ let clips_before = q["video"].as_array().unwrap().iter().map(|t| t["items"].as_array().unwrap().len()).sum::<usize>();
+ // Delete
+ d.ok("ui.key", json!({"key": "Delete"}));
+ d.frames(3);
+ assert!(d.transition(c.id).is_none(), "Delete removes the selected transition");
+ let q = d.exec("sequence.inspect", json!({}));
+ assert_eq!(q["video"].as_array().unwrap().iter().map(|t| t["items"].as_array().unwrap().len()).sum::<usize>(), clips_before, "its clips stay");
+ assert!(d.find("effectControls.transition.duration").is_none(), "Effect Controls lets go of it");
+ d.exec("edit.undo", json!({}));
+ assert!(d.transition(c.id).is_some(), "undo brings it back");
+ // clicking a clip selects the clip instead
+ let clip = q["video"][0]["items"][0]["clip"].as_u64().unwrap();
+ d.exec("timeline.select", json!({"transitions": [c.id]}));
+ d.exec("timeline.select", json!({"clips": [clip]}));
+ assert_eq!(d.exec("sequence.inspect", json!({}))["transitionSelection"], json!([]));
+}
+
+/// Dragging a centred transition's end changes its duration on both sides of the cut (#224);
+/// dragging its middle slides it over the cut (Custom Start). Each drag is one undo step.
+#[test]
+fn dragging_a_transition_end_or_middle() {
+ let mut d = Driver::demo();
+ let c = d.crossing();
+ let frame = frame_ticks(d.rate());
+ let undo_before = d.exec("sequence.inspect", json!({}));
+ let (x, y, w, h, _) = d.find(&format!("timeline.transition.{}.out", c.id)).expect("the transition's end");
+ let (fx, fy) = (x + w / 2.0, y + h / 2.0);
+ d.ok("ui.drag", json!({"from": {"x": fx, "y": fy}, "to": {"x": fx + 40.0, "y": fy}, "steps": 8}));
+ d.frames(3);
+ let x1 = d.transition(c.id).unwrap();
+ let (s1, d1) = (x1["start"].as_i64().unwrap(), x1["duration"].as_i64().unwrap());
+ assert!(d1 > c.duration, "dragging the end out lengthens it: {} -> {d1}", c.duration);
+ assert_eq!(x1["align"], json!("center"), "a centred transition stays centred");
+ assert!((s1 + d1 / 2 - c.cut).abs() <= frame, "still centred on the cut");
+ assert_eq!((d1 - c.duration) % (2 * frame), 0, "both ends moved by whole frames");
+ // the middle: slide it right of centre
+ let (x, y, w, h, _) = d.find(&format!("timeline.transition.{}", c.id)).unwrap();
+ let (mx, my) = (x + w / 2.0, y + h / 2.0);
+ // more than egui's 6 px click tolerance, or the press is a click
+ d.ok("ui.drag", json!({"from": {"x": mx, "y": my}, "to": {"x": mx + 14.0, "y": my}, "steps": 6}));
+ d.frames(3);
+ let x2 = d.transition(c.id).unwrap();
+ assert_eq!(x2["duration"].as_i64(), Some(d1), "sliding keeps the duration");
+ assert!(x2["start"].as_i64().unwrap() > s1, "and moves it right");
+ assert!(x2["start"].as_i64().unwrap() <= c.cut, "still over the cut");
+ assert_eq!(x2["align"], json!("custom"));
+ // two drags, two undo steps
+ d.exec("edit.undo", json!({}));
+ d.exec("edit.undo", json!({}));
+ let back = d.transition(c.id).unwrap();
+ assert_eq!((back["start"].as_i64(), back["duration"].as_i64()), (Some(c.start), Some(c.duration)), "{undo_before}");
+}
+
+/// Double-clicking a transition opens Set Transition Duration, whose OK sets the duration
+/// (following the alignment); Effect Controls' Alignment menu re-aligns it on the cut.
+#[test]
+fn set_transition_duration_and_alignment_menu() {
+ let mut d = Driver::demo();
+ let c = d.crossing();
+ let frame = frame_ticks(d.rate());
+ // double-click it
+ let (x0, y0, w, h, _) = d.find(&format!("timeline.transition.{}", c.id)).unwrap();
+ d.ok("ui.click", json!({"x": x0 + w / 2.0, "y": y0 + h / 2.0, "count": 2}));
+ d.frames(3);
+ let frames = c.duration / frame;
+ assert!(d.find("transitionDuration.value").is_some(), "Set Transition Duration opened");
+ assert_eq!(d.harness.state().ui.transition_duration.frames, frames, "with its duration");
+ assert_eq!(d.exec("sequence.inspect", json!({}))["transitionSelection"], json!([c.id]), "and selected it");
+ d.snapshot("transition-duration-dialog");
+ // Center at Cut: a new duration moves both ends
+ d.harness.state_mut().ui.transition_duration.frames = 10;
+ d.frames(2);
+ d.click("transitionDuration.ok");
+ assert!(d.find("transitionDuration.value").is_none(), "closed");
+ let x = d.transition(c.id).unwrap();
+ assert_eq!((x["start"].as_i64(), x["duration"].as_i64(), x["align"].as_str()), (Some(c.cut - 5 * frame), Some(10 * frame), Some("center")));
+ // the Alignment menu: Start at Cut
+ d.click("effectControls.transition.alignment");
+ d.click("effectControls.transition.alignment.option.start");
+ let x = d.transition(c.id).unwrap();
+ assert_eq!((x["start"].as_i64(), x["duration"].as_i64(), x["align"].as_str()), (Some(c.cut), Some(10 * frame), Some("start")));
+ assert_eq!(d.label("effectControls.transition.alignment"), "Start at Cut");
+ // Reverse
+ d.click("effectControls.transition.reverse");
+ assert_eq!(d.transition(c.id).unwrap()["reverse"], json!(true));
+}
+
+/// A transition's own settings are in Effect Controls and change it (Push: Direction, Motion Blur).
+#[test]
+fn transition_settings_in_effect_controls() {
+ let mut d = Driver::demo();
+ let q = d.exec("sequence.inspect", json!({}));
+ let push = q["video"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .flat_map(|t| t["transitions"].as_array().unwrap().clone())
+ .find(|x| x["effect"] == "push")
+ .expect("the demo has a Push");
+ let id = push["id"].as_u64().unwrap();
+ d.click(&format!("timeline.transition.{id}"));
+ for p in ["direction", "motion_blur"] {
+ assert!(d.find(&format!("effectControls.transition.param.{p}")).is_some(), "{p} shown");
+ }
+ d.snapshot("transition-push-settings");
+ d.click("effectControls.transition.param.direction");
+ d.click("effectControls.transition.param.direction.option.0");
+ assert_eq!(d.transition(id).unwrap()["params"]["direction"], json!({"Choice": 0}));
+ d.click("effectControls.transition.reset");
+ let def = filmcraft_engine::project::vtransition::find_transition("push", filmcraft_engine::project::EffectKind::VideoTransition).unwrap();
+ let want = serde_json::to_value(&def.instance().params.get("direction").unwrap().value).unwrap();
+ assert_eq!(d.transition(id).unwrap()["params"]["direction"], want, "Reset puts Push's own defaults back");
+}