Skip to content

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

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

awe8056e62f6506
diff --cc crates/engine/src/commands.rs
index 05144a41c,6609afddf..541387b38
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@@ -577,110 -664,6 +664,118 @@@ 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 tg = s.targeting();
+ let pi = s.project.item(item).ok_or_else(|| bad("timeline.place", "no such 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() => {
+ 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() => {
+ 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() {
+ 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() {
+ return Err(bad("timeline.place", "no audio destination: add or enable an audio track"));
+ }
- let full = match &pi.kind {
- // Settings ▸ Timeline ▸ Still Image Default Duration
- ItemKind::Media(m)
- if matches!(m.info.kind, filmcraft_media::MediaKind::Still)
- || (matches!(m.info.kind, filmcraft_media::MediaKind::Synthetic) && m.info.duration.0 <= 0) =>
- {
- s.prefs.timeline.still_duration(s.sequence_rate())
- }
- _ => pi.duration(),
- };
++ 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());
+ 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 = p.clone();
++ 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,
@@@ -2194,11 -2184,60 +2312,11 @@@ fn build() -> Vec<CommandSpec>
"Place Clip",
[],
None,
- r#"{"item":id|"items":[id] (back to back, one undo step),"track":"V1"|id|"A1" (sound only)?,"audioTrack":"A1"|id?,"time":ticks|"frame":i64|"seconds":f64,"insert":bool,"sourceIn":ticks?,"duration":ticks?,"video":bool=true,"audio":bool=true}"#,
- r#"{"item":id,"track":"V1"|id|"A1" (sound only)|"new" (a video track after the last)?,"audioTrack":"A1"|id|"new"?,"time":ticks|"frame":i64|"seconds":f64,"insert":bool,"sourceIn":ticks?,"duration":ticks?,"video":bool=true,"audio":bool=true}"#,
++ r#"{"item":id|"items":[id] (back to back, one undo step),"track":"V1"|id|"A1" (sound only)|"new" (a video track after the last)?,"audioTrack":"A1"|id|"new"?,"time":ticks|"frame":i64|"seconds":f64,"insert":bool,"sourceIn":ticks?,"duration":ticks?,"video":bool=true,"audio":bool=true}"#,
has_seq,
- |s, p| {
- 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 tg = s.targeting();
- let pi = s.project.item(item).ok_or_else(|| bad("timeline.place", "no such 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() => {
- 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() => {
- 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() {
- 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() {
- 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<_>>()}))
+ |s, p| match p.get("items") {
+ Some(items) => place_items(s, p, items),
+ None => place_one(s, p),
}
),
cmd!("timeline.select", "Select Clips", [], None, r#"{"clips":[id],"transitions":[id]?,"add":bool,"toggle":bool}"#, has_seq, |s, p| {
diff --cc crates/engine/src/lib.rs
index 303102e56,a2ed9e6a2..41df2750b
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -1121,8 -1138,8 +1171,10 @@@ mod panels_tests
#[cfg(test)]
mod par_tests;
#[cfg(test)]
+ mod paste_media_tests;
+ #[cfg(test)]
+mod place_items_tests;
+#[cfg(test)]
mod presets_tests;
#[cfg(test)]
mod previews_tests;
diff --cc crates/engine/src/place_items_tests.rs
index ac0088cbd,000000000..f320f2e63
mode 100644,000000..100644
--- a/crates/engine/src/place_items_tests.rs
+++ b/crates/engine/src/place_items_tests.rs
@@@ -1,109 -1,0 +1,125 @@@
+//! `timeline.place` with `items` and `file.newSequence` with `fromItems`: several items back to
+//! back, as one undo step.
+
+use filmcraft_project::ItemId;
+use serde_json::json;
+
+use crate::Session;
+
+/// A session on an empty sequence, and the ids of three media items with picture and sound.
+fn three() -> (Session, Vec<ItemId>) {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ let items: Vec<ItemId> = s.project.items.values().filter(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).take(3).collect();
+ assert!(items.len() >= 2, "the demo project has media to place");
+ s.execute("file.newSequence", json!({"name": "Back to back", "video": 2, "audio": 2})).unwrap();
+ (s, items)
+}
+
+fn ends(s: &Session) -> Vec<(i64, i64)> {
+ let q = s.active_sequence().unwrap();
+ q.video_tracks[0].items.iter().map(|i| (i.start.0, i.end().0)).collect()
+}
+
+/// Dragging several selected items placed them one by one, each one an undo step.
+#[test]
+fn items_land_back_to_back_in_one_undo_step() {
+ let (mut s, items) = three();
+ let steps = s.history.undo.len();
+ let r = s.execute("timeline.place", json!({"items": items.iter().map(|i| i.0).collect::<Vec<_>>(), "time": 0})).unwrap();
+ assert_eq!(r["placed"].as_array().unwrap().len(), items.len());
+ let spans = ends(&s);
+ assert_eq!(spans.len(), items.len());
+ assert_eq!(spans[0].0, 0);
+ for w in spans.windows(2) {
+ assert_eq!(w[0].1, w[1].0, "each item starts where the one before ends");
+ }
+ assert_eq!(s.history.undo.len(), steps + 1, "one undo step for all of them");
+ assert_eq!(s.history.undo.last().map(|u| u.0.as_str()), Some("Place Clips"));
+ s.undo();
+ assert!(ends(&s).is_empty(), "one undo takes them all off");
+ s.redo();
+ assert_eq!(ends(&s), spans);
+}
+
+/// One bad item in the list leaves the sequence and the history as they were.
+#[test]
+fn a_failing_item_places_nothing() {
+ let (mut s, items) = three();
+ let steps = s.history.undo.len();
+ let list = vec![items[0].0, u64::MAX - 1];
+ assert!(s.execute("timeline.place", json!({"items": list, "time": 0})).is_err());
+ assert!(ends(&s).is_empty());
+ assert_eq!(s.history.undo.len(), steps);
+}
+
+/// `items` is checked: not a list, empty, mixed with `item`, or with one item's range.
+#[test]
+fn items_are_checked() {
+ let (mut s, items) = three();
+ let one = items[0].0;
+ for p in [
+ json!({"items": one}),
+ json!({"items": []}),
+ json!({"items": ["x"]}),
+ json!({"items": [one], "item": one}),
+ json!({"items": [one], "duration": 5}),
+ json!({"items": [one], "sourceIn": 5}),
+ ] {
+ assert!(s.execute("timeline.place", p.clone()).is_err(), "{p}");
+ }
+ assert!(ends(&s).is_empty());
+}
+
+/// A new sequence from several items is one undo step: the sequence and its clips go together.
+#[test]
+fn new_sequence_from_items_is_one_undo_step() {
+ let (mut s, items) = three();
+ let steps = s.history.undo.len();
+ let sequences = s.project.sequences().count();
+ s.execute("file.newSequence", json!({"fromItems": items.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
+ assert_eq!(ends(&s).len(), items.len());
+ assert_eq!(s.history.undo.len(), steps + 1);
+ s.undo();
+ assert_eq!(s.project.sequences().count(), sequences);
+ assert!(s.execute("file.newSequence", json!({"fromItems": 3})).is_err());
+}
+
+/// Times at the edge of the number range are refused or placed, never a panic, and a refusal
+/// leaves the sequence and the history as they were.
+#[test]
+fn hostile_times_never_panic_and_leave_nothing_half_placed() {
+ let (mut s, items) = three();
+ let ids: Vec<u64> = items.iter().map(|i| i.0).collect();
+ for t in [i64::MAX, i64::MAX - 5, i64::MIN, -1] {
+ let steps = s.history.undo.len();
+ let r = s.execute("timeline.place", json!({"items": ids, "time": t}));
+ if r.is_err() {
+ assert_eq!(s.history.undo.len(), steps, "{t}");
+ assert!(ends(&s).is_empty(), "{t}");
+ } else {
+ assert_eq!(s.history.undo.len(), steps + 1, "{t}");
+ s.undo();
+ }
+ }
+ // zero-length and many items: capped, not unbounded
+ let many = vec![items[0].0; 10_001];
+ assert!(s.execute("timeline.place", json!({"items": many, "time": 0})).is_err());
+ assert!(ends(&s).is_empty());
+}
++
++/// `"track":"new"` with `items` adds one track, and the whole list goes on it, in one undo step.
++#[test]
++fn items_on_a_new_track_share_that_one_track() {
++ let (mut s, items) = three();
++ let tracks = s.active_sequence().unwrap().video_tracks.len();
++ let steps = s.history.undo.len();
++ let list: Vec<u64> = items.iter().map(|i| i.0).collect();
++ s.execute("timeline.place", json!({"items": list, "track": "new", "time": 0})).unwrap();
++ let q = s.active_sequence().unwrap();
++ assert_eq!(q.video_tracks.len(), tracks + 1, "one new video track, not one per item");
++ assert_eq!(q.video_tracks[tracks].items.len(), items.len());
++ assert_eq!(s.history.undo.len(), steps + 1);
++ s.undo();
++ assert_eq!(s.active_sequence().unwrap().video_tracks.len(), tracks, "undo removes the track too");
++}
diff --cc crates/ui-egui/src/panels/mod.rs
index 9da3f04b3,a2dd95be3..c3176248d
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -180,10 -194,8 +200,11 @@@ pub fn drag_ghost(app: &FilmcraftApp, u
let ctx = ui.ctx();
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");
let mode = match (s.video, s.audio) {
diff --cc crates/ui-egui/src/panels/timeline.rs
index 3c34aa8d3,70cde2b69..ed20f4067
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@@ -2312,23 -2543,20 +2547,29 @@@ fn interact(app: &mut FilmcraftApp, ui
ui.painter().text(r.left_top() + vec2(4.0, -2.0), Align2::LEFT_BOTTOM, tl!("Insert"), Tokens::ui(10.0), Color32::WHITE);
}
}
+ let target = match (&row, new_track) {
+ (Some(row), _) => Some(match row.kind {
+ TrackKind::Video => (json!(row.track.0), json!(seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0))),
+ TrackKind::Audio => (json!(seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0)), json!(row.track.0)),
+ }),
+ // the other stream goes on the track of the same number, or on a new one as well
+ (None, Some((TrackKind::Video, _))) => Some((json!("new"), seq.audio_tracks.get(seq.video_tracks.len()).map_or(json!("new"), |t| json!(t.id.0)))),
+ (None, Some((TrackKind::Audio, _))) => Some((seq.video_tracks.get(seq.audio_tracks.len()).map_or(json!("new"), |t| json!(t.id.0)), json!("new"))),
+ (None, None) => None,
+ };
if ctx.input(|i| i.pointer.any_released())
- && let Some(row) = row
+ && let Some((vt, at)) = target
{
- let (vt, at) = match row.kind {
- TrackKind::Video => (Some(row.track.0), seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0)),
- TrackKind::Audio => (seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0), Some(row.track.0)),
- };
- let mut params = json!({"item": item.0, "track": vt, "audioTrack": at, "time": t.0, "insert": mods.command});
+ // dragging one of several selected project items places them all, back to back, as one edit
+ let items = match source {
+ None => crate::panels::dragged_selection(app, item),
+ Some(_) => vec![item],
+ };
+ let mut params = json!({"track": vt, "audioTrack": at, "time": t.0, "insert": mods.command});
+ match items.as_slice() {
+ [one] => params["item"] = json!(one.0),
+ many => params["items"] = json!(many.iter().map(|i| i.0).collect::<Vec<_>>()),
+ }
if let Some(source) = source {
params["sourceIn"] = json!(source.range.start.0);
params["duration"] = json!(source.range.duration.0);
@@@ -2455,6 -2694,128 +2698,115 @@@
app.auto.add("timeline.tracks", layout.content, "tracks");
}
-/// Start tick of each clip when the clips are laid end to end from `start`. Saturates rather than overflows.
-pub(crate) fn chain_starts(start: Tick, durations: &[Tick]) -> Vec<Tick> {
- let mut t = start;
- durations
- .iter()
- .map(|d| {
- let at = t;
- t = Tick(t.0.saturating_add(d.0.max(0)));
- at
- })
- .collect()
-}
-
+ /// #374: trimming an audio clip must cut its waveform off at the moving edge, not squeeze the whole
+ /// waveform into the shorter clip: the preview draws from the item the trim will leave, which shows
+ /// the same media at every timeline time it still covers.
+ #[cfg(test)]
+ mod trim_preview_tests {
+ use super::*;
+
+ fn demo() -> (FilmcraftApp, Sequence) {
+ let mut s = filmcraft_engine::Session::default();
+ s.execute("file.openDemoProject", serde_json::json!({})).unwrap();
+ let seq = s.active_sequence().unwrap().clone();
+ (FilmcraftApp::new(s), seq)
+ }
+
+ fn assert_same_media(before: &TrackItem, after: &TrackItem) {
+ let mut t = after.start.max(before.start);
+ while t < after.end().min(before.end()) {
+ assert!((before.source_time_at(t) - after.source_time_at(t)).0.abs() <= 1, "{}: media moved at {t:?}", before.name);
+ t += Tick(filmcraft_time::TICKS_PER_SECOND / 10);
+ }
+ }
+
+ /// A source whose audio streams are different constants (0.1 for stream 0, 0.5 for stream 1).
+ struct TwoStreams(filmcraft_media::MediaInfo);
+
+ impl filmcraft_media::MediaSource for TwoStreams {
+ fn info(&self) -> &filmcraft_media::MediaInfo {
+ &self.0
+ }
+ fn video_frame(&self, _req: filmcraft_media::FrameRequest) -> filmcraft_media::Result<Arc<filmcraft_frame::VideoFrame>> {
+ Err(filmcraft_media::MediaError::NoStream("video"))
+ }
+ fn audio(&self, _start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<filmcraft_frame::AudioBuffer> {
+ Ok(filmcraft_frame::AudioBuffer { sample_rate, channels: vec![vec![0.1; frames]] })
+ }
+ fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<filmcraft_frame::AudioBuffer> {
+ match stream {
+ 0 => self.audio(start, frames, sample_rate),
+ 1 => Ok(filmcraft_frame::AudioBuffer { sample_rate, channels: vec![vec![0.5; frames]] }),
+ _ => Err(filmcraft_media::MediaError::NoStream("audio")),
+ }
+ }
+ }
+
+ #[test]
+ fn each_audio_stream_gets_its_own_waveform_peaks() {
+ let info = filmcraft_media::MediaInfo {
+ name: "two.mkv".into(),
+ kind: filmcraft_media::MediaKind::Movie,
+ duration: Tick(TICKS_PER_SECOND),
+ video: None,
+ audio_streams: Vec::new(),
+ container: "mkv".into(),
+ start_timecode: None,
+ file_size: None,
+ };
+ let src = TwoStreams(info);
+ let first = source_peaks(&src, 0, Tick(TICKS_PER_SECOND));
+ let second = source_peaks(&src, 1, Tick(TICKS_PER_SECOND));
+ assert!(!first.is_empty() && first.len() == second.len());
+ assert!(first.iter().all(|&(_, hi)| (hi - 0.1).abs() < 1e-6), "stream 0 is the quiet one");
+ assert!(second.iter().all(|&(_, hi)| (hi - 0.5).abs() < 1e-6), "stream 1 is its own audio, not stream 0 again");
+ assert!(source_peaks(&src, 2, Tick(TICKS_PER_SECOND)).is_empty(), "a missing stream has no peaks");
+ }
+
+ #[test]
+ fn trimming_the_music_keeps_its_waveform_in_place() {
+ let (mut app, seq) = demo();
+ let music = seq.audio_tracks.iter().flat_map(|t| &t.items).find(|i| i.name.contains("Ambient")).unwrap().clone();
+ for (edge, delta) in [(filmcraft_edit::Edge::In, 5), (filmcraft_edit::Edge::Out, -5), (filmcraft_edit::Edge::In, -1)] {
+ let delta = Tick(delta * filmcraft_time::TICKS_PER_SECOND);
+ app.tl.drag = Some(Drag::Trim { clip: music.id, edge, mode: filmcraft_edit::TrimMode::Regular, delta, from: Tick::ZERO });
+ let (mut out, mut edited) = (HashMap::new(), HashMap::new());
+ preview_drag(&app, &seq, &mut out, &mut edited);
+ let shown = edited.get(&music.id).expect("the trimmed clip is drawn from its edited item");
+ // where the preview places it is unchanged
+ let want = match edge {
+ filmcraft_edit::Edge::In => (music.start + delta, music.duration - delta, None),
+ filmcraft_edit::Edge::Out => (music.start, music.duration + delta, None),
+ };
+ assert_eq!(out.get(&music.id).copied(), Some(want));
+ assert_eq!((shown.start, shown.duration), (want.0, want.1));
+ // the music under every remaining timeline time is the same: the waveform stays put
+ assert_same_media(&music, shown);
+ if edge == filmcraft_edit::Edge::In {
+ assert_eq!(shown.source_in, music.source_in + delta, "5 s into the music, not the music squeezed");
+ }
+ }
+ }
+
+ #[test]
+ fn rolling_an_edit_keeps_both_sides_in_place_but_a_stretch_still_squeezes() {
+ let (mut app, seq) = demo();
+ let (left, right) = seq.audio_tracks[0].items.windows(2).find(|w| w[0].end() == w[1].start).map(|w| (w[0].clone(), w[1].clone())).unwrap();
+ let delta = Tick(filmcraft_time::TICKS_PER_SECOND / 2);
+ app.tl.drag = Some(Drag::Roll { left: left.id, right: right.id, delta, from: Tick::ZERO });
+ let (mut out, mut edited) = (HashMap::new(), HashMap::new());
+ preview_drag(&app, &seq, &mut out, &mut edited);
+ assert_same_media(&left, &edited[&left.id]);
+ assert_same_media(&right, &edited[&right.id]);
+ assert_eq!(edited[&right.id].start, right.start + delta);
+ // Rate Stretch keeps the same media in a new length: drawn from the original item
+ app.tl.drag = Some(Drag::Stretch { clip: left.id, edge: filmcraft_edit::Edge::Out, delta, from: Tick::ZERO });
+ let (mut out, mut edited) = (HashMap::new(), HashMap::new());
+ preview_drag(&app, &seq, &mut out, &mut edited);
+ assert!(edited.is_empty() && out.contains_key(&left.id));
+ }
+ }
+
#[cfg(test)]
mod waveform_tests {
use super::waveform_display_gain;
@@@ -2477,3 -2838,122 +2829,83 @@@
assert!((db(waveform_display_gain(1.0, -6.0)) - (-6.0)).abs() < 0.1);
}
}
-
-#[cfg(test)]
-mod chain_starts_tests {
- use super::chain_starts;
- use filmcraft_time::Tick;
-
- #[test]
- fn empty_list_has_no_starts() {
- assert!(chain_starts(Tick(100), &[]).is_empty());
- }
-
- #[test]
- fn one_clip_starts_at_the_drop_point() {
- assert_eq!(chain_starts(Tick(7), &[Tick(30)]), vec![Tick(7)]);
- }
-
- #[test]
- fn several_clips_are_laid_end_to_end() {
- let durations = [Tick(10), Tick(25), Tick(5)];
- assert_eq!(chain_starts(Tick(100), &durations), vec![Tick(100), Tick(110), Tick(135)]);
- }
-
- #[test]
- fn start_near_i64_max_saturates_without_panicking() {
- let starts = chain_starts(Tick(i64::MAX - 5), &[Tick(10), Tick(10), Tick(10)]);
- assert_eq!(starts, vec![Tick(i64::MAX - 5), Tick(i64::MAX), Tick(i64::MAX)]);
- }
-
- #[test]
- fn zero_length_clips_share_one_start() {
- assert_eq!(chain_starts(Tick(42), &[Tick(0), Tick(0), Tick(9)]), vec![Tick(42), Tick(42), Tick(42)]);
- }
-
- #[test]
- fn negative_durations_count_as_zero() {
- assert_eq!(chain_starts(Tick(5), &[Tick(-3), Tick(4)]), vec![Tick(5), Tick(5)]);
- }
-}
-
+ #[cfg(test)]
+ mod thumbnail_tiles_tests {
+ use super::*;
+
+ const S: Tick = Tick(TICKS_PER_SECOND);
+ const FRAME: Tick = Tick(TICKS_PER_SECOND / 25);
+
+ #[test]
+ fn continuous_thumbnails_tile_the_visible_part_of_the_clip() {
+ // a 10 s clip 1000 pt wide, 80 pt tiles, the panel showing x 250..650
+ let tiles = thumbnail_tiles(ThumbnailMode::Continuous, 0.0, 1000.0, 80.0, (250.0, 650.0), Tick(10 * S.0), FRAME);
+ let xs: Vec<f32> = tiles.iter().map(|t| t.0).collect();
+ assert_eq!(xs, [240.0, 320.0, 400.0, 480.0, 560.0, 640.0]);
+ // each tile shows the clip time under its left edge (100 pt per second)
+ assert_eq!(tiles[0].1, Tick(24 * S.0 / 10));
+ assert_eq!(tiles[5].1, Tick(64 * S.0 / 10));
+ // scrolling 30 pt moves the tiles with the clip: the ones still shown keep their frames
+ let scrolled = thumbnail_tiles(ThumbnailMode::Continuous, -30.0, 970.0, 80.0, (250.0, 650.0), Tick(10 * S.0), FRAME);
+ assert_eq!(scrolled.first(), Some(&(210.0, tiles[0].1)));
+ assert!(scrolled.iter().all(|(x, t)| tiles.iter().any(|(x0, t0)| *x0 - 30.0 == *x && t0 == t)));
+ // the last tile never shows a time past the clip's last frame
+ let end = thumbnail_tiles(ThumbnailMode::Continuous, 0.0, 1000.0, 80.0, (0.0, 2000.0), Tick(10 * S.0), FRAME);
+ assert_eq!(end.len(), 13);
+ assert!(end.iter().all(|(_, t)| *t <= Tick(10 * S.0) - FRAME));
+ // a clip far zoomed in asks for a bounded number of frames
+ let huge = thumbnail_tiles(ThumbnailMode::Continuous, -1.0e9, 1.0e9, 1.0, (-2.0e9, 2.0e9), Tick(10 * S.0), FRAME);
+ assert_eq!(huge.len(), MAX_THUMBNAIL_TILES);
+ }
+
+ #[test]
+ fn head_and_tail_thumbnails_need_room_for_two_frames() {
+ let dur = Tick(4 * S.0);
+ assert_eq!(thumbnail_tiles(ThumbnailMode::Head, 100.0, 500.0, 80.0, (0.0, 800.0), dur, FRAME), [(100.0, Tick::ZERO)]);
+ assert_eq!(thumbnail_tiles(ThumbnailMode::HeadAndTail, 100.0, 500.0, 80.0, (0.0, 800.0), dur, FRAME), [(100.0, Tick::ZERO), (420.0, dur - FRAME)]);
+ // narrower than two tiles: the head only, as in Continuous narrower than one tile
+ assert_eq!(thumbnail_tiles(ThumbnailMode::HeadAndTail, 100.0, 250.0, 80.0, (0.0, 800.0), dur, FRAME), [(100.0, Tick::ZERO)]);
+ assert_eq!(thumbnail_tiles(ThumbnailMode::Continuous, 100.0, 150.0, 80.0, (0.0, 800.0), dur, FRAME), [(100.0, Tick::ZERO)]);
+ // off screen or degenerate: nothing
+ assert!(thumbnail_tiles(ThumbnailMode::Head, 900.0, 1300.0, 80.0, (0.0, 800.0), dur, FRAME).is_empty());
+ assert!(thumbnail_tiles(ThumbnailMode::Continuous, 0.0, 400.0, f32::NAN, (0.0, 800.0), dur, FRAME).is_empty());
+ assert!(thumbnail_tiles(ThumbnailMode::Continuous, 0.0, 0.0, 80.0, (0.0, 800.0), dur, FRAME).is_empty());
+ }
+ }
+
+ #[cfg(test)]
+ mod new_track_tests {
+ use super::*;
+ use filmcraft_project::{Project, SequenceSettings};
+
+ /// #483: a drop above the top video track adds a video track, one below the last audio track an
+ /// audio track; over a track, between the areas or on the Mix row it adds none.
+ #[test]
+ fn empty_space_past_the_tracks_adds_a_track() {
+ let mut p = Project::new("t");
+ let id = p.new_sequence("s", SequenceSettings::default(), 1, 1, None);
+ let seq = p.sequence(id).cloned().expect("sequence");
+ // video area 0..200 (V1 at 150..200), divider, audio area 205..466 (A1 at 205..255), Mix 466..500
+ let row = |kind, track: &filmcraft_project::Track, y0: f32| Row {
+ track: track.id,
+ kind,
+ index: 0,
+ rect: Rect::from_min_max(pos2(0.0, y0), pos2(800.0, y0 + 50.0)),
+ lane: false,
+ };
+ let layout = Layout {
+ content: Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 500.0)),
+ ruler: Rect::from_min_max(pos2(0.0, -20.0), pos2(800.0, 0.0)),
+ rows: vec![row(TrackKind::Video, &seq.video_tracks[0], 150.0), row(TrackKind::Audio, &seq.audio_tracks[0], 205.0)],
+ pps: 100.0,
+ scroll: 0.0,
+ split_y: 200.0,
+ };
+ let at = |y| new_track_at(&seq, &layout, y, 50.0, 50.0);
+ assert_eq!(at(40.0), Some((TrackKind::Video, Rect::from_min_max(pos2(0.0, 100.0), pos2(800.0, 150.0)))));
+ assert_eq!(at(300.0), Some((TrackKind::Audio, Rect::from_min_max(pos2(0.0, 255.0), pos2(800.0, 305.0)))));
+ for y in [160.0, 202.0, 230.0, 480.0] {
+ assert_eq!(at(y), None, "y = {y}");
+ }
+ }
+ }
diff --cc crates/ui-egui/tests/project_panel_ui.rs
index af5d6c04c,25b9e294e..dbe83bc19
--- a/crates/ui-egui/tests/project_panel_ui.rs
+++ b/crates/ui-egui/tests/project_panel_ui.rs
@@@ -627,39 -743,245 +743,282 @@@ fn media_browser_drag_imports_into_the_
let _ = std::fs::remove_dir_all(&dir);
}
+/// Dragging one of several selected Project items onto the Timeline places all of them, back to
+/// back, as one undo step; an item outside the selection goes alone.
+#[test]
+fn dragging_a_selection_to_the_timeline_places_every_item() {
+ let mut d = Driver::demo();
+ let (bin, items) = d.footage();
+ assert!(items.len() >= 3);
+ 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"}}));
+ let card = |i: u64| format!("project.item.{i}");
+ d.wait_for(&card(items[0]));
+ let clips = |d: &mut Driver| d.app().session.active_sequence().map(|q| q.video_tracks.iter().map(|t| t.items.len()).sum::<usize>()).unwrap_or(0);
+ let steps = d.app().session.history.undo.len();
+ let drop = json!({"id": "timeline.tracks", "fx": 0.3, "fy": 0.1});
+
+ // an item that is not selected: one clip
+ d.exec("project.select", json!({"items": [items[2]]}));
+ d.ok("ui.drag", json!({"from": {"id": card(items[0])}, "to": drop, "steps": 16}));
+ d.frames(4);
+ assert_eq!(clips(&mut d), 1, "an unselected item goes alone");
+ d.exec("edit.undo", json!({}));
+
+ // two of the selection: both, back to back, in one undo step
+ d.exec("project.select", json!({"items": [items[0], items[1]]}));
+ d.frames(2);
+ d.ok("ui.drag", json!({"from": {"id": card(items[0])}, "to": drop, "steps": 16}));
+ d.frames(4);
+ assert_eq!(clips(&mut d), 2, "the whole selection is placed");
+ let mut v1: Vec<(i64, i64)> =
+ d.app().session.active_sequence().unwrap().video_tracks.iter().flat_map(|t| t.items.iter()).map(|i| (i.start.0, i.end().0)).collect();
+ v1.sort();
+ assert_eq!(v1[0].1, v1[1].0, "back to back");
+ assert_eq!(d.app().session.history.undo.len(), steps + 1, "the drag is one undo step");
+ d.exec("edit.undo", json!({}));
+ assert_eq!(clips(&mut d), 0);
+}
++
+ /// Double-clicking empty space in the Project panel opens Import, also between and beside the
+ /// Icon view's cards once the project has some. Only the strip under the last row used to answer,
+ /// so with a project loaded a double-click in the visible blank space did nothing. Real pointer
+ /// input at 60 frames per second, so the two clicks are a real double-click.
+ #[test]
+ fn double_click_empty_area_imports_with_a_project_loaded() {
+ fn driver(demo: bool) -> (Driver, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
+ let mut session = Session::default();
+ if demo {
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ }
+ let (tx, rx) = channel();
+ let mut app = FilmcraftApp::new(session).with_control(rx);
+ let picks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen = picks.clone();
+ app.hooks.pick_files = Some(Box::new(move |_| {
+ seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Vec::new()
+ }));
+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, snapshots: None };
+ d.frames(10);
+ (d, picks)
+ }
+ fn double_click(d: &mut Driver, at: egui::Pos2) {
+ let push = |d: &mut Driver, e: egui::Event| d.harness.input_mut().events.push(e);
+ // a pause first, as a person makes: clicks closer together continue the last gesture
+ // (a triple click) instead of starting a double-click
+ d.frames(60);
+ push(d, egui::Event::PointerMoved(at));
+ d.frames(1);
+ for _ in 0..2 {
+ for pressed in [true, false] {
+ push(d, egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ d.frames(1);
+ }
+ }
+ d.frames(3);
+ }
+ let count = |p: &std::sync::Arc<std::sync::atomic::AtomicUsize>| p.load(std::sync::atomic::Ordering::SeqCst);
+
+ // an empty project: the whole panel is the empty area
+ let (mut d, picks) = driver(false);
+ let r = d.rect("project.empty");
+ double_click(&mut d, egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0));
+ assert_eq!(count(&picks), 1, "empty project");
+
+ // the demo project, Icon view: the gap between the first two bins, and the space right of the
+ // last card in the first row
+ let (mut d, picks) = driver(true);
+ d.ok("ui.set", json!({}));
+ let (a, b) = (d.rect("project.bin.1"), d.rect("project.bin.2"));
+ assert!((a[1] - b[1]).abs() < 1.0 && b[0] > a[0] + a[2], "bins 1 and 2 share a row: {a:?} {b:?}");
+ double_click(&mut d, egui::pos2((a[0] + a[2] + b[0]) / 2.0, a[1] + a[3] / 2.0));
+ assert_eq!(count(&picks), 1, "between two bins");
+ let row: Vec<[f32; 4]> = d.ids("project.bin.").iter().map(|id| d.rect(id)).filter(|r| (r[1] - a[1]).abs() < 1.0).collect();
+ let last = row.iter().fold(a, |m, r| if r[0] > m[0] { *r } else { m });
+ let panel = d.rect("project.count");
+ if last[0] + last[2] + 30.0 < panel[0] + panel[2] {
+ double_click(&mut d, egui::pos2(last[0] + last[2] + 20.0, last[1] + last[3] / 2.0));
+ assert_eq!(count(&picks), 2, "right of the last card");
+ }
+ // a card still takes its own double-click: the bin opens, Import does not
+ double_click(&mut d, egui::pos2(a[0] + a[2] / 2.0, a[1] + a[3] / 2.0));
+ let picked = count(&picks);
+ assert!(picked <= 2, "double-clicking a bin must not open Import");
+ }
+
+ /// The report: with audio placed in the timeline, double-clicking the Project panel's empty space
+ /// no longer opened Import. A new sequence with a tone on A1 (so the panel shows the sequence and
+ /// the audio clip as cards); every empty spot opens Import: the strip under the cards and the space
+ /// beside them.
+ #[test]
+ fn double_click_imports_with_audio_in_the_timeline() {
+ let mut session = Session::default();
+ session.execute("file.newSequence", json!({"name": "Mix", "audio": 2, "video": 1})).unwrap();
+ let inter: Vec<f32> = (0..48_000).flat_map(|i| [(i as f32 * 0.0576).sin() * 0.5; 2]).collect();
+ let bytes: std::sync::Arc<[u8]> = filmcraft_engine::previews::write_wav_f32(&inter, 48_000).into();
+ let item = filmcraft_engine::commands::import_bytes(&mut session, "/tone.wav", bytes, None).unwrap();
+ session.execute("timeline.place", json!({"item": item.0, "audioTrack": "A1", "seconds": 0.0})).unwrap();
+ let (tx, rx) = channel();
+ let mut app = FilmcraftApp::new(session).with_control(rx);
+ let picks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen = picks.clone();
+ app.hooks.pick_files = Some(Box::new(move |_| {
+ seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Vec::new()
+ }));
+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, snapshots: None };
+ d.frames(10);
+ let double_click = |d: &mut Driver, at: egui::Pos2| {
+ let push = |d: &mut Driver, e: egui::Event| d.harness.input_mut().events.push(e);
+ d.frames(60);
+ push(d, egui::Event::PointerMoved(at));
+ d.frames(1);
+ for _ in 0..2 {
+ for pressed in [true, false] {
+ push(d, egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ d.frames(1);
+ }
+ }
+ d.frames(3);
+ };
+ let count = || picks.load(std::sync::atomic::Ordering::SeqCst);
+ let cards: Vec<[f32; 4]> = d.ids("project.item.").iter().filter(|id| id.matches('.').count() == 2).map(|id| d.rect(id)).collect();
+ assert!(!cards.is_empty(), "the sequence and the tone show as cards");
+ let empty = d.rect("project.empty");
+ eprintln!("cards {cards:?}, empty strip {empty:?}");
+ double_click(&mut d, egui::pos2(empty[0] + empty[2] / 2.0, empty[1] + empty[3] / 2.0));
+ let strip = count();
+ let last = cards.iter().fold(cards[0], |m, r| if r[0] > m[0] { *r } else { m });
+ double_click(&mut d, egui::pos2(last[0] + last[2] + 40.0, last[1] + last[3] / 2.0));
+ let beside = count() - strip;
+ assert_eq!((strip, beside), (1, 1), "double-click on (the strip under the cards, the space beside them)");
+ }
+
+ // ---- marquee selection (#578)
+
+ /// The Footage bin open in place in `view`, with its items' rects (row by row, left to right).
+ fn footage_in(d: &mut Driver, view: &str) -> Vec<(u64, [f32; 4])> {
+ let (bin, items) = d.footage();
+ d.exec("project.view.set", json!({"view": view}));
+ d.ok("ui.menu.invoke", json!({"id": "projectPanel.openBin", "params": {"bin": bin, "how": "inPlace"}}));
+ d.wait_for(&format!("project.item.{}", items[0]));
+ let mut rects: Vec<(u64, [f32; 4])> = items.iter().map(|i| (*i, d.rect(&format!("project.item.{i}")))).collect();
+ rects.sort_by(|a, b| (a.1[1], a.1[0]).partial_cmp(&(b.1[1], b.1[0])).unwrap());
+ rects
+ }
+
+ fn selection(d: &mut Driver) -> Vec<u64> {
+ let mut s: Vec<u64> = d.app().session.state.project_selection.iter().map(|i| i.0).collect();
+ s.sort_unstable();
+ s
+ }
+
+ fn sorted(mut v: Vec<u64>) -> Vec<u64> {
+ v.sort_unstable();
+ v
+ }
+
+ fn centre(r: [f32; 4]) -> (f32, f32) {
+ (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
+ }
+
+ fn marquee(d: &mut Driver, from: (f32, f32), to: (f32, f32), shift: bool) {
+ d.ok("ui.drag", json!({"from": {"x": from.0, "y": from.1}, "to": {"x": to.0, "y": to.1}, "steps": 12, "modifiers": {"shift": shift}}));
+ d.frames(3);
+ }
+
+ #[test]
+ fn marquee_selects_cards_in_icon_view() {
+ let mut d = project_driver();
+ let cards = footage_in(&mut d, "icon");
+ let [(i0, a), (i1, b), (i2, c)] = [cards[0], cards[1], cards[2]];
+ assert!((a[1] - c[1]).abs() < 1.0, "the first three cards share a row");
+ // from the gap above-left of the first card to the middle of the second
+ marquee(&mut d, (a[0] - 4.0, a[1] - 4.0), centre(b), false);
+ assert_eq!(selection(&mut d), sorted(vec![i0, i1]));
+ // Shift adds
+ marquee(&mut d, (c[0] + 4.0, c[1] - 4.0), centre(c), true);
+ assert_eq!(selection(&mut d), sorted(vec![i0, i1, i2]));
+ // a plain drag replaces
+ marquee(&mut d, (a[0] - 4.0, a[1] - 4.0), centre(a), false);
+ assert_eq!(selection(&mut d), vec![i0]);
+ // the gaps between cards are empty space: a click there deselects
+ d.ok("ui.click", json!({"x": a[0] - 4.0, "y": a[1] - 4.0}));
+ d.frames(2);
+ assert!(selection(&mut d).is_empty());
+ }
+
+ #[test]
+ fn escape_cancels_a_marquee_and_keeps_the_selection() {
+ let mut d = project_driver();
+ let cards = footage_in(&mut d, "icon");
+ let [(i0, a), (i1, b), (i2, c)] = [cards[0], cards[1], cards[2]];
+ d.exec("project.select", json!({"items": [i2]}));
+ let send = |d: &mut Driver, e: egui::Event| {
+ d.harness.input_mut().events.push(e);
+ d.frames(1);
+ };
+ let (from, to) = (egui::pos2(a[0] - 4.0, a[1] - 4.0), egui::pos2(centre(b).0, centre(b).1));
+ send(&mut d, egui::Event::PointerMoved(from));
+ send(&mut d, egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
+ for k in 1..=10 {
+ send(&mut d, egui::Event::PointerMoved(from.lerp(to, k as f32 / 10.0)));
+ }
+ assert_eq!(selection(&mut d), sorted(vec![i0, i1]), "the selection follows the rectangle");
+ send(&mut d, egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
+ let end = egui::pos2(centre(c).0, centre(c).1);
+ send(&mut d, egui::Event::PointerMoved(end));
+ send(&mut d, egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
+ d.frames(2);
+ assert_eq!(selection(&mut d), vec![i2], "Escape restored the selection the drag began with");
+ }
+
+ #[test]
+ fn only_the_left_button_draws_a_marquee() {
+ let mut d = project_driver();
+ let cards = footage_in(&mut d, "icon");
+ let [(i0, a), (_, b)] = [cards[0], cards[1]];
+ d.exec("project.select", json!({"items": [i0]}));
+ let (from, to) = (egui::pos2(a[0] - 4.0, a[1] - 4.0), egui::pos2(centre(b).0, centre(b).1));
+ for button in [egui::PointerButton::Middle, egui::PointerButton::Secondary] {
+ let mut send = |e: egui::Event| {
+ d.harness.input_mut().events.push(e);
+ d.frames(1);
+ };
+ send(egui::Event::PointerMoved(from));
+ send(egui::Event::PointerButton { pos: from, button, pressed: true, modifiers: Default::default() });
+ for k in 1..=10 {
+ send(egui::Event::PointerMoved(from.lerp(to, k as f32 / 10.0)));
+ }
+ send(egui::Event::PointerButton { pos: to, button, pressed: false, modifiers: Default::default() });
+ d.key("Escape");
+ assert_eq!(selection(&mut d), vec![i0], "{button:?} drag left the selection alone");
+ assert!(!d.has("project.marquee"));
+ }
+ }
+
+ #[test]
+ fn marquee_selects_rows_in_list_view() {
+ let mut d = project_driver();
+ let rows = footage_in(&mut d, "list");
+ let n = rows.len();
+ let (last, before_last) = (rows[n - 1], rows[n - 2]);
+ let empty = d.rect("project.empty");
+ // from the empty space under the rows up into the second-to-last row
+ marquee(&mut d, (empty[0] + 60.0, empty[1] + 20.0), (empty[0] + 60.0, centre(before_last.1).1), false);
+ assert_eq!(selection(&mut d), sorted(vec![last.0, before_last.0]));
+ }
+
+ #[test]
+ fn marquee_selects_cards_in_freeform_view() {
+ let mut d = project_driver();
+ let cards = footage_in(&mut d, "freeform");
+ let [(i0, a), (i1, b)] = [cards[0], cards[1]];
+ assert!((a[1] - b[1]).abs() < 1.0, "the first two cards share a row");
+ marquee(&mut d, (a[0] - 6.0, a[1] - 6.0), centre(b), false);
+ assert_eq!(selection(&mut d), sorted(vec![i0, i1]));
+ assert!(!d.app().session.project.item(ItemId(i0)).unwrap().metadata.contains_key(FREEFORM_POS), "the marquee moved no card");
+ }