Skip to content

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

Merge upstream/main into feat/multi-select-drag

awea078906ac1d3
diff --cc crates/engine/src/commands.rs
index 541387b38,90ed841de..c46230b04
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@@ -664,118 -738,6 +738,119 @@@ pub(crate) fn ensure_audio_tracks(p: &m
Ok(p.sequence(seq_id).map(|q| q.audio_tracks.iter().map(|t| t.id).collect()).unwrap_or_default())
}
+/// `timeline.place` for one item (`item`).
+fn place_one(s: &mut Session, p: &Value) -> Result<Value> {
+ if crate::sequence_tools::wants_new_track(p) {
+ return crate::sequence_tools::place_on_new_tracks(s, p);
+ }
+ let stream_flag = |key: &str| match p.get(key) {
+ None => Ok(true),
+ Some(Value::Bool(v)) => Ok(*v),
+ _ => Err(bad("timeline.place", format!("`{key}` must be a boolean"))),
+ };
+ let (video, audio) = (stream_flag("video")?, stream_flag("audio")?);
+ if !video && !audio {
+ return Err(bad("timeline.place", "enable video, audio, or both"));
+ }
+ let item = item_p(p, "item").ok_or_else(|| bad("timeline.place", "need `item`"))?;
- let at = time_p(s, p, "").unwrap_or(s.playhead());
++ let at = sequence_time_p(s, p, "", "timeline.place")?.unwrap_or(s.playhead());
+ let tg = s.targeting();
+ let pi = s.project.item(item).ok_or_else(|| bad("timeline.place", "no such item"))?;
++ let (has_video, has_audio) = s.project.source_streams(item);
+ let is_audio = |t: TrackId| s.active_sequence().is_some_and(|q| q.audio_tracks.iter().any(|x| x.id == t));
+ // `track` is where the picture goes and `audioTrack` where the sound goes. A caller that
+ // names an audio track as `track` asks for the sound alone, on that track.
+ let (v, a) = match (track_p(s, p, "track", "timeline.place")?, track_p(s, p, "audioTrack", "timeline.place")?) {
+ (Some(t), Some(_)) if is_audio(t) => {
+ return Err(bad("timeline.place", "`track` names an audio track and `audioTrack` is given as well: name the sound's track once"));
+ }
+ (_, Some(t)) if !is_audio(t) => return Err(bad("timeline.place", "`audioTrack` names a video track")),
- (Some(t), None) if is_audio(t) && !pi.has_audio() => {
++ (Some(t), None) if is_audio(t) && !has_audio => {
+ return Err(bad("timeline.place", "`track` names an audio track and this item has no sound"));
+ }
+ (Some(t), None) if is_audio(t) => (None, Some(t)),
- (Some(_), None) if !pi.has_video() => {
++ (Some(_), None) if !has_video => {
+ return Err(bad("timeline.place", "`track` names a video track and this item has no picture: name an audio track"));
+ }
+ (v, a) => (v.or(tg.video_dest), a.or(tg.audio_dest)),
+ };
+ let v = v.filter(|_| video);
+ let a = a.filter(|_| audio);
- if p.get("video").is_some() && video && pi.has_video() && v.is_none() {
++ if p.get("video").is_some() && video && has_video && v.is_none() {
+ return Err(bad("timeline.place", "no video destination: add or enable a video track"));
+ }
- if p.get("audio").is_some() && audio && pi.has_audio() && a.is_none() {
++ if p.get("audio").is_some() && audio && has_audio && a.is_none() {
+ return Err(bad("timeline.place", "no audio destination: add or enable an audio track"));
+ }
+ let full = full_duration(s, pi);
+ let (mi, mo) = match &pi.kind {
+ ItemKind::Media(m) => (m.mark_in, m.mark_out.map(|o| o + pi.frame_rate().frame_duration())),
+ ItemKind::Subclip { range, .. } => (Some(range.start), Some(range.end())),
+ _ => (None, None),
+ };
+ let sin = p.get("sourceIn").and_then(Value::as_i64).map(Tick).or(mi).unwrap_or_default();
+ let dur = p.get("duration").and_then(Value::as_i64).map(Tick).unwrap_or_else(|| mo.unwrap_or(full) - sin);
+ let ids = place_item(s, item, TimeRange::new(sin, dur), at, v, a, bool_p(p, "insert").unwrap_or(false), "Place Clip", None)?;
+ Ok(json!({"clips": ids.iter().map(|c| c.0).collect::<Vec<_>>()}))
+}
+
+/// Most items one `timeline.place` with `items` takes: a larger list is refused, not cut.
+const MAX_PLACE_ITEMS: usize = 10_000;
+
+/// `timeline.place` for `items`: the first at the given time, each next one where the previous one
+/// ends, all as one undo step. `track`, `audioTrack`, `insert`, `video` and `audio` apply to every
+/// item; `sourceIn` and `duration` name one item's range, so they need `item`.
+fn place_items(s: &mut Session, p: &Value, items: &Value) -> Result<Value> {
+ let ids: Vec<ItemId> = items
+ .as_array()
+ .ok_or_else(|| bad("timeline.place", "`items` must be a list of item ids"))?
+ .iter()
+ .map(|v| v.as_u64().map(ItemId).ok_or_else(|| bad("timeline.place", "`items` must be a list of item ids")))
+ .collect::<Result<_>>()?;
+ if p.get("item").is_some() || p.get("sourceIn").is_some() || p.get("duration").is_some() {
+ return Err(bad("timeline.place", "give `item` or `items`, and no `sourceIn` or `duration` with `items`"));
+ }
+ if ids.is_empty() || ids.len() > MAX_PLACE_ITEMS {
+ return Err(bad("timeline.place", format!("`items` needs 1 to {MAX_PLACE_ITEMS} item ids")));
+ }
- let mut at = time_p(s, p, "").unwrap_or(s.playhead());
++ let mut at = sequence_time_p(s, p, "", "timeline.place")?.unwrap_or(s.playhead());
+ s.edit_group("Place Clips", |s| {
+ let mut placed = Vec::new();
+ // "new" adds a track for the first item only; the rest follow it on that track
+ let mut base = p.clone();
+ for item in ids {
+ let mut one = base.clone();
+ if let Some(o) = one.as_object_mut() {
+ o.remove("items");
+ for k in ["time", "frame", "seconds"] {
+ o.remove(k);
+ }
+ o.insert("item".into(), json!(item.0));
+ o.insert("time".into(), json!(at.0));
+ }
+ let r = place_one(s, &one)?;
+ let clips: Vec<ClipId> = r["clips"].as_array().map(|a| a.iter().filter_map(|c| c.as_u64().map(ClipId)).collect()).unwrap_or_default();
+ if crate::sequence_tools::wants_new_track(&base)
+ && let Some(q) = s.active_sequence()
+ {
+ for (key, audio) in [("track", false), ("audioTrack", true)] {
+ if base.get(key).and_then(Value::as_str).is_some_and(|v| v.eq_ignore_ascii_case("new"))
+ && let Some(t) =
+ clips.iter().find_map(|c| q.find_item(*c).map(|(t, _)| t).filter(|t| q.audio_tracks.iter().any(|x| x.id == *t) == audio))
+ {
+ base[key] = json!(t.0);
+ }
+ }
+ }
+ if let Some(end) = s.active_sequence().and_then(|q| clips.iter().filter_map(|c| q.find_item(*c).map(|(_, i)| i.end())).max()) {
+ at = end;
+ }
+ placed.push(json!(clips.iter().map(|c| c.0).collect::<Vec<_>>()));
+ }
+ Ok(json!({"clips": placed.iter().flat_map(|c| c.as_array().cloned().unwrap_or_default()).collect::<Vec<_>>(), "placed": placed}))
+ })
+}
+
/// Place a project item on the timeline (drag from Project, or Insert/Overwrite from source).
pub(crate) fn place_item(
s: &mut Session,
diff --cc crates/engine/src/lib.rs
index a86be68b8,2e265707c..48be6024c
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -833,47 -841,36 +841,77 @@@ impl Session
Ok(r)
}
+ /// Run several undoable edits as one undo step labelled `label`. If `f` fails, every edit it made
+ /// is rolled back and the history is as before.
+ pub fn edit_group<R>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<R>) -> Result<R> {
+ let (project, state, undo, redo, limit) =
+ (self.project.clone(), self.state.clone(), self.history.undo.len(), self.history.redo.clone(), self.history.limit);
+ // keep every step the group makes, however many, so the first one can be found afterwards
+ self.history.limit = usize::MAX;
+ // a panic inside the group must not leave the history unlimited: restore, then let it go on
+ let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
+ self.history.limit = limit;
+ let first = self.history.undo.get(undo).map(|e| e.1.clone());
+ let rolled_back = |s: &mut Session| {
+ s.history.undo.truncate(undo);
+ s.history.redo = redo.clone();
+ s.history.merge_key = None;
+ s.project = project.clone();
+ s.state = state.clone();
+ s.bump();
+ };
+ match (r, first) {
+ (Ok(Ok(v)), Some(first)) => {
+ self.history.undo.truncate(undo);
+ self.history.undo.push((label.to_string(), first));
+ if self.history.undo.len() > limit {
+ self.history.undo.remove(0);
+ }
+ self.history.merge_key = None;
+ Ok(v)
+ }
+ (Ok(Ok(v)), None) => Ok(v),
+ (Ok(Err(e)), _) => {
+ rolled_back(self);
+ Err(e)
+ }
+ (Err(panic), _) => {
+ rolled_back(self);
+ std::panic::resume_unwind(panic)
+ }
+ }
+ }
+
+ /// Where the undo history stands now, for [`Session::revert_to`].
+ pub fn undo_mark(&self) -> UndoMark {
+ UndoMark(self.history.undo.last().map(|u| Arc::as_ptr(&u.1) as usize))
+ }
+
+ /// Take back every edit made since `mark` (a gesture cancelled with Escape, #580), merged or
+ /// not: the project returns to how it was at `mark`, and neither undo nor redo keeps them.
+ /// Nothing happens when `mark` has left the history. Returns how many steps were taken back.
+ pub fn revert_to(&mut self, mark: UndoMark) -> usize {
+ if let UndoMark(Some(p)) = mark
+ && !self.history.undo.iter().any(|u| Arc::as_ptr(&u.1) as usize == p)
+ {
+ return 0;
+ }
+ let mut earliest = None;
+ let mut n = 0;
+ while self.undo_mark() != mark {
+ let Some((_, prev)) = self.history.undo.pop() else { break };
+ earliest = Some(prev);
+ n += 1;
+ }
+ if let Some(prev) = earliest {
+ self.project = prev;
+ self.history.merge_key = None;
+ self.fix_state();
+ self.bump();
+ }
+ n
+ }
+
/// 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)
diff --cc crates/ui-egui/src/panels/mod.rs
index 4a719b5c1,cc8926ffe..62017cdeb
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -195,16 -188,36 +195,39 @@@ pub fn clear_drag(ui: &egui::Ui)
ui.ctx().data_mut(|d| d.insert_temp::<Option<DragPayloadBox>>(payload_id(), None));
}
- /// Draw the drag ghost near the pointer and clear the payload after release.
+ fn cancelled_id() -> egui::Id {
+ egui::Id::new("filmcraft-drag-cancelled")
+ }
+
+ /// Abandon the drag in progress (Escape, #580): nothing is dropped, and nothing restarts it until
+ /// the button comes up.
+ pub fn cancel_drag(ui: &egui::Ui) {
+ clear_drag(ui);
+ ui.ctx().data_mut(|d| d.insert_temp(cancelled_id(), true));
+ }
+
+ /// Whether the press in progress had its drag cancelled with Escape.
+ pub fn drag_cancelled(ui: &egui::Ui) -> bool {
+ ui.ctx().data(|d| d.get_temp::<bool>(cancelled_id())).unwrap_or(false)
+ }
+
+ /// Draw the drag ghost near the pointer and clear the payload after release. Escape cancels it.
pub fn drag_ghost(app: &FilmcraftApp, ui: &egui::Ui) {
+ if !ui.ctx().input(|i| i.pointer.any_down()) {
+ ui.ctx().data_mut(|d| d.remove::<bool>(cancelled_id()));
+ }
let Some(pl) = payload(ui) else { return };
let ctx = ui.ctx();
+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ cancel_drag(ui);
+ return;
+ }
if let Some(p) = ctx.pointer_hover_pos() {
let label = match &pl {
- DragPayload::Item(i) => app.session.project.item(*i).map(|x| x.name.clone()).unwrap_or_default(),
+ DragPayload::Item(i) => match dragged_selection(app, *i).len() {
+ 1 => app.session.project.item(*i).map(|x| x.name.clone()).unwrap_or_default(),
+ n => format!("{n} items"),
+ },
DragPayload::Bin(b) => app.session.project.root.find_bin(filmcraft_project::BinId(*b)).map(|x| x.name.clone()).unwrap_or_default(),
DragPayload::Source(s) => {
let name = app.session.project.item(s.item).map(|i| i.name.as_str()).unwrap_or("Source");
diff --cc crates/ui-egui/src/panels/timeline.rs
index 0ac698cc6,bf8815a68..f8edd6802
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@@ -626,12 -667,28 +667,32 @@@ fn empty_state(app: &mut FilmcraftApp,
&& ui.input(|i| i.pointer.hover_pos()).is_some_and(|pos| app.timeline_drop_target(ui.ctx(), pos))
&& ui.input(|i| i.pointer.any_released())
{
- let _ = app.session.execute("file.newSequence", json!({"fromItem": item.0}));
+ // a multi-selection makes the sequence from its first item and follows it, back to back, in one undo step
+ let items: Vec<u64> = crate::panels::dragged_selection(app, item).iter().map(|i| i.0).collect();
+ if let Err(e) = app.session.execute("file.newSequence", json!({"fromItems": items})) {
+ app.ui.status = e.to_string();
+ }
}
+ // OS files dropped on an empty Timeline: import already happened; create a sequence from the first item
+ if let Some((items, p)) = app.pending_timeline_drop.clone()
+ && rect.contains(p)
+ && let Some((first, rest)) = items.split_first()
+ {
+ app.pending_timeline_drop = None;
+ if let Err(e) = app.session.execute("file.newSequence", json!({"fromItem": first.0})) {
+ app.ui.status = e.to_string();
+ } else {
+ let mut t = app.session.project.item(*first).map(|i| i.duration()).unwrap_or(Tick::ZERO);
+ for item in rest {
+ let params = json!({"item": item.0, "time": t.0, "insert": false});
+ if let Err(e) = app.session.execute("timeline.place", params) {
+ app.ui.status = e.to_string();
+ } else {
+ t = Tick(t.0.saturating_add(app.session.project.item(*item).map(|i| i.duration().0.max(0)).unwrap_or(0)));
+ }
+ }
+ }
+ }
}
/// The through-edit mark: two small triangles pointing at the cut, centred on the track, with a
diff --cc crates/ui-egui/tests/project_panel_ui.rs
index 854c485b7,3f4142284..8a76e0a48
--- a/crates/ui-egui/tests/project_panel_ui.rs
+++ b/crates/ui-egui/tests/project_panel_ui.rs
@@@ -1040,19 -1003,38 +1040,55 @@@ fn marquee_selects_cards_in_freeform_vi
assert!(!d.app().session.project.item(ItemId(i0)).unwrap().metadata.contains_key(FREEFORM_POS), "the marquee moved no card");
}
+/// The Project selection can hold a bin beside items (one id space). Dragging the items still
+/// places them: the bin is left out instead of failing the whole drop.
+#[test]
+fn a_bin_in_the_selection_does_not_stop_the_items_being_placed() {
+ let mut d = Driver::demo();
+ let (bin, items) = d.footage();
+ d.exec("file.newSequence", json!({"name": "Drop", "video": 2, "audio": 2}));
+ d.ok("ui.menu.invoke", json!({"id": "projectPanel.openBin", "params": {"bin": bin, "how": "inPlace"}}));
+ d.wait_for(&format!("project.item.{}", items[0]));
+ d.exec("project.select", json!({"items": [items[0], bin, items[1]]}));
+ d.frames(2);
+ d.ok("ui.drag", json!({"from": {"id": format!("project.item.{}", items[0])}, "to": {"id": "timeline.tracks", "fx": 0.3, "fy": 0.1}, "steps": 16}));
+ d.frames(4);
+ let clips = d.app().session.active_sequence().map(|q| q.video_tracks.iter().map(|t| t.items.len()).sum::<usize>()).unwrap_or(0);
+ assert_eq!(clips, 2, "status: {}", d.app().ui.status);
+}
++
+ /// Escape during a Media Browser drag (#580) takes the import back, even over the Timeline.
+ #[test]
+ fn escape_takes_back_a_media_browser_drag() {
+ let dir = media_dir("drag-escape");
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).unwrap();
+ let mut d = Driver::with(session);
+ d.ok("ui.set", json!({"workspace": "Editing"}));
+ d.ok("ui.panel.show", json!({"panel": "MediaBrowser"}));
+ d.exec("mediaBrowser.navigate", json!({"path": dir.to_string_lossy()}));
+ d.frames(3);
+ d.wait_for("mediaBrowser.entry.b-roll.wav");
+ let (n0, before) = (d.app().session.project.items.len(), d.app().session.project.to_json());
+ let e = d.rect("mediaBrowser.entry.b-roll.wav");
+ let tl = d.rect("panel.Timeline");
+ let (from, to) = (egui::pos2(e[0] + 40.0, e[1] + e[3] / 2.0), egui::pos2(tl[0] + tl[2] * 0.6, tl[1] + tl[3] * 0.75));
+ let mut send = |e: egui::Event| {
+ d.harness.input_mut().events.push(e);
+ d.frames(1);
+ };
+ let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
+ send(egui::Event::PointerMoved(from));
+ send(button(from, true));
+ for k in 1..=20 {
+ send(egui::Event::PointerMoved(from.lerp(to, k as f32 / 20.0)));
+ if k == 10 {
+ send(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
+ }
+ }
+ send(button(to, false));
+ d.frames(6);
+ assert_eq!(d.app().session.project.items.len(), n0, "the import was taken back");
+ assert_eq!(d.app().session.project.to_json(), before, "nothing was placed on the Timeline");
+ let _ = std::fs::remove_dir_all(&dir);
+ }