Skip to content

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

fix: 新規トラック移動のリンクと編集履歴を保持 (#1187)

Ikki Nishiharaaa9d78cd9c99
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index ce502fcec..a1392b8cc 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -345,8 +345,23 @@ pub(crate) fn item_p(p: &Value, k: &str) -> Option<ItemId> {
fn move_clips(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "timeline.move";
let mut listed: Vec<(ClipId, TrackId, Tick)> = Vec::new();
+ let mut new_moves = Vec::new();
for m in p.get("moves").and_then(Value::as_array).into_iter().flatten() {
- let track = track_p(s, m, "track", CMD)?;
+ let track = if str_p(m, "track").is_some_and(|t| t.eq_ignore_ascii_case("new")) {
+ let clip = clip_p(m, "clip").ok_or_else(|| bad(CMD, "new track needs a clip"))?;
+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
+ let (source, _) = q.find_item(clip).ok_or(edit::EditError::NoItem(clip))?;
+ if q.track(source).is_some_and(|t| t.locked) {
+ return Err(edit::EditError::Locked.into());
+ }
+ if m.get("time").and_then(Value::as_i64).is_none() {
+ return Err(bad(CMD, "new track needs a time"));
+ }
+ new_moves.push((clip, source));
+ Some(source)
+ } else {
+ track_p(s, m, "track", CMD)?
+ };
if let (Some(clip), Some(track), Some(time)) = (clip_p(m, "clip"), track, m.get("time").and_then(Value::as_i64)) {
listed.push((clip, track, Tick(time)));
}
@@ -391,16 +406,48 @@ fn move_clips(s: &mut Session, p: &Value) -> Result<Value> {
q.into_iter().flat_map(|q| q.all_tracks()).flat_map(|t| t.items.iter().map(move |i| (i.id.0, t.id, i.start, i.end(), i.item))).collect()
};
let before = spots(s);
+ // Allocate destinations in the same transaction as the move: an invalid edit leaves
+ // neither empty tracks nor history entries. Each source track keeps its clips together.
+ let prepare = |q: &mut filmcraft_project::Sequence, ctx: &mut edit::EditCtx<'_>| -> Result<Vec<(ClipId, TrackId, Tick)>> {
+ let sources: Vec<_> = q.all_tracks().filter(|t| new_moves.iter().any(|m| m.1 == t.id)).map(|t| (t.id, t.kind, t.channels)).collect();
+ for kind in [TrackKind::Video, TrackKind::Audio] {
+ let added = sources.iter().filter(|s| s.1 == kind).count();
+ if added > 0 && q.tracks(kind).len().saturating_add(added) > crate::sequence_tools::MAX_TRACKS {
+ return Err(bad(CMD, "new tracks exceed the sequence track limit"));
+ }
+ }
+ let mut destinations = Vec::new();
+ for (source, kind, channels) in sources {
+ let tracks = if kind == TrackKind::Video { &mut q.video_tracks } else { &mut q.audio_tracks };
+ let prefix = if kind == TrackKind::Video { "Video" } else { "Audio" };
+ let id = TrackId(ctx.alloc());
+ let mut track = Track::new(id, kind, format!("{prefix} {}", tracks.len() + 1));
+ track.channels = channels;
+ tracks.push(track);
+ destinations.push((source, id));
+ }
+ Ok(moves
+ .iter()
+ .map(|&(clip, track, time)| {
+ let dest = new_moves.iter().find(|m| m.0 == clip).and_then(|m| destinations.iter().find(|d| d.0 == m.1)).map_or(track, |d| d.1);
+ (clip, dest, time)
+ })
+ .collect())
+ };
let copied = if copy {
let label = if ins { "Copy (Insert)" } else { "Copy" };
s.edit_sequence(label, |q, ctx, st| {
- let ids = edit::copy_items(q, &moves, ins, ctx)?;
+ let destinations = prepare(q, ctx)?;
+ let ids = edit::copy_items(q, &destinations, ins, ctx)?;
st.selection = ids.clone();
st.transition_selection.clear();
Ok(ids)
})?
} else {
- s.edit_sequence(if ins { "Move (Insert)" } else { "Move" }, |q, ctx, _| Ok(edit::move_items(q, &moves, ins, ctx)?))?;
+ s.edit_sequence(if ins { "Move (Insert)" } else { "Move" }, |q, ctx, _| {
+ let destinations = prepare(q, ctx)?;
+ Ok(edit::move_items(q, &destinations, ins, ctx)?)
+ })?;
Vec::new()
};
// An overwrite shortens, splits or removes whatever already sits where a clip lands, and a
@@ -2528,12 +2575,7 @@ fn build() -> Vec<CommandSpec> {
None,
r#"{"moves":[{"clip":id,"track":id|"V2"|"new" (after the last of its kind),"time":ticks}],"insert":bool,"linked":bool?,"copy":bool?}"#,
has_seq,
- |s, p| {
- if crate::sequence_tools::move_wants_new_track(p) {
- return crate::sequence_tools::move_to_new_tracks(s, p);
- }
- move_clips(s, p)
- }
+ move_clips
),
cmd!(
"timeline.trim",
diff --git a/crates/engine/src/sequence_tools.rs b/crates/engine/src/sequence_tools.rs
index f871f0118..90716d2fc 100644
--- a/crates/engine/src/sequence_tools.rs
+++ b/crates/engine/src/sequence_tools.rs
@@ -774,65 +774,6 @@ pub(crate) fn place_on_new_tracks(s: &mut Session, p: &Value) -> Result<Value> {
}
}
-/// `timeline.move` names `"new"` as the `track` of a move.
-pub(crate) fn move_wants_new_track(p: &Value) -> bool {
- p.get("moves").and_then(Value::as_array).is_some_and(|m| m.iter().any(is_new_move))
-}
-
-/// One move of `timeline.move` with `"track":"new"`.
-fn is_new_move(m: &Value) -> bool {
- m.get("track").and_then(Value::as_str).is_some_and(|v| v.eq_ignore_ascii_case("new"))
-}
-
-/// `timeline.move` with `"track":"new"` on some moves (#1104: a clip dragged into the empty space
-/// above the top video track or below the last audio track): one track is added after the last one
-/// of each kind the `"new"` clips come from, they all land on it, and the track and the move are
-/// one undo step. When the move fails, the new tracks go away again.
-pub(crate) fn move_to_new_tracks(s: &mut Session, p: &Value) -> Result<Value> {
- let cmd = "timeline.move";
- let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
- let (mut new_v, mut new_a) = (false, false);
- for m in p.get("moves").and_then(Value::as_array).into_iter().flatten().filter(|m| is_new_move(m)) {
- let clip = crate::commands::clip_p(m, "clip").ok_or_else(|| bad(cmd, "need `clip` in each move"))?;
- let (track, _) = q.find_item(clip).ok_or_else(|| bad(cmd, "no such clip"))?;
- if q.video_tracks.iter().any(|t| t.id == track) {
- new_v = true;
- } else {
- new_a = true;
- }
- }
- let added = add_tracks(s, &json!({"video": u64::from(new_v), "audio": u64::from(new_a)}))?;
- let mark = s.history.undo.len();
- let (video, audio) = (added.get("video").and_then(|v| v.get(0)).cloned(), added.get("audio").and_then(|v| v.get(0)).cloned());
- let mut moves = p.get("moves").and_then(Value::as_array).cloned().unwrap_or_default();
- for m in moves.iter_mut().filter(|m| is_new_move(m)) {
- let on_video = crate::commands::clip_p(m, "clip")
- .and_then(|c| s.active_sequence().and_then(|q| q.find_item(c).map(|(t, _)| q.video_tracks.iter().any(|v| v.id == t))))
- .unwrap_or(true);
- m["track"] = if on_video { video.clone() } else { audio.clone() }.unwrap_or(Value::Null);
- }
- let mut q = p.clone();
- q["moves"] = Value::Array(moves);
- let run = crate::commands::find(cmd).ok_or_else(|| EngineError::UnknownCommand(cmd.into()))?.run;
- match run(s, &q) {
- Ok(v) => {
- // the new tracks and the move are one undo step
- if mark >= 1
- && s.history.undo.len() == mark + 1
- && let (Some((label, _)), Some((_, before))) = (s.history.undo.pop(), s.history.undo.pop())
- {
- s.history.undo.push((label, before));
- }
- Ok(v)
- }
- Err(e) => {
- s.undo();
- s.history.redo.pop();
- Err(e)
- }
- }
-}
-
fn delete_tracks(s: &mut Session, p: &Value) -> Result<Value> {
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
diff --git a/crates/engine/src/timeline_move_tests.rs b/crates/engine/src/timeline_move_tests.rs
index 565edd55b..f6aa640ff 100644
--- a/crates/engine/src/timeline_move_tests.rs
+++ b/crates/engine/src/timeline_move_tests.rs
@@ -299,3 +299,116 @@ fn copy_leaves_the_originals_and_links_the_copies() {
assert!(r.is_err());
assert_eq!(s.active_sequence().unwrap().all_tracks().map(|t| t.items.len()).sum::<usize>(), 2);
}
+
+#[test]
+fn new_track_moves_and_copies_are_one_atomic_edit() {
+ for copy in [false, true] {
+ let mut s = demo();
+ let (vt, v, at, a) = last_pair(&s);
+ let before = s.project.clone();
+ let count = s.history.undo.len();
+ let q = s.active_sequence().unwrap();
+ let counts = (q.video_tracks.len(), q.audio_tracks.len());
+ let r = s
+ .execute(
+ "timeline.move",
+ json!({"moves":[{"clip":v.id.0,"track":"new","time":v.start.0},{"clip":a.id.0,"track":"new","time":a.start.0}],"linked":false,"copy":copy}),
+ )
+ .unwrap();
+ let q = s.active_sequence().unwrap();
+ assert_eq!((q.video_tracks.len(), q.audio_tracks.len()), (counts.0 + 1, counts.1 + 1));
+ let new_v = q.video_tracks.last().unwrap();
+ let new_a = q.audio_tracks.last().unwrap();
+ assert_eq!(new_a.channels, before.sequence(s.state.active_sequence.unwrap()).unwrap().track(at).unwrap().channels);
+ assert_eq!((new_v.items[0].item, new_a.items[0].item), (v.item, a.item));
+ assert_eq!((new_v.items[0].start, new_a.items[0].start), (v.start, a.start));
+ if copy {
+ assert_eq!(state(&s, v.id), (vt, v.start));
+ assert_eq!(state(&s, a.id), (at, a.start));
+ assert_ne!(new_v.items[0].id, v.id);
+ assert!(new_v.items[0].link.is_some() && new_v.items[0].link == new_a.items[0].link);
+ assert_ne!(new_v.items[0].link, v.link);
+ assert_eq!(s.state.selection.len(), 2);
+ assert_eq!(r["copied"].as_array().unwrap().len(), 2);
+ } else {
+ assert_eq!(state(&s, v.id), (new_v.id, v.start));
+ assert_eq!(state(&s, a.id), (new_a.id, a.start));
+ }
+ q.check().unwrap();
+ assert_eq!(s.history.undo.len(), count + 1);
+ let after = s.project.clone();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, *before);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(*s.project, *after);
+ }
+}
+
+#[test]
+fn new_track_group_keeps_clips_from_the_same_source_together() {
+ let mut s = demo();
+ let q = s.active_sequence().unwrap();
+ let clips = q.video_tracks[0].items[..2].to_vec();
+ let tracks = q.video_tracks.len();
+ let before = s.project.clone();
+ let moves: Vec<_> = clips.iter().map(|c| json!({"clip":c.id.0,"track":"new","time":c.start.0})).collect();
+ s.execute("timeline.move", json!({"moves":moves,"linked":false})).unwrap();
+ let q = s.active_sequence().unwrap();
+ assert_eq!(q.video_tracks.len(), tracks + 1);
+ let t = q.video_tracks.last().unwrap();
+ assert_eq!(t.items, clips);
+ q.check().unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, *before);
+}
+
+#[test]
+fn refused_new_track_moves_preserve_document_and_both_history_stacks() {
+ let mut s = demo();
+ let (_, v, _, _) = last_pair(&s);
+ s.execute("timeline.setTrack", json!({"track":"V1","locked":true})).unwrap();
+ for moves in [
+ json!([{"clip":v.id.0,"track":"new","time":v.start.0}]),
+ json!([{"clip":u64::MAX,"track":"new","time":0}]),
+ json!([{"clip":v.id.0,"track":"new","time":i64::MAX}]),
+ json!([{"clip":v.id.0,"track":"new","time":0},{"clip":u64::MAX,"track":"V2","time":0}]),
+ ] {
+ let before = s.project.clone();
+ let history = s.execute("history.list", json!({})).unwrap();
+ assert!(s.execute("timeline.move", json!({"moves":moves,"linked":false})).is_err());
+ assert_eq!(*s.project, *before);
+ assert_eq!(s.execute("history.list", json!({})).unwrap(), history);
+ }
+ s.execute("edit.undo", json!({})).unwrap();
+ let before = s.project.clone();
+ let history = s.execute("history.list", json!({})).unwrap();
+ assert!(!history["redo"].as_array().unwrap().is_empty());
+ for moves in [
+ json!([{"clip":v.id.0,"track":"new","time":0},{"clip":u64::MAX,"track":"V2","time":0}]),
+ json!([{"clip":v.id.0,"track":"new","time":i64::MAX}]),
+ json!([{"clip":v.id.0,"track":"new"}]),
+ json!([{"clip":v.id.0,"track":"new","time":"invalid"}]),
+ ] {
+ assert!(s.execute("timeline.move", json!({"moves":moves,"linked":false})).is_err());
+ assert_eq!(*s.project, *before);
+ assert_eq!(s.execute("history.list", json!({})).unwrap(), history);
+ }
+}
+
+#[test]
+fn new_track_moves_respect_the_track_limit() {
+ let mut s = demo();
+ let (_, v, _, _) = last_pair(&s);
+ s.edit_sequence("Limit fixture", |q, ctx, _| {
+ while q.video_tracks.len() < crate::sequence_tools::MAX_TRACKS {
+ q.video_tracks.push(filmcraft_project::Track::new(TrackId(ctx.alloc()), filmcraft_project::TrackKind::Video, "Limit".into()));
+ }
+ Ok(())
+ })
+ .unwrap();
+ let before = s.project.clone();
+ let history = s.execute("history.list", json!({})).unwrap();
+ assert!(s.execute("timeline.move", json!({"moves":[{"clip":v.id.0,"track":"new","time":v.start.0}],"linked":false})).is_err());
+ assert_eq!(*s.project, *before);
+ assert_eq!(s.execute("history.list", json!({})).unwrap(), history);
+}
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index ac4caf535..65fcc9662 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -577,6 +577,25 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
+ // An existing clip dragged past the outer row previews its new destination (#1187).
+ if let Some(Drag::Move { clips, offset, new_track: Some((kind, band)), .. }) = app.tl.drag.clone() {
+ let preview = painter.with_clip_rect(band.intersect(content));
+ for clip in clips {
+ if let Some((track, it)) = seq.find_item(clip)
+ && seq.track(track).is_some_and(|t| t.kind == kind)
+ {
+ let start = (it.start + offset).max(Tick::ZERO);
+ let body = Rect::from_min_max(pos2(layout.x_of(start), band.min.y + 1.0), pos2(layout.x_of(start + it.duration), band.max.y - 1.0));
+ preview.rect_filled(body, 3.0, t.accent.gamma_multiply(0.4));
+ preview.rect_stroke(body, 3.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
+ if body.height() >= 20.0 {
+ preview.text(body.left_top() + vec2(4.0, 2.0), Align2::LEFT_TOP, &it.name, Tokens::ui(11.0), t.text);
+ }
+ app.auto.add(&format!("timeline.newTrackPreview.{}", clip.0), body.intersect(band), &it.name);
+ }
+ }
+ }
+
// ---- track headers
draw_headers(app, ui, seq, &rows, rect, vclip, aclip, &t);
// divider between video and audio
@@ -1784,6 +1803,7 @@ fn preview_drag(app: &FilmcraftApp, seq: &Sequence, out: &mut HashMap<ClipId, (T
};
let Some(d) = &app.tl.drag else { return };
match d {
+ Drag::Move { new_track: Some(_), .. } => {}
Drag::Move { clips, offset, track_delta, .. } => {
for c in clips {
if let Some((tid, it)) = seq.find_item(*c) {
@@ -2456,16 +2476,13 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
(Some(c), Some(s)) if c.kind == s.kind => c.index as i32 - s.index as i32,
_ => 0,
};
- // #1104: past the last track of the clips' kind, a new track (only for clips of one track)
- let new_track = start_row.filter(|_| clips.iter().all(|c| seq.find_item(*c).is_some_and(|(t, _)| t == start_track))).and_then(|s| {
- let (vh, ah) = (app.ui.timeline.video_track_h, app.ui.timeline.audio_track_h);
- new_track_at(seq, layout, p.y, vh, ah).filter(|(kind, _)| *kind == s.kind)
- });
- if let Some((_, band)) = new_track {
- let (x0, x1) = (layout.x_of((first + offset).max(Tick::ZERO)), layout.x_of((last + offset).max(Tick::ZERO)));
- let r = Rect::from_min_max(pos2(x0, band.min.y + 1.0), pos2(x1, band.max.y - 1.0));
- ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside);
- }
+ // A linked or multitrack selection gets one destination per source track.
+ let new_track = start_row
+ .filter(|_| clips.iter().all(|c| seq.find_item(*c).is_some_and(|(tid, _)| seq.track(tid).is_some_and(|t| !t.locked))))
+ .and_then(|s| {
+ let (vh, ah) = (app.ui.timeline.video_track_h, app.ui.timeline.audio_track_h);
+ new_track_at(seq, layout, p.y, vh, ah).filter(|(kind, _)| *kind == s.kind)
+ });
Some(Drag::Move { clips, grab_tick, start_track, offset, track_delta, new_track, copy: mods.alt })
}
Drag::Trim { clip, edge, mode, from, .. } => seq.find_item(clip).map(|(_, it)| {
diff --git a/crates/ui-egui/tests/timeline_trim_ui.rs b/crates/ui-egui/tests/timeline_trim_ui.rs
index c68d56129..23e12e859 100644
--- a/crates/ui-egui/tests/timeline_trim_ui.rs
+++ b/crates/ui-egui/tests/timeline_trim_ui.rs
@@ -390,3 +390,94 @@ fn dragging_in_the_trim_monitor_trims_without_hanging() {
assert!(e1 < e0, "the Out edge moved in by {} frames", frames.abs());
assert!((6..=14).contains(&-frames), "about 11 frames expected for 60 px at 6 px/frame, moved {}", frames.abs());
}
+
+fn move_existing_clip_to_a_new_track(audio: bool, linked: bool) {
+ let mut d = Driver::demo();
+ d.exec("sequence.linkedSelection", json!({"on": linked}));
+ d.exec("sequence.snap", json!({"on": false}));
+ d.ok("ui.set", json!({"timeline":{"videoTrackHeight":32,"audioTrackHeight":32}}));
+ d.frames(6);
+ let q = d.app().session.active_sequence().unwrap();
+ let tracks = if audio { &q.audio_tracks } else { &q.video_tracks };
+ let count = tracks.len();
+ let clip = tracks[0].items[0].id;
+ let original = q.find_item(clip).unwrap().1.clone();
+ let other = if audio { &q.video_tracks } else { &q.audio_tracks };
+ let other_count = other.len();
+ let partner = linked.then(|| {
+ assert!(original.link.is_some());
+ other.iter().flat_map(|t| &t.items).find(|i| i.link == original.link).unwrap().clone()
+ });
+ let layout = d.app().tl.layout.as_ref().unwrap();
+ let row = layout.rows.iter().find(|r| r.track == tracks[0].id).unwrap();
+ let outer = layout.rows.iter().find(|r| r.track == tracks.last().unwrap().id).unwrap();
+ let from = egui::pos2(layout.x_of(original.start + filmcraft_time::Tick(original.duration.0 / 2)), row.rect.min.y + 8.0);
+ let to = egui::pos2(from.x, if audio { outer.rect.max.y + 8.0 } else { outer.rect.min.y - 8.0 });
+ assert!(layout.content.contains(to));
+ assert!(layout.row_at(to.y).is_none());
+ let before = d.app().session.project.clone();
+ let undo = d.app().session.history.undo.len();
+ d.harness.input_mut().events.push(egui::Event::PointerMoved(from));
+ d.frames(1);
+ d.harness.input_mut().events.push(egui::Event::PointerButton {
+ pos: from,
+ button: egui::PointerButton::Primary,
+ pressed: true,
+ modifiers: Default::default(),
+ });
+ d.frames(1);
+ for i in 1..=12 {
+ d.harness.input_mut().events.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 12.0)));
+ d.frames(1);
+ }
+ // A frame updates the gesture, then the next frame paints its destination.
+ d.frames(2);
+ let preview = d.ok("ui.elements", json!({"prefix":format!("timeline.newTrackPreview.{}",clip.0)}));
+ assert_eq!(preview.as_array().unwrap().len(), 1, "new destination is shown during the drag");
+ assert_eq!(*d.app().session.project, *before);
+ assert_eq!(d.app().session.history.undo.len(), undo);
+ d.harness.input_mut().events.push(egui::Event::PointerButton {
+ pos: to,
+ button: egui::PointerButton::Primary,
+ pressed: false,
+ modifiers: Default::default(),
+ });
+ d.frames(2);
+ let q = d.app().session.active_sequence().unwrap();
+ let tracks = if audio { &q.audio_tracks } else { &q.video_tracks };
+ assert_eq!(tracks.len(), count + 1, "drop creates a new outer track");
+ assert_eq!(q.find_item(clip).unwrap().0, tracks.last().unwrap().id);
+ assert_eq!(q.find_item(clip).unwrap().1, &original);
+ let other = if audio { &q.video_tracks } else { &q.audio_tracks };
+ assert_eq!(other.len(), other_count + usize::from(linked));
+ if let Some(partner) = partner {
+ assert_eq!(q.find_item(partner.id).unwrap().0, other.last().unwrap().id);
+ assert_eq!(q.find_item(partner.id).unwrap().1, &partner);
+ }
+ assert_eq!(d.app().session.history.undo.len(), undo + 1);
+ let after = d.app().session.project.clone();
+ d.exec("edit.undo", json!({}));
+ assert_eq!(*d.app().session.project, *before);
+ d.exec("edit.redo", json!({}));
+ assert_eq!(*d.app().session.project, *after);
+}
+
+#[test]
+fn existing_video_clip_drag_above_tracks_adds_a_track() {
+ move_existing_clip_to_a_new_track(false, false);
+}
+
+#[test]
+fn existing_audio_clip_drag_below_tracks_adds_a_track() {
+ move_existing_clip_to_a_new_track(true, false);
+}
+
+#[test]
+fn linked_video_drag_adds_video_and_audio_tracks() {
+ move_existing_clip_to_a_new_track(false, true);
+}
+
+#[test]
+fn linked_audio_drag_adds_audio_and_video_tracks() {
+ move_existing_clip_to_a_new_track(true, true);
+}