forge
Explore
Log in

Don't you dare go Hollow

Clips land where they mean to — snap to every lane, a line that says so, and a key that turns it off

Browse files at this commit

bd70ab19f6f3eed8b616be4443d0f121ec135165Ahmet Kaan GümüşParent: 9935946
  • feat
    • clips land where they mean to — snap to every lane, a line that says so, and a key that turns it off
Show full message
✨ feat(timeline): clips land where they mean to — snap to every lane, a line that says so, and a key that turns it off

The snap reached one gesture and one lane: a clip dropped on a track met
the edges already on that track and nothing else. A trim met nothing at
all, and a library row dropped on a lane landed on the raw frame under
the pointer.

Now every edge on the timeline is a target -- both ends of every clip on
every lane, the playhead, the head of the show -- and all three gestures
ask the same question: the clip drag, the edge trim, and the row let go
on a lane. A take on V1 lines up with the sound on A1, which is what a
cut across tracks means.

While the hand is still moving, the lanes draw the frame it is about to
land on: one pale line, under the playhead's own and in another colour,
and only while a gesture is live -- gpui drops a drag without telling
anyone, so the line asks whether one is in flight rather than remembering
that one was. A target the engine's own trim room clamps away draws
nothing: the line only promises what the release will do.

And it can be switched off, with "n" or the button beside the zoom: off,
a drag lands exactly where the hand leaves it and no line is drawn, which
is the frame-by-frame placement a magnet must never take away. The button
says which way it is set, because a toggle that looks the same either way
says nothing.
crates/app/src/keymap.rsmodified+14 -3
@@ -78,13 +78,14 @@ pub enum ActionId {
78 Speed,78 Speed,
79 Silence,79 Silence,
80 Mix,80 Mix,
81+ ToggleSnap,
81 CancelExport,82 CancelExport,
82 }83 }
83 84
84 impl ActionId {85 impl ActionId {
85 /// Display order everywhere -- the editor lists them in it and86 /// Display order everywhere -- the editor lists them in it and
86 /// [`Keymap::defaults`] binds them in it.87 /// [`Keymap::defaults`] binds them in it.
87- pub const ALL: [ActionId; 39] = [88+ pub const ALL: [ActionId; 40] = [
88 ActionId::Play,89 ActionId::Play,
89 ActionId::StepBack,90 ActionId::StepBack,
90 ActionId::StepForward,91 ActionId::StepForward,
@@ -123,6 +124,7 @@ impl ActionId {
123 ActionId::Speed,124 ActionId::Speed,
124 ActionId::Silence,125 ActionId::Silence,
125 ActionId::Mix,126 ActionId::Mix,
127+ ActionId::ToggleSnap,
126 ActionId::CancelExport,128 ActionId::CancelExport,
127 ];129 ];
128 130
@@ -167,6 +169,7 @@ impl ActionId {
167 ActionId::Speed => "Speed (tape)…",169 ActionId::Speed => "Speed (tape)…",
168 ActionId::Silence => "Silences: cut or speed up…",170 ActionId::Silence => "Silences: cut or speed up…",
169 ActionId::Mix => "Mix: track volumes and the limiter…",171 ActionId::Mix => "Mix: track volumes and the limiter…",
172+ ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
170 ActionId::CancelExport => "Cancel export",173 ActionId::CancelExport => "Cancel export",
171 }174 }
172 }175 }
@@ -213,6 +216,7 @@ impl ActionId {
213 ActionId::Speed => "speed",216 ActionId::Speed => "speed",
214 ActionId::Silence => "silence",217 ActionId::Silence => "silence",
215 ActionId::Mix => "mix",218 ActionId::Mix => "mix",
219+ ActionId::ToggleSnap => "toggle-snap",
216 ActionId::CancelExport => "cancel-export",220 ActionId::CancelExport => "cancel-export",
217 }221 }
218 }222 }
@@ -265,6 +269,9 @@ impl ActionId {
265 | ActionId::AddVideoLane269 | ActionId::AddVideoLane
266 | ActionId::AddAudioLane270 | ActionId::AddAudioLane
267 | ActionId::RemoveVideoLane271 | ActionId::RemoveVideoLane
272+ // Not a view setting despite being a pointer aid: it decides where
273+ // a drag actually lands, which is an edit and not a magnification.
274+ | ActionId::ToggleSnap
268 | ActionId::RemoveAudioLane => Category::Editing,275 | ActionId::RemoveAudioLane => Category::Editing,
269 ActionId::ToggleMute276 ActionId::ToggleMute
270 | ActionId::VolumeUp277 | ActionId::VolumeUp
@@ -645,6 +652,9 @@ impl Keymap {
645 // machine's volume and not the project's -- two things one key652 // machine's volume and not the project's -- two things one key
646 // must not mean.653 // must not mean.
647 b(ActionId::Mix, "f", false),654 b(ActionId::Mix, "f", false),
655+ // The snap takes "n", which is what every other editor toggles
656+ // it with: free here, and nowhere near the two keys that delete.
657+ b(ActionId::ToggleSnap, "n", false),
648 b(ActionId::CancelExport, "escape", false),658 b(ActionId::CancelExport, "escape", false),
649 ],659 ],
650 }660 }
@@ -907,7 +917,7 @@ mod tests {
907 #[test]917 #[test]
908 fn every_default_stroke_reaches_its_action() {918 fn every_default_stroke_reaches_its_action() {
909 let k = Keymap::defaults();919 let k = Keymap::defaults();
910- assert_eq!(k.entries().len(), 41);920+ assert_eq!(k.entries().len(), 42);
911 assert_eq!(k.lookup("space", false), Some(ActionId::Play));921 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
912 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two922 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
913 // ends of the timeline.923 // ends of the timeline.
@@ -1141,7 +1151,8 @@ mod tests {
1141 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1151 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1142 // The label is the editor's column, and never the file's word for it.1152 // The label is the editor's column, and never the file's word for it.
1143 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1153 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1144- assert_eq!(ActionId::ALL.len(), 39);1154+ assert_eq!(ActionId::ALL.len(), 40);
1155+ assert_eq!(k.display(ActionId::ToggleSnap), "n");
1145 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");1156 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1146 }1157 }
1147 1158
crates/app/src/main.rsmodified+275 -34
@@ -19,11 +19,11 @@ use engine::project::{Edge, Lane, LaneKind, Source, Speed};
19 use engine::scale::FitPolicy;19 use engine::scale::FitPolicy;
20 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};20 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
21 use gpui::{21 use gpui::{
22- AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,22+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,
23- KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,23+ FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
24- Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign,24+ PathBuilder, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size,
25- TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px,25+ Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img,
26- relative, rgb, rgba, size,26+ point, prelude::*, px, relative, rgb, rgba, size,
27 };27 };
28 28
29 /// Editor chrome: three grays and one accent, all darker than the picture so the29 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -749,6 +749,16 @@ struct Player {
749 /// the value being dragged, and stale between drags, which costs nothing --749 /// the value being dragged, and stale between drags, which costs nothing --
750 /// no drag starts without a press on the box it moves.750 /// no drag starts without a press on the box it moves.
751 grab: u32,751 grab: u32,
752+ /// Whether a drag or a trim is pulled onto the edges near it. On by
753+ /// default, because clips meeting exactly is what a timeline is for, and off
754+ /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement
755+ /// no magnet may take away.
756+ snap: bool,
757+ /// The frame the live gesture is about to land on, or `None` while it is
758+ /// over open bed: the line every lane draws so the snap is seen before it
759+ /// happens rather than discovered after the release. Stale between gestures,
760+ /// which costs nothing -- it is drawn only while one is live.
761+ snap_cue: Option<u32>,
752 last_scrub: Instant,762 last_scrub: Instant,
753 last_target: u32,763 last_target: u32,
754 /// The running export. While it owns the UI the editor is read-only.764 /// The running export. While it owns the UI the editor is read-only.
@@ -1092,12 +1102,26 @@ impl Player {
1092 ActionId::Speed => self.open_speed(cx),1102 ActionId::Speed => self.open_speed(cx),
1093 ActionId::Silence => self.open_silence(cx),1103 ActionId::Silence => self.open_silence(cx),
1094 ActionId::Mix => self.open_mix(None, cx),1104 ActionId::Mix => self.open_mix(None, cx),
1105+ ActionId::ToggleSnap => self.toggle_snap(cx),
1095 // Nothing to cancel while nothing is exporting; the export guard in1106 // Nothing to cancel while nothing is exporting; the export guard in
1096 // the key handler is what answers this one while there is.1107 // the key handler is what answers this one while there is.
1097 ActionId::CancelExport => {}1108 ActionId::CancelExport => {}
1098 }1109 }
1099 }1110 }
1100 1111
1112+ /// The magnet off and on again, in words: a snap that stops working
1113+ /// silently reads as a bug, and one that starts working silently reads as
1114+ /// one too. The line goes with it -- nothing is being promised any more.
1115+ fn toggle_snap(&mut self, cx: &mut Context<Self>) {
1116+ self.snap = !self.snap;
1117+ self.snap_cue = None;
1118+ self.notice = Some(match self.snap {
1119+ true => "SNAP ON — drags land on clip edges, the playhead and the start".into(),
1120+ false => "SNAP OFF — drags land exactly where the hand leaves them".into(),
1121+ });
1122+ cx.notify();
1123+ }
1124+
1101 /// The one place a clip becomes *the* selected one: a click, a right-click1125 /// The one place a clip becomes *the* selected one: a click, a right-click
1102 /// that opens the menu, and every selection key go through here, so what a1126 /// that opens the menu, and every selection key go through here, so what a
1103 /// keyboard marks and what a pointer marks are the same state marked the1127 /// keyboard marks and what a pointer marks are the same state marked the
@@ -2378,8 +2402,8 @@ impl Player {
2378 if self.exporting().is_some() {2402 if self.exporting().is_some() {
2379 return;2403 return;
2380 }2404 }
2381- let (Some(start), Some(was)) = (2405+ let (Some((start, _)), Some(was)) = (
2382- self.drop_frame(from, idx, to, x),2406+ self.drop_frame(from, idx, x),
2383 self.session2407 self.session
2384 .as_ref()2408 .as_ref()
2385 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),2409 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
@@ -2441,26 +2465,60 @@ impl Player {
2441 /// the scroll clamp pins the bed's right edge to the duration, and the2465 /// the scroll clamp pins the bed's right edge to the duration, and the
2442 /// pointer has no pixel past it. The upgrade is to let the scroll clamp2466 /// pointer has no pixel past it. The upgrade is to let the scroll clamp
2443 /// leave a screen of empty bed after the end, the way every NLE does.2467 /// leave a screen of empty bed after the end, the way every NLE does.
2444- fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> {2468+ fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
2445- let session = self.session.as_ref()?;2469+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
2446- let clip = session.lane_clips(from).get(idx).copied()?;
2447 let raw = self.frame_under(x).saturating_sub(self.grab);2470 let raw = self.frame_under(x).saturating_sub(self.grab);
2448- // The edges worth landing on: both ends of every clip already on the2471+ let marks = self.snap_targets(Some((from, idx)));
2449- // lane it is being let go over, the playhead, and the head of the2472+ Some(self.snap_to(raw, clip.frames(), &marks))
2450- // timeline. Never the group's own boxes -- a clip does not snap to2473+ }
2451- // where it already is.2474+
2452- let mut marks: Vec<u32> = session2475+ /// The line while the clip is still in the hand: the very answer
2453- .lane_clips(to)2476+ /// [`Player::drop_frame`] will commit, worked out on every move of the drag,
2454- .iter()2477+ /// so what the eye was promised is where the release puts it. A pointer that
2455- .enumerate()2478+ /// has wandered off the bed promises nothing.
2456- .filter(|&(i, c)| {2479+ fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) {
2457- (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link)2480+ let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue);
2458- })2481+ self.set_cue(cue, x, cx);
2459- .flat_map(|(_, c)| [c.start, c.end()])2482+ }
2460- .collect();2483+
2461- marks.push(frame_at(session.now(), self.fps));2484+ /// The same line for a library row on its way to a lane: it goes down at
2462- marks.push(0);2485+ /// the frame it is let go on ([`Player::insert_source`]), so that frame is
2463- Some(snapped(raw, clip.frames(), self.snap_frames(), &marks))2486+ /// what snaps and what is drawn. No length to snap by -- the file's own is
2487+ /// not known until the engine has placed it -- so only its head lands.
2488+ fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) {
2489+ let marks = self.snap_targets(None);
2490+ let cue = self.snap_to(self.frame_under(x), 0, &marks).1;
2491+ self.set_cue(cue, x, cx);
2492+ }
2493+
2494+ /// Sets the line, or takes it away, and repaints only when it moved: a
2495+ /// pointer dragged off the bed (up to the library, say) is not promising a
2496+ /// landing any more.
2497+ fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) {
2498+ let bed = self.ruler.get();
2499+ let cue = cue.filter(|_| x >= bed.left() && x <= bed.right());
2500+ if cue != self.snap_cue {
2501+ self.snap_cue = cue;
2502+ cx.notify();
2503+ }
2504+ }
2505+
2506+ /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its
2507+ /// lanes, so a clip meets a take one track over as readily as one beside it.
2508+ fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> {
2509+ let Some(session) = &self.session else {
2510+ return Vec::new();
2511+ };
2512+ let lanes = session.lanes();
2513+ let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect();
2514+ let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx)));
2515+ snap_marks(&clips, skip, frame_at(session.now(), self.fps))
2516+ }
2517+
2518+ /// Where a gesture at `raw` lands and the mark that pulled it there, with
2519+ /// the switch honoured: snapping off, nothing moves and no line is drawn.
2520+ fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) {
2521+ snap_cue(self.snap, raw, len, self.snap_frames(), marks)
2464 }2522 }
2465 2523
2466 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's2524 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
@@ -2524,14 +2582,25 @@ impl Player {
2524 /// against the same duration the boxes are drawn to, so the edge tracks the2582 /// against the same duration the boxes are drawn to, so the edge tracks the
2525 /// pointer exactly.2583 /// pointer exactly.
2526 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {2584 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2527- let at = self.frame_under(x);2585+ let Some(trim) = self.trim else {
2528- let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2529 return;2586 return;
2530 };2587 };
2531- let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {2588+ // The edge is pulled onto the same marks a whole clip is, by itself:
2589+ // there is no other end travelling with it, so it snaps at length zero.
2590+ let marks = self.snap_targets(Some((trim.lane, trim.idx)));
2591+ let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks);
2592+ let Some((lo, hi)) = self
2593+ .session
2594+ .as_ref()
2595+ .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge))
2596+ else {
2532 return;2597 return;
2533 };2598 };
2534- trim.to = at.clamp(lo, hi);2599+ let to = at.clamp(lo, hi);
2600+ // The line only stands where the edge actually stopped: a mark the
2601+ // engine's own room clamped away was never reached.
2602+ self.set_cue(cue.filter(|_| to == at), x, cx);
2603+ self.trim = Some(Trim { to, ..trim });
2535 cx.notify();2604 cx.notify();
2536 }2605 }
2537 2606
@@ -3806,6 +3875,21 @@ impl Render for Player {
3806 }3875 }
3807 }3876 }
3808 }))3877 }))
3878+ // A drop event carries no path of its own -- gpui only tells the
3879+ // target that something landed -- so the line that promises where
3880+ // it will land is fed by the drag's own moves, which do carry the
3881+ // pointer (gpui div.rs:282). On the root, because a drag crosses
3882+ // the window: it starts on a clip or on a library row and ends over
3883+ // a lane, and only an ancestor of both hears all of it.
3884+ .on_drag_move(cx.listener(|this, event: &DragMoveEvent<ClipDrag>, _, cx| {
3885+ let ClipDrag { lane, idx } = *event.drag(cx);
3886+ this.preview_drop(lane, idx, event.event.position.x, cx);
3887+ }))
3888+ .on_drag_move(
3889+ cx.listener(|this, event: &DragMoveEvent<AssetDrag>, _, cx| {
3890+ this.preview_place(event.event.position.x, cx);
3891+ }),
3892+ )
3809 // Scrubbing is tracked on the root because the pointer leaves the3893 // Scrubbing is tracked on the root because the pointer leaves the
3810 // 6 px ruler on the first drag and its own listeners then stop3894 // 6 px ruler on the first drag and its own listeners then stop
3811 // firing; the root's hitbox is the whole window.3895 // firing; the root's hitbox is the whole window.
@@ -4571,6 +4655,25 @@ impl Player {
4571 live,4655 live,
4572 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),4656 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
4573 ))4657 ))
4658+ // The magnet, beside the zoom for the zoom's own reason: it
4659+ // changes nothing on the timeline, it changes how the hand
4660+ // meets it. The label is the state, as the volume's is --
4661+ // a toggle that looks the same either way says nothing.
4662+ .child(control(
4663+ "snap",
4664+ None,
4665+ if self.snap { "Snap" } else { "No snap" },
4666+ format!(
4667+ "{} — {}",
4668+ key(ActionId::ToggleSnap),
4669+ match self.snap {
4670+ true => "drags and trims land on clip edges, the playhead and the start",
4671+ false => "drags and trims land exactly where the hand leaves them",
4672+ }
4673+ ),
4674+ live,
4675+ cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)),
4676+ ))
4574 // Import is not here: it belongs to the media list it adds4677 // Import is not here: it belongs to the media list it adds
4575 // to, and two doors into one action is a question about4678 // to, and two doors into one action is a question about
4576 // which one is the real one.4679 // which one is the real one.
@@ -6693,6 +6796,14 @@ impl Player {
6693 // it, so all of them move together when it does. No bed width is needed6796 // it, so all of them move together when it does. No bed width is needed
6694 // to place them any more -- a second is so many pixels wherever it is.6797 // to place them any more -- a second is so many pixels wherever it is.
6695 let scale = self.scale;6798 let scale = self.scale;
6799+ // Where the snap line stands, in the same pixels every box is placed
6800+ // through -- and only while a gesture is actually live: gpui drops a
6801+ // drag without telling anyone, so this asks whether one is in flight
6802+ // (`App::has_active_drag`) rather than remembering that one was.
6803+ let cue = self
6804+ .snap_cue
6805+ .filter(|_| self.trim.is_some() || cx.has_active_drag())
6806+ .map(|frame| scale.px_at(f64::from(frame) / self.fps));
6696 let clips = self6807 let clips = self
6697 .session6808 .session
6698 .as_ref()6809 .as_ref()
@@ -6839,7 +6950,12 @@ impl Player {
6839 // the window, which took it from the release that fired6950 // the window, which took it from the release that fired
6840 // this (gpui window.rs:3602).6951 // this (gpui window.rs:3602).
6841 .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| {6952 .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| {
6842- let at = this.frame_under(window.mouse_position().x);6953+ // Onto the edges near it, exactly as a clip carried by
6954+ // hand lands: the line drawn while it was in flight is
6955+ // the frame it goes down on.
6956+ let x = window.mouse_position().x;
6957+ let marks = this.snap_targets(None);
6958+ let (at, _) = this.snap_to(this.frame_under(x), 0, &marks);
6843 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)6959 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)
6844 }))6960 }))
6845 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))6961 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
@@ -7083,6 +7199,20 @@ impl Player {
7083 .bg(rgba(0x4a9effaa))7199 .bg(rgba(0x4a9effaa))
7084 }),7200 }),
7085 )7201 )
7202+ // What the gesture in flight is about to land on, drawn on
7203+ // every lane so a clip lining up with a take one track over
7204+ // can be seen to line up with it. Under the playhead's line
7205+ // and in another colour, since the two mean different
7206+ // things and often stand on the same pixel.
7207+ .children(cue.map(|x| {
7208+ div()
7209+ .absolute()
7210+ .top_0()
7211+ .h_full()
7212+ .left(px(x))
7213+ .w(px(1.))
7214+ .bg(rgb(INK))
7215+ }))
7086 // Last, so it is over the clips: the same fraction in both7216 // Last, so it is over the clips: the same fraction in both
7087 // lanes, which is the playhead being one line.7217 // lanes, which is the playhead being one line.
7088 .child(7218 .child(
@@ -8732,6 +8862,56 @@ fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
8732 best.map_or(raw, |(_, start)| start)8862 best.map_or(raw, |(_, start)| start)
8733 }8863 }
8734 8864
8865+/// The edges worth landing on, off *every* lane: both ends of every clip on the
8866+/// timeline, less `skip` -- the clip being dragged, which does not snap to where
8867+/// it already is -- and less the other halves of its group, which travel with
8868+/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead
8869+/// and the head of the timeline go on the end: a clip meets the cursor and the
8870+/// start of the show as readily as it meets another take.
8871+///
8872+/// All lanes rather than the one being dropped on, because a cut is made across
8873+/// the timeline: a title on V2 lines up with the shot under it, and a sound
8874+/// effect lines up with the frame it belongs to.
8875+fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec<u32> {
8876+ let link = skip
8877+ .and_then(|(lane, idx)| lanes.get(lane)?.get(idx))
8878+ .and_then(|clip| clip.link);
8879+ let mut marks: Vec<u32> = lanes
8880+ .iter()
8881+ .enumerate()
8882+ .flat_map(|(lane, clips)| {
8883+ clips
8884+ .iter()
8885+ .enumerate()
8886+ .filter(move |&(idx, clip)| {
8887+ Some((lane, idx)) != skip && !(link.is_some() && clip.link == link)
8888+ })
8889+ .flat_map(|(_, clip)| [clip.start, clip.end()])
8890+ })
8891+ .collect();
8892+ marks.push(playhead);
8893+ marks.push(0);
8894+ marks
8895+}
8896+
8897+/// [`snapped`], and the mark that pulled it there -- the line the bed draws
8898+/// while the hand is still moving. `None` when nothing was near enough: a line
8899+/// standing over open bed would promise a landing that is not going to happen.
8900+/// The head is read before the tail, exactly as [`snapped`] prefers it.
8901+///
8902+/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
8903+/// draws no line at all, which is the whole point of being able to turn it off.
8904+fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option<u32>) {
8905+ if !on {
8906+ return (raw, None);
8907+ }
8908+ let start = snapped(raw, len, tol, marks);
8909+ let mark = [start, start.saturating_add(len)]
8910+ .into_iter()
8911+ .find(|mark| marks.contains(mark));
8912+ (start, mark)
8913+}
8914+
8735 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin8915 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin
8736 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An8916 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
8737 /// element that was never painted reads as its middle -- flat, the one answer8917 /// element that was never painted reads as its middle -- flat, the one answer
@@ -9073,9 +9253,9 @@ mod tests {
9073 estimated_mb, export_path, export_settings, format_key, format_line, format_refusal,9253 estimated_mb, export_path, export_settings, format_key, format_line, format_refusal,
9074 fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,9254 fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,
9075 keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h,9255 keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h,
9076- project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped,9256+ project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snap_cue,
9077- source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, transport,9257+ snap_marks, snapped, source_tint, span_partner, speed_at, summary_head, summary_tail,
9078- unseen_paths, unseen_sources, whole_take, window_title,9258+ timecode, transport, unseen_paths, unseen_sources, whole_take, window_title,
9079 };9259 };
9080 use super::{9260 use super::{
9081 LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP,9261 LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP,
@@ -9503,6 +9683,9 @@ mod tests {
9503 source.contains("this.remove_lane(lane, cx)")9683 source.contains("this.remove_lane(lane, cx)")
9504 }9684 }
9505 ActionId::ToggleMute => element("volume"),9685 ActionId::ToggleMute => element("volume"),
9686+ // The button beside the zoom, which says which way it is
9687+ // set as well as setting it.
9688+ ActionId::ToggleSnap => element("snap"),
9506 // The fader on every audio track's own header, which is9689 // The fader on every audio track's own header, which is
9507 // also what opens the card the limiter is on.9690 // also what opens the card the limiter is on.
9508 ActionId::Mix => element("mix-lane"),9691 ActionId::Mix => element("mix-lane"),
@@ -10203,6 +10386,62 @@ mod tests {
10203 assert_eq!(snapped(2, 40, 4, &marks), 0);10386 assert_eq!(snapped(2, 40, 4, &marks), 0);
10204 }10387 }
10205 10388
10389+ /// Where those edges come from: every lane, not the one being dropped on --
10390+ /// and never the clip in the hand or the half of it one track down.
10391+ #[test]
10392+ fn the_marks_are_every_lane_the_playhead_and_the_start() {
10393+ let clip = |start: u32, frames: u32, link| Clip {
10394+ start,
10395+ in_frame: 0,
10396+ out_frame: frames,
10397+ source: 0,
10398+ link,
10399+ eq: None,
10400+ color: None,
10401+ fit: Default::default(),
10402+ speed: Default::default(),
10403+ };
10404+ // A grouped take across two lanes at 100..160, and a lone one on the
10405+ // audio lane at 400..430.
10406+ let video = [clip(100, 60, Some(7))];
10407+ let audio = [clip(100, 60, Some(7)), clip(400, 30, None)];
10408+ let lanes: [&[Clip]; 2] = [&video, &audio];
10409+
10410+ // Nothing in the hand: both lanes' edges, the playhead, and 0.
10411+ let mut all = snap_marks(&lanes, None, 300);
10412+ all.sort_unstable();
10413+ assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]);
10414+
10415+ // The video half in the hand: its own edges are gone, and so are its
10416+ // group's on the other lane -- both boxes travel with the drag. The
10417+ // lone audio clip is still a target, which is the whole point: a take
10418+ // being carried on V1 lands flush with a sound on A1.
10419+ let mut carried = snap_marks(&lanes, Some((0, 0)), 300);
10420+ carried.sort_unstable();
10421+ assert_eq!(carried, [0, 300, 400, 430]);
10422+
10423+ // An index that names no clip skips nothing and still answers.
10424+ assert_eq!(snap_marks(&[], Some((3, 9)), 0), [0, 0]);
10425+ }
10426+
10427+ /// The line the bed draws, and the switch that turns the whole thing off.
10428+ #[test]
10429+ fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() {
10430+ let marks = [100, 160, 300, 0];
10431+ // Pulled by the tail: the clip lands at 60 and the line stands on the
10432+ // edge its *tail* met, 100 -- not on the head it happens to have.
10433+ assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100)));
10434+ // Pulled by the head: line and landing are the same frame.
10435+ assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160)));
10436+ // A trim carries no length, so only its own edge lands.
10437+ assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300)));
10438+ // Open bed: nothing moves and nothing is drawn.
10439+ assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None));
10440+ // Switched off, a gesture that would have snapped lands raw and draws
10441+ // no line -- the frame-by-frame placement the toggle is for.
10442+ assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
10443+ }
10444+
10206 #[test]10445 #[test]
10207 fn timecode_counts_frames_inside_the_second() {10446 fn timecode_counts_frames_inside_the_second() {
10208 assert_eq!(timecode(0., 30.), "00:00:00:00");10447 assert_eq!(timecode(0., 30.), "00:00:00:00");
@@ -12115,6 +12354,8 @@ fn main() {
12115 scrubbing: false,12354 scrubbing: false,
12116 trim: None,12355 trim: None,
12117 grab: 0,12356 grab: 0,
12357+ snap: true,
12358+ snap_cue: None,
12118 last_scrub: Instant::now(),12359 last_scrub: Instant::now(),
12119 last_target: 0,12360 last_target: 0,
12120 export: None,12361 export: None,