Skip to content

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

timeline: update box selection live while it is dragged

ReReddo9f4814335be4
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index d5766c0bb..0d1c51107 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -151,8 +151,12 @@ pub enum Drag {
Pan {
last: Pos2,
},
+ /// Box selection, shown live: `before` is the selection when the drag began, which Shift or
+ /// Ctrl (`add`) keep; the release commits one `timeline.select`.
Marquee {
start: Pos2,
+ before: Vec<ClipId>,
+ add: bool,
},
Divider,
ZoomBar {
@@ -1697,6 +1701,18 @@ fn preview_drag(app: &FilmcraftApp, seq: &Sequence, out: &mut HashMap<ClipId, (T
}
}
+/// The clips a marquee rectangle touches, on the tracks it crosses.
+fn marquee_clips(seq: &Sequence, layout: &Layout, r: Rect) -> Vec<ClipId> {
+ let (a, b) = (layout.tick_at(r.min.x), layout.tick_at(r.max.x));
+ layout
+ .rows
+ .iter()
+ .filter(|row| row.rect.intersects(r))
+ .filter_map(|row| seq.track(row.track))
+ .flat_map(|tr| tr.items.iter().filter(|i| i.start < b && i.end() > a).map(|i| i.id))
+ .collect()
+}
+
fn shift_track(seq: &Sequence, tid: TrackId, delta: i32) -> Option<TrackId> {
if delta == 0 {
return Some(tid);
@@ -2163,7 +2179,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
// the video and audio tracks, #683)
(_, Grab::Other(hit @ (Hit::Empty { .. } | Hit::None))) if layout.content.contains(p) => {
if resp.drag_started() {
- Some(Drag::Marquee { start: p })
+ Some(Drag::Marquee { start: p, before: app.session.state.selection.clone(), add: mods.shift || mods.command })
} else {
app.session.state.selection.clear();
app.session.state.edit_points.clear();
@@ -2278,11 +2294,20 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
Some(Drag::Transition { id, edge, from, start, duration })
}
Drag::Volume(v) => Some(Drag::Volume(super::timeline_volume::drag(app, ui, seq, layout, v, p.y))),
- Drag::Marquee { start } => {
+ Drag::Marquee { start, before, add } => {
let r = Rect::from_two_pos(start, p);
ui.painter().rect_filled(r, 0.0, Color32::from_white_alpha(18));
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_white_alpha(140)), StrokeKind::Inside);
- Some(Drag::Marquee { start })
+ // the clips in the box are selected as it grows and shrinks; only the release runs
+ // the command, so the drag is one selection change
+ let mut sel = if add { before.clone() } else { Vec::new() };
+ for c in filmcraft_engine::commands::with_links(&app.session, &marquee_clips(seq, layout, r)) {
+ if !sel.contains(&c) {
+ sel.push(c);
+ }
+ }
+ app.session.state.selection = sel;
+ Some(Drag::Marquee { start, before, add })
}
other => Some(other),
};
@@ -2329,20 +2354,15 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let moved = seq.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == id)).is_some_and(|x| (x.start, x.duration) != (start, duration));
moved.then(|| app.session.execute("sequence.setTransition", json!({"transition": id.0, "start": start.0, "duration": duration.0})))
}
- Drag::Marquee { start } => {
- if let Some(end) = resp.interact_pointer_pos() {
- let r = Rect::from_two_pos(start, end);
- let (a, b) = (layout.tick_at(r.min.x), layout.tick_at(r.max.x));
- let ids: Vec<u64> = layout
- .rows
- .iter()
- .filter(|row| row.rect.intersects(r))
- .filter_map(|row| seq.track(row.track))
- .flat_map(|tr| tr.items.iter().filter(|i| i.start < b && i.end() > a).map(|i| i.id.0))
- .collect();
- Some(app.session.execute("timeline.select", json!({"clips": ids, "add": mods.shift})))
- } else {
- None
+ Drag::Marquee { start, before, add } => {
+ app.session.state.selection = before;
+ // egui ends a drag on Escape: that cancels the box, as in the Project panel
+ match resp.interact_pointer_pos() {
+ Some(end) if !ctx.input(|i| i.key_pressed(egui::Key::Escape)) => {
+ let ids: Vec<u64> = marquee_clips(seq, layout, Rect::from_two_pos(start, end)).iter().map(|c| c.0).collect();
+ Some(app.session.execute("timeline.select", json!({"clips": ids, "add": add})))
+ }
+ _ => None,
}
}
_ => None,
diff --git a/crates/ui-egui/tests/timeline_marquee_ui.rs b/crates/ui-egui/tests/timeline_marquee_ui.rs
new file mode 100644
index 000000000..962eefbac
--- /dev/null
+++ b/crates/ui-egui/tests/timeline_marquee_ui.rs
@@ -0,0 +1,159 @@
+//! Headless UI tests of box (marquee) selection in the Timeline: the selection follows the box
+//! while it is dragged, Shift adds to the selection the drag began with, and Escape cancels.
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_project::ClipId;
+use filmcraft_ui_egui::FilmcraftApp;
+use filmcraft_ui_egui::control::ControlRequest;
+use serde_json::{Value, json};
+
+struct Driver {
+ harness: Harness<'static, FilmcraftApp>,
+ tx: Sender<ControlRequest>,
+ modifiers: egui::Modifiers,
+}
+
+impl Driver {
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let app = FilmcraftApp::new(session).with_control(rx);
+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, modifiers: egui::Modifiers::NONE };
+ d.frames(4);
+ d
+ }
+
+ fn frames(&mut self, n: usize) {
+ for _ in 0..n {
+ let ctx = self.harness.ctx.clone();
+ let mut raw = std::mem::take(self.harness.input_mut());
+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
+ *self.harness.input_mut() = raw;
+ self.harness.step();
+ }
+ }
+
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let (req, reply) = ControlRequest::new(method, params.clone());
+ self.tx.send(req).unwrap();
+ for _ in 0..600 {
+ self.frames(1);
+ if let Ok(v) = reply.try_recv() {
+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");
+ return v["result"].clone();
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+
+ fn exec(&mut self, command: &str, params: Value) -> Value {
+ self.ok("engine.execute", json!({"command": command, "params": params}))
+ }
+
+ fn rect(&mut self, id: &str) -> egui::Rect {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("no element {id}")).clone();
+ let r: Vec<f32> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect();
+ egui::Rect::from_min_size(egui::pos2(r[0], r[1]), egui::vec2(r[2], r[3]))
+ }
+
+ fn send(&mut self, e: egui::Event) {
+ let modifiers = self.modifiers;
+ self.harness.input_mut().events.extend([egui::Event::ModifiersChanged(modifiers), e]);
+ self.frames(1);
+ }
+
+ fn button(&mut self, pos: egui::Pos2, pressed: bool) {
+ let modifiers = self.modifiers;
+ self.send(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers });
+ }
+
+ /// Move the pointer to `to` in small steps, a frame each.
+ fn move_to(&mut self, from: egui::Pos2, to: egui::Pos2) {
+ for k in 1..=8 {
+ self.send(egui::Event::PointerMoved(from.lerp(to, k as f32 / 8.0)));
+ }
+ }
+
+ fn selected(&self, clip: u64) -> bool {
+ self.harness.state().session.state.selection.contains(&ClipId(clip))
+ }
+
+ /// The last two clips of Video 1, and a point on Video 1 just past the end of the sequence.
+ fn setup(&mut self) -> (u64, u64, egui::Rect, egui::Rect, egui::Pos2) {
+ self.ok("ui.set", json!({"focused": "Timeline"}));
+ let seq = self.exec("sequence.inspect", json!({}));
+ let items = seq["video"][0]["items"].as_array().unwrap().clone();
+ let id = |i: &Value| i["clip"].as_u64().unwrap();
+ let (a, b) = (id(&items[items.len() - 2]), id(&items[items.len() - 1]));
+ let (ra, rb) = (self.rect(&format!("timeline.clip.{a}")), self.rect(&format!("timeline.clip.{b}")));
+ let start = egui::pos2(rb.max.x + 12.0, rb.center().y);
+ assert_eq!(self.ok("ui.timeline.hit", json!({"x": start.x, "y": start.y}))["hit"], "empty", "the drag starts on empty space");
+ (a, b, ra, rb, start)
+ }
+}
+
+#[test]
+fn the_selection_follows_the_box_while_it_is_dragged() {
+ let mut d = Driver::demo();
+ let (a, b, ra, rb, start) = d.setup();
+ d.exec("timeline.select", json!({"clips": []}));
+ d.send(egui::Event::PointerMoved(start));
+ d.button(start, true);
+ // into the last clip: selected before the button comes up
+ let over_b = egui::pos2(rb.center().x, start.y + 2.0);
+ d.move_to(start, over_b);
+ assert!(d.selected(b) && !d.selected(a), "the box selects what it touches as it grows");
+ // on into the clip before it
+ let over_a = egui::pos2(ra.center().x, start.y + 2.0);
+ d.move_to(over_b, over_a);
+ assert!(d.selected(a) && d.selected(b));
+ // and back: the clip that left the box is no longer selected
+ d.move_to(over_a, over_b);
+ assert!(d.selected(b) && !d.selected(a), "a clip leaving the box is deselected");
+ d.button(over_b, false);
+ d.frames(2);
+ assert!(d.selected(b) && !d.selected(a), "the release keeps what the box showed");
+}
+
+#[test]
+fn shift_adds_to_the_selection_the_drag_began_with() {
+ let mut d = Driver::demo();
+ let (a, b, _, rb, start) = d.setup();
+ d.exec("timeline.select", json!({"clips": [a]}));
+ d.modifiers = egui::Modifiers::SHIFT;
+ d.send(egui::Event::PointerMoved(start));
+ d.button(start, true);
+ let over_b = egui::pos2(rb.center().x, start.y + 2.0);
+ d.move_to(start, over_b);
+ assert!(d.selected(a) && d.selected(b), "Shift keeps the earlier selection and adds the box");
+ // shrinking the box to nothing leaves the selection the drag began with
+ d.move_to(over_b, start + egui::vec2(-2.0, 2.0));
+ assert!(d.selected(a) && !d.selected(b));
+ d.move_to(start + egui::vec2(-2.0, 2.0), over_b);
+ d.button(over_b, false);
+ d.modifiers = egui::Modifiers::NONE;
+ d.frames(2);
+ assert!(d.selected(a) && d.selected(b));
+}
+
+#[test]
+fn escape_cancels_the_box_and_restores_the_selection() {
+ let mut d = Driver::demo();
+ let (a, b, ra, _, start) = d.setup();
+ d.exec("timeline.select", json!({"clips": [a]}));
+ d.send(egui::Event::PointerMoved(start));
+ d.button(start, true);
+ let over_a = egui::pos2(ra.center().x, start.y + 2.0);
+ d.move_to(start, over_a);
+ assert!(d.selected(b));
+ d.send(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
+ d.button(over_a, false);
+ d.frames(2);
+ assert!(d.selected(a) && !d.selected(b), "Escape put back the selection the drag began with");
+}