Skip to content

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

#482: Preview transition placement while dragging

DWAA166087a01072d0fc
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index b5e4c847a..4bb8113e6 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -3183,6 +3183,16 @@ fn set_transition(s: &mut Session, p: &Value) -> Result<Value> {
}
fn apply_transition(s: &mut Session, p: &Value, kind: TrackKind) -> Result<Value> {
+ let (track, tr) = preview_transition(s, p, kind)?;
+ let label = format!("Apply {}", tr.effect.def().map_or("Transition", |d| d.name));
+ let id = s.edit_sequence(&label, |q, ctx, _| Ok(edit::add_transition(q, track, tr, ctx)?))?;
+ Ok(json!({"transition": id.0}))
+}
+
+/// Plan an applied transition without editing the project or allocating an id.
+/// Uses the same `effect`, `clip`, `edge`, `frames` and settings as transition application,
+/// so a drag preview shows the exact range that release will commit.
+pub fn preview_transition(s: &Session, p: &Value, kind: TrackKind) -> Result<(TrackId, Transition)> {
let eff_id = str_p(p, "effect")
.map(str::to_string)
.unwrap_or_else(|| if kind == TrackKind::Video { s.state.default_video_transition.clone() } else { s.state.default_audio_transition.clone() });
@@ -3233,6 +3243,9 @@ fn apply_transition(s: &mut Session, p: &Value, kind: TrackKind) -> Result<Value
}
}
let (track, from, to, cut) = found.ok_or_else(|| EngineError::Other("no edit point at the playhead on targeted tracks".into()))?;
+ if q.track(track).is_some_and(|tr| tr.locked) {
+ return Err(edit::EditError::Locked.into());
+ }
let start = if from.is_some() && to.is_some() {
cut - dur.mul_ratio(1, 2)
} else if to.is_some() {
@@ -3241,9 +3254,7 @@ fn apply_transition(s: &mut Session, p: &Value, kind: TrackKind) -> Result<Value
cut - dur
};
let tr = Transition { id: TransitionId(0), effect: instance, start: rate.snap(start), duration: dur, from, to, align: Default::default(), reverse };
- let label = format!("Apply {}", def.name);
- let id = s.edit_sequence(&label, |q, ctx, _| Ok(edit::add_transition(q, track, tr, ctx)?))?;
- Ok(json!({"transition": id.0}))
+ Ok((track, tr))
}
/// JSON description of the project (bins, items) for agents.
diff --git a/crates/engine/src/vfx_tests.rs b/crates/engine/src/vfx_tests.rs
index f01ced7fa..cb2df9587 100644
--- a/crates/engine/src/vfx_tests.rs
+++ b/crates/engine/src/vfx_tests.rs
@@ -12,6 +12,38 @@ fn demo() -> Session {
s
}
+#[test]
+fn transition_preview_is_read_only_and_matches_apply_and_undo() {
+ use crate::commands::preview_transition;
+ use filmcraft_project::TrackKind;
+ for (kind, effect) in [(TrackKind::Video, "cross_dissolve"), (TrackKind::Audio, "constant_power")] {
+ let mut s = demo();
+ let clips: Vec<_> = s.active_sequence().unwrap().tracks(kind)[0].items.iter().map(|c| c.id).collect();
+ for clip in clips {
+ for edge in ["in", "out"] {
+ let params = json!({"effect": effect, "clip": clip.0, "edge": edge, "frames": 7});
+ let before = s.project.to_json();
+ let revision = s.revision;
+ let (track, planned) = preview_transition(&s, &params, kind).unwrap();
+ assert_eq!(s.project.to_json(), before);
+ assert_eq!(s.revision, revision);
+ let result = s.execute("effects.apply", params).unwrap();
+ let applied =
+ s.active_sequence().unwrap().track(track).unwrap().transitions.iter().find(|t| Some(t.id.0) == result["transition"].as_u64()).unwrap();
+ assert_eq!((applied.start, applied.duration, applied.from, applied.to), (planned.start, planned.duration, planned.from, planned.to));
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.project.to_json(), before);
+ s.execute("edit.redo", json!({})).unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ }
+ }
+ assert!(preview_transition(&s, &json!({"effect": effect, "clip": u64::MAX}), kind).is_err());
+ let track = s.active_sequence().unwrap().tracks(kind)[0].id;
+ std::sync::Arc::make_mut(&mut s.project).sequence_mut(s.state.active_sequence.unwrap()).unwrap().track_mut(track).unwrap().locked = true;
+ assert!(preview_transition(&s, &json!({"effect": effect, "clip": s.active_sequence().unwrap().track(track).unwrap().items[0].id.0}), kind).is_err());
+ }
+}
+
fn first_v1_clip(s: &Session) -> u64 {
s.active_sequence().unwrap().video_tracks[0].items[0].id.0
}
diff --git a/crates/ui-egui/README.md b/crates/ui-egui/README.md
index 21ff94e6d..9a0fbf1ed 100644
--- a/crates/ui-egui/README.md
+++ b/crates/ui-egui/README.md
@@ -3,6 +3,18 @@
The egui frontend draws panels and dialogs, and dispatches project changes through the engine.
Interactive controls keep stable automation ids regardless of the interface language.
+## Transition drop previews
+
+Dragging a video or audio transition over a compatible clip shows its actual time span, the
+selected cut and an In/Out label. Shared cuts center the span; isolated edges use a one-sided
+span. The preview uses the engine's read-only transition planner, including Timeline duration
+preferences, and release dispatches `effects.apply` with the same edge. Locked tracks and
+incompatible clip types show no valid transition preview. Ordinary effects retain their clip
+outline. `timeline.transitionDropPreview` exposes the span and edge to automation.
+
+`transition_drop_ui` covers both edges of short video/audio clips, hover without project edits,
+the committed span and undo. Set `FILMCRAFT_UI_SNAPSHOT_DIR` to render screenshots with wgpu.
+
## Localisation
Edit > Language offers English, Japanese and Spanish. The language is stored in the engine's
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index a39dc82ea..17cd5b49d 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
+ In Entrada
+ Out Salida
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 811a75eea..bf0830920 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -2164,16 +2164,40 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
&& let Some(row) = layout.rows.iter().find(|r| r.track == tid)
{
{
- let r = Rect::from_min_max(pos2(layout.x_of(it.start), row.rect.min.y), pos2(layout.x_of(it.end()), row.rect.max.y));
- ui.painter().rect_stroke(r, 3.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
+ let transition_kind = filmcraft_project::find_effect(&effect).and_then(|d| match d.kind {
+ filmcraft_project::EffectKind::VideoTransition => Some(TrackKind::Video),
+ filmcraft_project::EffectKind::AudioTransition => Some(TrackKind::Audio),
+ _ => None,
+ });
+ let edge = if p.x - layout.x_of(it.start) < layout.x_of(it.end()) - p.x { "in" } else { "out" };
+ let params = json!({"effect": effect, "clip": clip.0, "edge": edge});
+ if let Some(kind) = transition_kind {
+ if let Ok((_, tr)) = filmcraft_engine::commands::preview_transition(&app.session, &params, kind) {
+ let r = Rect::from_min_max(pos2(layout.x_of(tr.start), row.rect.min.y + 1.0), pos2(layout.x_of(tr.end()), row.rect.max.y - 1.0));
+ let painter = ui.painter().with_clip_rect(layout.content);
+ painter.rect_filled(r, 2.0, app.tokens.accent.gamma_multiply(0.35));
+ paint_hatch(&painter, r.intersect(layout.content));
+ painter.rect_stroke(r, 2.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
+ let cut = if edge == "in" { it.start } else { it.end() };
+ let x = layout.x_of(cut);
+ painter.line_segment([pos2(x, r.top()), pos2(x, r.bottom())], Stroke::new(3.0, app.tokens.accent));
+ // Keep the edge label readable even when the clip/transition is only a few pixels wide.
+ let label = if edge == "in" { tl!("In") } else { tl!("Out") };
+ let label_width = painter.layout_no_wrap(label.to_string(), Tokens::ui(11.0), app.tokens.accent).size().x + 8.0;
+ let label_rect = Rect::from_center_size(pos2(p.x, row.rect.top() + 10.0), vec2(label_width, 15.0));
+ painter.rect_filled(label_rect, 2.0, app.tokens.panel_bg);
+ painter.text(label_rect.center(), Align2::CENTER_CENTER, label, Tokens::ui(11.0), app.tokens.accent);
+ app.auto.add("timeline.transitionDropPreview", r.intersect(layout.content), edge);
+ }
+ } else {
+ let r = Rect::from_min_max(pos2(layout.x_of(it.start), row.rect.min.y), pos2(layout.x_of(it.end()), row.rect.max.y));
+ ui.painter().rect_stroke(r, 3.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
+ }
if ctx.input(|i| i.pointer.any_released()) {
- let is_transition = filmcraft_project::find_effect(&effect)
- .is_some_and(|d| matches!(d.kind, filmcraft_project::EffectKind::VideoTransition | filmcraft_project::EffectKind::AudioTransition));
let r = if let Some(name) = effect.strip_prefix("preset:") {
app.session.execute("presets.apply", json!({"preset": name, "clips": [clip.0]}))
- } else if is_transition {
- let edge = if p.x - layout.x_of(it.start) < layout.x_of(it.end()) - p.x { "in" } else { "out" };
- app.session.execute("effects.apply", json!({"effect": effect, "clip": clip.0, "edge": edge}))
+ } else if transition_kind.is_some() {
+ app.session.execute("effects.apply", params)
} else {
app.session.execute("effects.apply", json!({"effect": effect, "clips": [clip.0]}))
};
diff --git a/crates/ui-egui/tests/transition_drop_ui.rs b/crates/ui-egui/tests/transition_drop_ui.rs
new file mode 100644
index 000000000..e26133472
--- /dev/null
+++ b/crates/ui-egui/tests/transition_drop_ui.rs
@@ -0,0 +1,141 @@
+//! Transition drag feedback: actual span and edge, no edit until release, one undo step.
+use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2};
+use egui_kittest::Harness;
+use filmcraft_engine::{Session, commands::preview_transition};
+use filmcraft_project::TrackKind;
+use filmcraft_ui_egui::FilmcraftApp;
+use serde_json::json;
+
+fn step(h: &mut Harness<'static, FilmcraftApp>) {
+ let ctx = h.ctx.clone();
+ let mut raw = std::mem::take(h.input_mut());
+ eframe::App::raw_input_hook(h.state_mut(), &ctx, &mut raw);
+ *h.input_mut() = raw;
+ ctx.request_repaint();
+ h.step();
+}
+
+fn pointer(h: &mut Harness<'static, FilmcraftApp>, pos: Pos2, pressed: Option<bool>) {
+ h.input_mut().events.push(Event::PointerMoved(pos));
+ if pressed == Some(true) {
+ step(h);
+ }
+ if let Some(pressed) = pressed {
+ h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
+ }
+ step(h);
+}
+
+fn rect(h: &Harness<'static, FilmcraftApp>, id: &str) -> Rect {
+ let [x, y, w, height] = h.state().auto.elements.iter().find(|e| e.id == id).unwrap_or_else(|| panic!("missing {id}")).rect;
+ Rect::from_min_size(pos2(x, y), vec2(w, height))
+}
+
+fn harness(effect: &str) -> Harness<'static, FilmcraftApp> {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ s.execute("file.newSequence", json!({"name":"Transition drops","fps":24})).unwrap();
+ let rate = s.sequence_rate();
+ // A short clip touching a longer clip: either edge must be distinguishable on screen.
+ for (at, frames) in [(0, 48), (48, 6)] {
+ s.execute("timeline.place", json!({"item":5,"time":rate.tick_of(at).0,"duration":rate.tick_of(frames).0})).unwrap();
+ }
+ let mut app = FilmcraftApp::new(s);
+ app.set_workspace("Effects");
+ app.ui.effects_search = effect.to_string();
+ let mut builder = Harness::builder().with_size(vec2(1600.0, 980.0)).with_max_steps(10_000);
+ if std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").is_some() {
+ builder = builder.wgpu();
+ }
+ let mut h = builder.build_eframe(move |_cc| app);
+ for _ in 0..4 {
+ step(&mut h);
+ }
+ // Opening the new sequence restores its own view; set the test zoom after that initial fit.
+ h.state_mut().ui.timeline.pps = 60.0;
+ h.state_mut().ui.timeline.target_pps = 60.0;
+ h.state_mut().ui.timeline.fit_pending = false;
+ step(&mut h);
+ h
+}
+
+#[test]
+fn transition_drag_previews_both_edges_of_short_clips_and_commits_that_span() {
+ for (kind, effect, name) in [(TrackKind::Video, "cross_dissolve", "Cross Dissolve"), (TrackKind::Audio, "constant_power", "Constant Power")] {
+ let mut h = harness(name);
+ let clip = h.state().session.active_sequence().unwrap().tracks(kind)[0].items[1].id;
+ let clip_rect = rect(&h, &format!("timeline.clip.{}", clip.0));
+ let from = rect(&h, &format!("effects.item.{effect}")).center();
+ let before = h.state().session.project.to_json();
+ pointer(&mut h, from, Some(true));
+ pointer(&mut h, from + vec2(0.0, 10.0), None);
+ for (edge, fraction) in [("in", 0.2), ("out", 0.8)] {
+ let to = pos2(clip_rect.left() + clip_rect.width() * fraction, clip_rect.center().y);
+ pointer(&mut h, to, None);
+ let preview = h.state().auto.elements.iter().find(|e| e.id == "timeline.transitionDropPreview").expect("transition preview while dragging");
+ assert_eq!(preview.label, edge);
+ assert_eq!(h.state().session.project.to_json(), before, "hover must not edit");
+ let (_, planned) = preview_transition(&h.state().session, &json!({"effect":effect,"clip":clip.0,"edge":edge}), kind).unwrap();
+ let rate = h.state().session.sequence_rate();
+ let short = &h.state().session.active_sequence().unwrap().tracks(kind)[0].items[1];
+ let px_per_tick = clip_rect.width() / short.duration.0 as f32;
+ let expected_left = clip_rect.left() + (planned.start - short.start).0 as f32 * px_per_tick;
+ let content = rect(&h, "timeline.tracks");
+ let expected_right = (expected_left + planned.duration.0 as f32 * px_per_tick).min(content.right());
+ let expected_left = expected_left.max(content.left());
+ assert!((preview.rect[0] - expected_left).abs() < 1.0);
+ assert!(
+ (preview.rect[2] - (expected_right - expected_left)).abs() < 1.0,
+ "{kind:?} {edge}: preview {:?}, clip {clip_rect:?}, planned {planned:?}, pps {}",
+ preview.rect,
+ h.state().ui.timeline.pps
+ );
+ assert_eq!(
+ planned.duration,
+ if kind == TrackKind::Video {
+ h.state().session.prefs.timeline.video_transition_duration(rate)
+ } else {
+ h.state().session.prefs.timeline.audio_transition_duration(rate)
+ }
+ );
+ if let Some(dir) = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR") {
+ let dir = std::path::PathBuf::from(dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ h.render().unwrap().save(dir.join(format!("transition-{effect}-{edge}.png"))).unwrap();
+ }
+ }
+ let to = pos2(clip_rect.left() + clip_rect.width() * 0.8, clip_rect.center().y);
+ let (_, planned) = preview_transition(&h.state().session, &json!({"effect":effect,"clip":clip.0,"edge":"out"}), kind).unwrap();
+ pointer(&mut h, to, Some(false));
+ let applied = h.state().session.active_sequence().unwrap().tracks(kind)[0].transitions.last().unwrap();
+ assert_eq!((applied.start, applied.duration, applied.from, applied.to), (planned.start, planned.duration, planned.from, planned.to));
+ h.state_mut().session.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(h.state().session.project.to_json(), before);
+ step(&mut h);
+ assert!(!h.state().auto.elements.iter().any(|e| e.id == "timeline.transitionDropPreview"));
+ }
+}
+
+#[test]
+fn incompatible_and_locked_tracks_do_not_offer_a_transition_preview() {
+ for locked in [false, true] {
+ let mut h = harness("Cross Dissolve");
+ let kind = if locked { TrackKind::Video } else { TrackKind::Audio };
+ let q = h.state().session.active_sequence().unwrap();
+ let (track, clip) = (q.tracks(kind)[0].id, q.tracks(kind)[0].items[1].id);
+ if locked {
+ let s = &mut h.state_mut().session;
+ std::sync::Arc::make_mut(&mut s.project).sequence_mut(s.state.active_sequence.unwrap()).unwrap().track_mut(track).unwrap().locked = true;
+ step(&mut h);
+ }
+ let to = rect(&h, &format!("timeline.clip.{}", clip.0)).center();
+ let from = rect(&h, "effects.item.cross_dissolve").center();
+ let before = h.state().session.project.to_json();
+ pointer(&mut h, from, Some(true));
+ pointer(&mut h, from + vec2(0.0, 10.0), None);
+ pointer(&mut h, to, None);
+ assert!(!h.state().auto.elements.iter().any(|e| e.id == "timeline.transitionDropPreview"));
+ pointer(&mut h, to, Some(false));
+ assert_eq!(h.state().session.project.to_json(), before);
+ }
+}