forge
Explore
Log in

Don't you dare go Hollow

Merge remote-tracking branch 'origin/main' into worktree-agent-abe7c9ebe8b525c5f

Browse files at this commit

5007fc6eb0d811ea7239f3524e04bdc73d3a650bAhmet Kaan GümüşParent: 79da4461c58757
crates/app/src/keymap.rsmodified+41 -5
@@ -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
@@ -326,7 +333,7 @@ pub struct Fixed {
326 pub category: Category,333 pub category: Category,
327 }334 }
328 335
329-pub const FIXED: [Fixed; 21] = [336+pub const FIXED: [Fixed; 26] = [
330 // Not a chord at all but a way of pressing one, and the only place the337 // Not a chord at all but a way of pressing one, and the only place the
331 // editor can say so: holding a key that moves a *value* runs it, and338 // editor can say so: holding a key that moves a *value* runs it, and
332 // holding anything else still does what one press did.339 // holding anything else still does what one press did.
@@ -394,7 +401,7 @@ pub const FIXED: [Fixed; 21] = [
394 // its own: a band nothing but a drag can reach is a band half the users of401 // its own: a band nothing but a drag can reach is a band half the users of
395 // this editor cannot move at all. Card-local, so none of them is bindable.402 // this editor cannot move at all. Card-local, so none of them is bindable.
396 Fixed {403 Fixed {
397- chord: "1–5",404+ chord: "1–9, 0",
398 label: "Pick an equalizer band",405 label: "Pick an equalizer band",
399 category: Category::Audio,406 category: Category::Audio,
400 },407 },
@@ -408,6 +415,31 @@ pub const FIXED: [Fixed; 21] = [
408 label: "Lower the picked band 1 dB",415 label: "Lower the picked band 1 dB",
409 category: Category::Audio,416 category: Category::Audio,
410 },417 },
418+ Fixed {
419+ chord: "← / →",
420+ label: "Move the picked band down or up in frequency",
421+ category: Category::Audio,
422+ },
423+ Fixed {
424+ chord: "shift ← / →",
425+ label: "Widen or narrow the picked band (its Q)",
426+ category: Category::Audio,
427+ },
428+ Fixed {
429+ chord: "a",
430+ label: "Add an equalizer band beside the picked one",
431+ category: Category::Audio,
432+ },
433+ Fixed {
434+ chord: "x",
435+ label: "Remove the picked equalizer band",
436+ category: Category::Audio,
437+ },
438+ Fixed {
439+ chord: "f",
440+ label: "Flatten the picked band (double-click does the same)",
441+ category: Category::Audio,
442+ },
411 Fixed {443 Fixed {
412 chord: "r",444 chord: "r",
413 label: "Flatten every band",445 label: "Flatten every band",
@@ -645,6 +677,9 @@ impl Keymap {
645 // machine's volume and not the project's -- two things one key677 // machine's volume and not the project's -- two things one key
646 // must not mean.678 // must not mean.
647 b(ActionId::Mix, "f", false),679 b(ActionId::Mix, "f", false),
680+ // The snap takes "n", which is what every other editor toggles
681+ // it with: free here, and nowhere near the two keys that delete.
682+ b(ActionId::ToggleSnap, "n", false),
648 b(ActionId::CancelExport, "escape", false),683 b(ActionId::CancelExport, "escape", false),
649 ],684 ],
650 }685 }
@@ -907,7 +942,7 @@ mod tests {
907 #[test]942 #[test]
908 fn every_default_stroke_reaches_its_action() {943 fn every_default_stroke_reaches_its_action() {
909 let k = Keymap::defaults();944 let k = Keymap::defaults();
910- assert_eq!(k.entries().len(), 41);945+ assert_eq!(k.entries().len(), 42);
911 assert_eq!(k.lookup("space", false), Some(ActionId::Play));946 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
912 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two947 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
913 // ends of the timeline.948 // ends of the timeline.
@@ -1141,7 +1176,8 @@ mod tests {
1141 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");1176 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.1177 // The label is the editor's column, and never the file's word for it.
1143 assert_eq!(ActionId::CancelExport.label(), "Cancel export");1178 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1144- assert_eq!(ActionId::ALL.len(), 39);1179+ assert_eq!(ActionId::ALL.len(), 40);
1180+ assert_eq!(k.display(ActionId::ToggleSnap), "n");
1145 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");1181 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1146 }1182 }
1147 1183
crates/app/src/main.rsmodified+1141 -188
@@ -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
@@ -85,6 +85,13 @@ const WAVE_BPS: u32 = 40;
85 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,85 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
86 /// and a path with a point per pixel is a path per repaint.86 /// and a path with a point per pixel is a path per repaint.
87 const WAVE_COL: f32 = 2.;87 const WAVE_COL: f32 = 2.;
88+/// The most columns one envelope is ever built from. A waveform is drawn into
89+/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a
90+/// screen wide, so nothing on screen ever reaches this -- it is the backstop for
91+/// a box laid out wider than any screen, whose path would otherwise cost a point
92+/// per two pixels of a width nobody can see and stall the repaint that was
93+/// meant to draw the wave.
94+const WAVE_COLS_MAX: usize = 4096;
88 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px95 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
89 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.96 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.
90 const HIT_MIN: f32 = 24.;97 const HIT_MIN: f32 = 24.;
@@ -281,6 +288,13 @@ struct AssetDrag(PathBuf, usize);
281 struct ClipDrag {288 struct ClipDrag {
282 lane: Lane,289 lane: Lane,
283 idx: usize,290 idx: usize,
291+ /// The clip that was picked up, so the drop can find it again: gpui freezes
292+ /// the payload for the whole gesture, and an edit made *during* one -- a
293+ /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples
294+ /// the indices under it. The index alone would then name a different take at
295+ /// the release, and the drag would move a clip nobody touched (see
296+ /// [`live_idx`]).
297+ clip: Clip,
284 }298 }
285 299
286 /// A clip edge being dragged: which end of which clip, and the timeline frame300 /// A clip edge being dragged: which end of which clip, and the timeline frame
@@ -569,6 +583,36 @@ const EQ_FREQ_HIGH: f32 = 20_000.;
569 /// and short enough that the card still fits a 360 px window.583 /// and short enough that the card still fits a 360 px window.
570 const EQ_GRAPH_H: f32 = 132.;584 const EQ_GRAPH_H: f32 = 132.;
571 585
586+/// How wide the equalizer card is allowed to get. It is the one card that is a
587+/// *graph*: every pixel across is frequency resolution, and at the 320 px the
588+/// other cards use, a third of an octave was a couple of pixels. Past this the
589+/// curve stops gaining anything and the card starts reading as a wall.
590+const EQ_W_MAX: f32 = 720.;
591+
592+/// The gap the card leaves either side of it, so it reads as a card on a scrim
593+/// rather than as a second window: it takes the width it can get inside that.
594+const EQ_W_MARGIN: f32 = 32.;
595+
596+/// How many bands one clip's equalizer may carry from this card. Ten because
597+/// the keyboard picks a band with a digit and a keyboard has ten of them --
598+/// past that a band would be reachable by pointer only. The engine itself caps
599+/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more
600+/// and this card will draw and edit every one it finds.
601+const EQ_BANDS_MAX: usize = 10;
602+
603+/// One press of the frequency keys, as a factor: a sixth of an octave, so a
604+/// band walks the whole axis in about sixty presses and still lands close
605+/// enough to a named frequency to aim at one.
606+const EQ_FREQ_STEP: f32 = 1.122_462;
607+
608+/// One press of the Q keys, as a factor, and the range they move in. Below the
609+/// bottom a peak is barely a peak any more; above the top it is a whistle on
610+/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside
611+/// them, so nothing a file carries has to be dragged into range first.
612+const EQ_Q_STEP: f32 = 1.25;
613+const EQ_Q_LOW: f32 = 0.3;
614+const EQ_Q_HIGH: f32 = 12.;
615+
572 /// How many points the curve is drawn from. One per ~3 px across the card:616 /// How many points the curve is drawn from. One per ~3 px across the card:
573 /// past that the line is smooth and the extra biquad evaluations are wasted.617 /// past that the line is smooth and the extra biquad evaluations are wasted.
574 const EQ_CURVE_STEPS: usize = 96;618 const EQ_CURVE_STEPS: usize = 96;
@@ -617,6 +661,11 @@ const EQ_SPECTRUM_INK: u32 = 0x7f95ad66;
617 /// its weight: it is what makes a boost read as a hill rather than as a wire.661 /// its weight: it is what makes a boost read as a hill rather than as a wire.
618 const EQ_FILL_INK: u32 = 0x4a9eff26;662 const EQ_FILL_INK: u32 = 0x4a9eff26;
619 663
664+/// One band's own response, drawn under the sum: a dim thread per band, so a
665+/// boost pushed against a cut can be *seen* as two bands rather than as the
666+/// flat line their total makes.
667+const EQ_BELL_INK: u32 = 0x4a9eff66;
668+
620 /// The colour card's four controls, in the order it lists them: what each is669 /// The colour card's four controls, in the order it lists them: what each is
621 /// called and the range it moves in. The order is `ColorParams`' own, which is670 /// called and the range it moves in. The order is `ColorParams`' own, which is
622 /// what [`color_band`] indexes.671 /// what [`color_band`] indexes.
@@ -790,6 +839,16 @@ struct Player {
790 /// the value being dragged, and stale between drags, which costs nothing --839 /// the value being dragged, and stale between drags, which costs nothing --
791 /// no drag starts without a press on the box it moves.840 /// no drag starts without a press on the box it moves.
792 grab: u32,841 grab: u32,
842+ /// Whether a drag or a trim is pulled onto the edges near it. On by
843+ /// default, because clips meeting exactly is what a timeline is for, and off
844+ /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement
845+ /// no magnet may take away.
846+ snap: bool,
847+ /// The frame the live gesture is about to land on, or `None` while it is
848+ /// over open bed: the line every lane draws so the snap is seen before it
849+ /// happens rather than discovered after the release. Stale between gestures,
850+ /// which costs nothing -- it is drawn only while one is live.
851+ snap_cue: Option<u32>,
793 last_scrub: Instant,852 last_scrub: Instant,
794 last_target: u32,853 last_target: u32,
795 /// The running export. While it owns the UI the editor is read-only.854 /// The running export. While it owns the UI the editor is read-only.
@@ -1133,12 +1192,26 @@ impl Player {
1133 ActionId::Speed => self.open_speed(cx),1192 ActionId::Speed => self.open_speed(cx),
1134 ActionId::Silence => self.open_silence(cx),1193 ActionId::Silence => self.open_silence(cx),
1135 ActionId::Mix => self.open_mix(None, cx),1194 ActionId::Mix => self.open_mix(None, cx),
1195+ ActionId::ToggleSnap => self.toggle_snap(cx),
1136 // Nothing to cancel while nothing is exporting; the export guard in1196 // Nothing to cancel while nothing is exporting; the export guard in
1137 // the key handler is what answers this one while there is.1197 // the key handler is what answers this one while there is.
1138 ActionId::CancelExport => {}1198 ActionId::CancelExport => {}
1139 }1199 }
1140 }1200 }
1141 1201
1202+ /// The magnet off and on again, in words: a snap that stops working
1203+ /// silently reads as a bug, and one that starts working silently reads as
1204+ /// one too. The line goes with it -- nothing is being promised any more.
1205+ fn toggle_snap(&mut self, cx: &mut Context<Self>) {
1206+ self.snap = !self.snap;
1207+ self.snap_cue = None;
1208+ self.notice = Some(match self.snap {
1209+ true => "SNAP ON — drags land on clip edges, the playhead and the start".into(),
1210+ false => "SNAP OFF — drags land exactly where the hand leaves them".into(),
1211+ });
1212+ cx.notify();
1213+ }
1214+
1142 /// Whether the editor can be asked for `action` right now, and why not when1215 /// Whether the editor can be asked for `action` right now, and why not when
1143 /// it cannot. `on` is the clip the question is about -- the one a clip menu1216 /// it cannot. `on` is the clip the question is about -- the one a clip menu
1144 /// was opened on -- and `None` asks about the marked clip instead, which is1217 /// was opened on -- and `None` asks about the marked clip instead, which is
@@ -2016,41 +2089,78 @@ impl Player {
2016 cx.notify();2089 cx.notify();
2017 }2090 }
2018 2091
2019- /// Moves one band and says whether anything changed. Live only: the write2092+ /// Changes the picked band in place and says whether anything moved. Every
2020- /// is [`commit_eq`](Player::commit_eq)'s.2093+ /// edit of a band goes through here -- the drag, each key, each stepper
2021- fn set_band(&mut self, band: usize, gain_db: f32) -> bool {2094+ /// button -- so the card has exactly one place that clamps a band into what
2022- let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);2095+ /// the graph can draw, and no caller has to remember the limits.
2023- match self.eq_params.bands.get_mut(band) {2096+ fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
2024- Some(b) if b.gain_db != gain_db => {2097+ let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
2025- b.gain_db = gain_db;2098+ return false;
2026- true2099+ };
2027- }2100+ let was = *band;
2028- _ => false,2101+ change(band);
2102+ band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH);
2103+ band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
2104+ band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH);
2105+ *band != was
2106+ }
2107+
2108+ /// The keyboard's and the buttons' version of a drag: one step on the picked
2109+ /// band, committed straight away -- neither has a release to wait for.
2110+ fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) {
2111+ if self.set_band(change) {
2112+ self.commit_eq(cx);
2029 }2113 }
2030 }2114 }
2031 2115
2032- /// The keyboard's version of a drag: one step on the picked band, committed2116+ /// Where the pointer sits in the graph, as the picked band's frequency and
2033- /// straight away -- a keystroke has no release to wait for.2117+ /// gain: across is the frequency axis and down is the gain one, so the
2034- fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {2118+ /// handle follows the hand both ways rather than sliding up a rail. Called
2035- let gain = self2119+ /// on every pointer sample, so the curve bends under it; the write is the
2036- .eq_params2120+ /// release's ([`commit_eq`](Player::commit_eq)).
2037- .bands2121+ fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
2038- .get(self.eq_band)2122+ let bounds = self.eq_graph.get();
2039- .map_or(0., |b| b.gain_db);2123+ let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
2040- if self.set_band(self.eq_band, gain + by) {2124+ let freq = eq_freq(frac_along(at.x, bounds));
2041- self.commit_eq(cx);2125+ if self.set_band(|b| {
2126+ b.gain_db = gain;
2127+ b.freq_hz = freq;
2128+ }) {
2129+ cx.notify();
2042 }2130 }
2043 }2131 }
2044 2132
2045- /// Where the pointer sits down the graph, as a gain on the picked band: the2133+ /// A band added beside the picked one, at the frequency with the most room
2046- /// middle is flat and the top and bottom edges are the limit either way.2134+ /// around it ([`inserted_band`]), and picked so the next keystroke moves the
2047- /// Called on every pointer sample, so the curve bends under the hand; the2135+ /// band that was just made. Refused rather than silently ignored at the cap.
2048- /// write is the release's ([`commit_eq`](Player::commit_eq)).2136+ fn add_band(&mut self, cx: &mut Context<Self>) {
2049- fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {2137+ if self.eq_params.bands.len() >= EQ_BANDS_MAX {
2050- let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT;2138+ self.notice = Some(
2051- if self.set_band(self.eq_band, gain) {2139+ format!(
2140+ "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
2141+ )
2142+ .into(),
2143+ );
2052 cx.notify();2144 cx.notify();
2145+ return;
2053 }2146 }
2147+ let band = inserted_band(&self.eq_params.bands, self.eq_band);
2148+ self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len());
2149+ self.eq_params.bands.insert(self.eq_band, band);
2150+ self.commit_eq(cx);
2151+ }
2152+
2153+ /// Takes the picked band out. The last one stays: an equalizer of no bands
2154+ /// is a card with nothing to edit, and flattening is what "off" means here.
2155+ fn remove_band(&mut self, cx: &mut Context<Self>) {
2156+ if self.eq_params.bands.len() <= 1 {
2157+ self.notice = Some("LAST BAND — flatten it instead (r), or close the card".into());
2158+ cx.notify();
2159+ return;
2160+ }
2161+ self.eq_params.bands.remove(self.eq_band);
2162+ self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1);
2163+ self.commit_eq(cx);
2054 }2164 }
2055 2165
2056 /// Which band a press on the graph grabs: the nearest one along the2166 /// Which band a press on the graph grabs: the nearest one along the
@@ -2450,8 +2560,8 @@ impl Player {
2450 if self.exporting().is_some() {2560 if self.exporting().is_some() {
2451 return;2561 return;
2452 }2562 }
2453- let (Some(start), Some(was)) = (2563+ let (Some((start, _)), Some(was)) = (
2454- self.drop_frame(from, idx, to, x),2564+ self.drop_frame(from, idx, x),
2455 self.session2565 self.session
2456 .as_ref()2566 .as_ref()
2457 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),2567 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
@@ -2513,26 +2623,70 @@ impl Player {
2513 /// the scroll clamp pins the bed's right edge to the duration, and the2623 /// the scroll clamp pins the bed's right edge to the duration, and the
2514 /// pointer has no pixel past it. The upgrade is to let the scroll clamp2624 /// pointer has no pixel past it. The upgrade is to let the scroll clamp
2515 /// leave a screen of empty bed after the end, the way every NLE does.2625 /// leave a screen of empty bed after the end, the way every NLE does.
2516- fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> {2626+ fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
2517- let session = self.session.as_ref()?;2627+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
2518- let clip = session.lane_clips(from).get(idx).copied()?;
2519 let raw = self.frame_under(x).saturating_sub(self.grab);2628 let raw = self.frame_under(x).saturating_sub(self.grab);
2520- // The edges worth landing on: both ends of every clip already on the2629+ let marks = self.snap_targets(Some((from, idx)));
2521- // lane it is being let go over, the playhead, and the head of the2630+ Some(self.snap_to(raw, clip.frames(), &marks))
2522- // timeline. Never the group's own boxes -- a clip does not snap to2631+ }
2523- // where it already is.2632+
2524- let mut marks: Vec<u32> = session2633+ /// Which index the clip in the hand is at *now*: [`live_idx`] against the
2525- .lane_clips(to)2634+ /// lane the drag named, since a stroke during the gesture moves the indices
2526- .iter()2635+ /// gpui froze into the payload. Both halves of a drag ask it -- the line
2527- .enumerate()2636+ /// drawn in flight and the drop that commits -- so the promise and the
2528- .filter(|&(i, c)| {2637+ /// landing are made about one clip.
2529- (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link)2638+ fn dragged(&self, drag: &ClipDrag) -> Option<usize> {
2530- })2639+ let session = self.session.as_ref()?;
2531- .flat_map(|(_, c)| [c.start, c.end()])2640+ live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip)
2532- .collect();2641+ }
2533- marks.push(frame_at(session.now(), self.fps));2642+
2534- marks.push(0);2643+ /// The line while the clip is still in the hand: the very answer
2535- Some(snapped(raw, clip.frames(), self.snap_frames(), &marks))2644+ /// [`Player::drop_frame`] will commit, worked out on every move of the drag,
2645+ /// so what the eye was promised is where the release puts it. A pointer that
2646+ /// has wandered off the bed promises nothing.
2647+ fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) {
2648+ let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue);
2649+ self.set_cue(cue, x, cx);
2650+ }
2651+
2652+ /// The same line for a library row on its way to a lane: it goes down at
2653+ /// the frame it is let go on ([`Player::insert_source`]), so that frame is
2654+ /// what snaps and what is drawn. No length to snap by -- the file's own is
2655+ /// not known until the engine has placed it -- so only its head lands.
2656+ fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) {
2657+ let marks = self.snap_targets(None);
2658+ let cue = self.snap_to(self.frame_under(x), 0, &marks).1;
2659+ self.set_cue(cue, x, cx);
2660+ }
2661+
2662+ /// Sets the line, or takes it away, and repaints only when it moved: a
2663+ /// pointer dragged off the bed (up to the library, say) is not promising a
2664+ /// landing any more.
2665+ fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) {
2666+ let bed = self.ruler.get();
2667+ let cue = cue.filter(|_| x >= bed.left() && x <= bed.right());
2668+ if cue != self.snap_cue {
2669+ self.snap_cue = cue;
2670+ cx.notify();
2671+ }
2672+ }
2673+
2674+ /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its
2675+ /// lanes, so a clip meets a take one track over as readily as one beside it.
2676+ fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> {
2677+ let Some(session) = &self.session else {
2678+ return Vec::new();
2679+ };
2680+ let lanes = session.lanes();
2681+ let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect();
2682+ let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx)));
2683+ snap_marks(&clips, skip, frame_at(session.now(), self.fps))
2684+ }
2685+
2686+ /// Where a gesture at `raw` lands and the mark that pulled it there, with
2687+ /// the switch honoured: snapping off, nothing moves and no line is drawn.
2688+ fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) {
2689+ snap_cue(self.snap, raw, len, self.snap_frames(), marks)
2536 }2690 }
2537 2691
2538 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's2692 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
@@ -2596,14 +2750,25 @@ impl Player {
2596 /// against the same duration the boxes are drawn to, so the edge tracks the2750 /// against the same duration the boxes are drawn to, so the edge tracks the
2597 /// pointer exactly.2751 /// pointer exactly.
2598 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {2752 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2599- let at = self.frame_under(x);2753+ let Some(trim) = self.trim else {
2600- let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2601 return;2754 return;
2602 };2755 };
2603- let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {2756+ // The edge is pulled onto the same marks a whole clip is, by itself:
2757+ // there is no other end travelling with it, so it snaps at length zero.
2758+ let marks = self.snap_targets(Some((trim.lane, trim.idx)));
2759+ let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks);
2760+ let Some((lo, hi)) = self
2761+ .session
2762+ .as_ref()
2763+ .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge))
2764+ else {
2604 return;2765 return;
2605 };2766 };
2606- trim.to = at.clamp(lo, hi);2767+ let to = at.clamp(lo, hi);
2768+ // The line only stands where the edge actually stopped: a mark the
2769+ // engine's own room clamped away was never reached.
2770+ self.set_cue(cue.filter(|_| to == at), x, cx);
2771+ self.trim = Some(Trim { to, ..trim });
2607 cx.notify();2772 cx.notify();
2608 }2773 }
2609 2774
@@ -2645,39 +2810,13 @@ impl Player {
2645 }) else {2810 }) else {
2646 return clip;2811 return clip;
2647 };2812 };
2648- match trim.edge {2813+ let still = self.session.as_ref().is_some_and(|session| {
2649- // A still grows forward from source frame 0 instead, exactly as2814+ session
2650- // `Project::trim` writes it: with the in-point clamped at 0 the box2815+ .sources()
2651- // below would slide left rather than stretch, and the release would2816+ .get(clip.source)
2652- // then commit a wider clip than the drag drew.2817+ .is_some_and(|s| engine::is_image(&s.path))
2653- Edge::Start2818+ });
2654- if self.session.as_ref().is_some_and(|session| {2819+ trimmed_clip(clip, trim.edge, trim.to, still)
2655- session
2656- .sources()
2657- .get(clip.source)
2658- .is_some_and(|s| engine::is_image(&s.path))
2659- }) =>
2660- {
2661- Clip {
2662- in_frame: 0,
2663- out_frame: clip.end().saturating_sub(trim.to).max(1),
2664- start: trim.to,
2665- ..clip
2666- }
2667- }
2668- // The in-point follows the head, exactly as `Project::trim` moves
2669- // it: what stays on screen plays what it always played.
2670- Edge::Start => Clip {
2671- in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
2672- .clamp(0, i64::from(clip.out_frame - 1)) as u32,
2673- start: trim.to,
2674- ..clip
2675- },
2676- Edge::End => Clip {
2677- out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
2678- ..clip
2679- },
2680- }
2681 }2820 }
2682 2821
2683 /// How long the timeline is *drawn* as: its own length, and while a tail is2822 /// How long the timeline is *drawn* as: its own length, and while a tail is
@@ -2685,6 +2824,15 @@ impl Player {
2685 /// at the last frame has nowhere to put a pointer that means "longer", so2824 /// at the last frame has nowhere to put a pointer that means "longer", so
2686 /// without this the last clip on the timeline could be pulled in and never2825 /// without this the last clip on the timeline could be pulled in and never
2687 /// let back out.2826 /// let back out.
2827+ ///
2828+ /// Scroll room only, now that a second is an absolute number of pixels
2829+ /// ([`Scale`]): the extra length loosens [`View::settled`]'s clamp, which is
2830+ /// where the pixels past the last frame come from, and moves no box by a
2831+ /// pixel. It is still the *only* headroom at the tail -- zoomed in against
2832+ /// the end, that clamp pins the bed's right edge to the duration and an
2833+ /// End-trim of the last clip would have nowhere to be dragged to. What it
2834+ /// must not do is be read as a length anyone is told: the timecode reads
2835+ /// `PlaybackSession::timeline_duration` for exactly that reason.
2688 fn drawn_duration(&self) -> f64 {2836 fn drawn_duration(&self) -> f64 {
2689 let Some(session) = &self.session else {2837 let Some(session) = &self.session else {
2690 return 0.;2838 return 0.;
@@ -3715,31 +3863,55 @@ impl Render for Player {
3715 // cannot move at all, and every one of them is listed in the3863 // cannot move at all, and every one of them is listed in the
3716 // keys menu (keymap.rs `FIXED`) rather than being a secret.3864 // keys menu (keymap.rs `FIXED`) rather than being a secret.
3717 if this.eq_open.is_some() {3865 if this.eq_open.is_some() {
3866+ // Shift makes the two horizontal keys Q instead of
3867+ // frequency: both are the *width* of the same hump, so they
3868+ // sit on the same axis rather than on two keys nobody would
3869+ // guess. Wider is a lower Q, which is why left widens.
3870+ let shift = event.keystroke.modifiers.shift;
3718 if key == ESCAPE {3871 if key == ESCAPE {
3719 // Nothing to undo: every change is already at the clip,3872 // Nothing to undo: every change is already at the clip,
3720 // and undo is undo's own key.3873 // and undo is undo's own key.
3721 this.eq_open = None;3874 this.eq_open = None;
3722 this.eq_dragging = false;3875 this.eq_dragging = false;
3723 } else if key == "up" {3876 } else if key == "up" {
3724- this.nudge_band(EQ_STEP, cx);3877+ this.nudge_band(|b| b.gain_db += EQ_STEP, cx);
3725 } else if key == "down" {3878 } else if key == "down" {
3726- this.nudge_band(-EQ_STEP, cx);3879+ this.nudge_band(|b| b.gain_db -= EQ_STEP, cx);
3880+ } else if key == "left" && shift {
3881+ this.nudge_band(|b| b.q /= EQ_Q_STEP, cx);
3882+ } else if key == "right" && shift {
3883+ this.nudge_band(|b| b.q *= EQ_Q_STEP, cx);
3884+ } else if key == "left" {
3885+ this.nudge_band(|b| b.freq_hz /= EQ_FREQ_STEP, cx);
3886+ } else if key == "right" {
3887+ this.nudge_band(|b| b.freq_hz *= EQ_FREQ_STEP, cx);
3727 } else if key == "r" {3888 } else if key == "r" {
3728 for band in &mut this.eq_params.bands {3889 for band in &mut this.eq_params.bands {
3729 band.gain_db = 0.;3890 band.gain_db = 0.;
3730 }3891 }
3731 this.commit_eq(cx);3892 this.commit_eq(cx);
3893+ } else if key == "f" {
3894+ // This one band back to flat, which is the undo of one
3895+ // hand movement -- `r` is the undo of the whole card.
3896+ this.nudge_band(|b| b.gain_db = 0., cx);
3897+ } else if key == "a" {
3898+ this.add_band(cx);
3899+ } else if key == "x" {
3900+ this.remove_band(cx);
3732 } else if key == "s" {3901 } else if key == "s" {
3733 // The analyser off and on. Nothing is committed: it is3902 // The analyser off and on. Nothing is committed: it is
3734 // what the card *shows*, so it survives no further than3903 // what the card *shows*, so it survives no further than
3735 // this window.3904 // this window.
3736 this.eq_spectrum = !this.eq_spectrum;3905 this.eq_spectrum = !this.eq_spectrum;
3737 } else if let Ok(digit) = key.parse::<usize>() {3906 } else if let Ok(digit) = key.parse::<usize>() {
3738- // 1-based, as the rows are numbered on screen; a digit3907+ // As the keys are laid out: 1-9 then 0 for the tenth,
3739- // past the last band picks nothing rather than panics.3908+ // which is the cap ([`EQ_BANDS_MAX`]). A digit past the
3740- if let Some(band) = digit.checked_sub(1)3909+ // last band picks nothing rather than panics.
3741- && band < this.eq_params.bands.len()3910+ let band = match digit {
3742- {3911+ 0 => EQ_BANDS_MAX - 1,
3912+ n => n - 1,
3913+ };
3914+ if band < this.eq_params.bands.len() {
3743 this.eq_band = band;3915 this.eq_band = band;
3744 }3916 }
3745 }3917 }
@@ -3878,6 +4050,26 @@ impl Render for Player {
3878 }4050 }
3879 }4051 }
3880 }))4052 }))
4053+ // A drop event carries no path of its own -- gpui only tells the
4054+ // target that something landed -- so the line that promises where
4055+ // it will land is fed by the drag's own moves, which do carry the
4056+ // pointer (gpui div.rs:282). On the root, because a drag crosses
4057+ // the window: it starts on a clip or on a library row and ends over
4058+ // a lane, and only an ancestor of both hears all of it.
4059+ .on_drag_move(cx.listener(|this, event: &DragMoveEvent<ClipDrag>, _, cx| {
4060+ // The clip the payload named, wherever an edit mid-drag has
4061+ // since put it ([`Player::dragged`]): the line has to promise a
4062+ // landing for the take actually in the hand.
4063+ let drag = *event.drag(cx);
4064+ if let Some(idx) = this.dragged(&drag) {
4065+ this.preview_drop(drag.lane, idx, event.event.position.x, cx);
4066+ }
4067+ }))
4068+ .on_drag_move(
4069+ cx.listener(|this, event: &DragMoveEvent<AssetDrag>, _, cx| {
4070+ this.preview_place(event.event.position.x, cx);
4071+ }),
4072+ )
3881 // Scrubbing is tracked on the root because the pointer leaves the4073 // Scrubbing is tracked on the root because the pointer leaves the
3882 // 6 px ruler on the first drag and its own listeners then stop4074 // 6 px ruler on the first drag and its own listeners then stop
3883 // firing; the root's hitbox is the whole window.4075 // firing; the root's hitbox is the whole window.
@@ -3886,7 +4078,7 @@ impl Render for Player {
3886 // the equalizer drag is tracked here for the ruler's reason.4078 // the equalizer drag is tracked here for the ruler's reason.
3887 if this.eq_dragging {4079 if this.eq_dragging {
3888 if event.pressed_button == Some(MouseButton::Left) {4080 if event.pressed_button == Some(MouseButton::Left) {
3889- this.drag_band(event.position.y, cx);4081+ this.drag_band(event.position, cx);
3890 } else {4082 } else {
3891 // Released outside the window: the up below never came,4083 // Released outside the window: the up below never came,
3892 // so this is where the gesture ends -- and it still owes4084 // so this is where the gesture ends -- and it still owes
@@ -3956,7 +4148,7 @@ impl Render for Player {
3956 if std::mem::take(&mut this.eq_dragging) {4148 if std::mem::take(&mut this.eq_dragging) {
3957 // The release lands exactly, then the gesture is written4149 // The release lands exactly, then the gesture is written
3958 // once -- the append-only table's whole reason.4150 // once -- the append-only table's whole reason.
3959- this.drag_band(event.position.y, cx);4151+ this.drag_band(event.position, cx);
3960 this.commit_eq(cx);4152 this.commit_eq(cx);
3961 return;4153 return;
3962 }4154 }
@@ -4058,7 +4250,7 @@ impl Render for Player {
4058 // column, and only one of the two is ever up.4250 // column, and only one of the two is ever up.
4059 .children(self.keys_overlay(cx))4251 .children(self.keys_overlay(cx))
4060 .children(self.export_card(window.viewport_size(), cx))4252 .children(self.export_card(window.viewport_size(), cx))
4061- .children(self.eq_card(cx))4253+ .children(self.eq_card(window.viewport_size(), cx))
4062 .children(self.color_card(cx))4254 .children(self.color_card(cx))
4063 .children(self.speed_card(cx))4255 .children(self.speed_card(cx))
4064 .children(self.silence_card(cx))4256 .children(self.silence_card(cx))
@@ -4643,6 +4835,25 @@ impl Player {
4643 live,4835 live,
4644 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),4836 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
4645 ))4837 ))
4838+ // The magnet, beside the zoom for the zoom's own reason: it
4839+ // changes nothing on the timeline, it changes how the hand
4840+ // meets it. The label is the state, as the volume's is --
4841+ // a toggle that looks the same either way says nothing.
4842+ .child(control(
4843+ "snap",
4844+ None,
4845+ if self.snap { "Snap" } else { "No snap" },
4846+ format!(
4847+ "{} — {}",
4848+ key(ActionId::ToggleSnap),
4849+ match self.snap {
4850+ true => "drags and trims land on clip edges, the playhead and the start",
4851+ false => "drags and trims land exactly where the hand leaves them",
4852+ }
4853+ ),
4854+ live,
4855+ cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)),
4856+ ))
4646 // Import is not here: it belongs to the media list it adds4857 // Import is not here: it belongs to the media list it adds
4647 // to, and two doors into one action is a question about4858 // to, and two doors into one action is a question about
4648 // which one is the real one.4859 // which one is the real one.
@@ -4715,10 +4926,20 @@ impl Player {
4715 .gap(px(12.))4926 .gap(px(12.))
4716 // Fixed width and one line: changing digits must not push4927 // Fixed width and one line: changing digits must not push
4717 // the row around, nor wrap and change its height.4928 // the row around, nor wrap and change its height.
4929+ // The timeline's own length, never the drawn one: a tail
4930+ // being dragged inflates the bed to the room that edge has
4931+ // ([`Player::drawn_duration`]), and for a still that room is
4932+ // ten minutes -- a total that jumped to 10:00:00 the moment
4933+ // a picture's edge was pressed, and back on release.
4718 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(4934 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
4719 "{} / {}",4935 "{} / {}",
4720 timecode(position, self.fps),4936 timecode(position, self.fps),
4721- timecode(duration, self.fps)4937+ timecode(
4938+ self.session
4939+ .as_ref()
4940+ .map_or(0., PlaybackSession::timeline_duration),
4941+ self.fps
4942+ )
4722 )))4943 )))
4723 .child(4944 .child(
4724 div()4945 div()
@@ -5498,20 +5719,28 @@ impl Player {
5498 }5719 }
5499 5720
5500 /// The equalizer of one audio clip: its frequency response drawn as a5721 /// The equalizer of one audio clip: its frequency response drawn as a
5501- /// curve, a handle per band sitting on it, and a row that flattens them5722+ /// curve, a handle per band sitting on it, each band's own bell under the
5502- /// all. The curve is the clip's actual filter (`EqParams::response_db`5723+ /// sum, and a row that reads and moves the picked band's three numbers. The
5503- /// reads the coefficients the samples go through), and it is redrawn on5724+ /// curve is the clip's actual filter (`EqParams::response_db` reads the
5504- /// every pointer sample of a drag, so the shape bends under the hand.5725+ /// coefficients the samples go through), and it is redrawn on every pointer
5726+ /// sample of a drag, so the shape bends under the hand.
5505 ///5727 ///
5506- /// The same scrim and width as the other two cards, and the same plain divs5728+ /// Wider than the other cards and wider still on a bigger window
5507- /// -- nothing here takes focus, so the root keeps the keyboard and the5729+ /// ([`eq_card_w`]): every pixel across is frequency resolution, which none
5508- /// card's own strokes (`1`–`5`, up, down, `r`) reach it.5730+ /// of the row-shaped cards have any use for. The same scrim and the same
5731+ /// plain divs -- nothing here takes focus, so the root keeps the keyboard
5732+ /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`,
5733+ /// `s`) reach it.
5509 ///5734 ///
5510 /// Every change is written at the clip as it is made5735 /// Every change is written at the clip as it is made
5511 /// ([`Player::commit_eq`]), so what the card shows is always what is5736 /// ([`Player::commit_eq`]), so what the card shows is always what is
5512 /// playing: there is no OK button to forget, and closing it changes5737 /// playing: there is no OK button to forget, and closing it changes
5513 /// nothing. What takes a curve back off is undo, like every other edit.5738 /// nothing. What takes a curve back off is undo, like every other edit.
5514- fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {5739+ fn eq_card(
5740+ &self,
5741+ viewport: Size<Pixels>,
5742+ cx: &mut Context<Self>,
5743+ ) -> Option<impl IntoElement> {
5515 let (lane, idx) = self.eq_open?;5744 let (lane, idx) = self.eq_open?;
5516 // The rate the engine filters this timeline at, so the drawn curve is5745 // The rate the engine filters this timeline at, so the drawn curve is
5517 // the one those coefficients make -- near the top of the axis a 44.1 kHz5746 // the one those coefficients make -- near the top of the axis a 44.1 kHz
@@ -5565,13 +5794,20 @@ impl Player {
5565 .bg(rgb(HOVER_DIM))5794 .bg(rgb(HOVER_DIM))
5566 .cursor_pointer()5795 .cursor_pointer()
5567 // The press picks the band under it *and* is already the first5796 // The press picks the band under it *and* is already the first
5568- // sample of the drag, so a plain click sets a value.5797+ // sample of the drag, so a plain click sets a value. A second click
5798+ // takes that band back to flat instead: the gesture that undoes one
5799+ // handle, with no modifier to remember.
5569 .on_mouse_down(5800 .on_mouse_down(
5570 MouseButton::Left,5801 MouseButton::Left,
5571 cx.listener(|this, event: &MouseDownEvent, _, cx| {5802 cx.listener(|this, event: &MouseDownEvent, _, cx| {
5572 this.eq_band = this.nearest_band(event.position.x);5803 this.eq_band = this.nearest_band(event.position.x);
5804+ if event.click_count >= 2 {
5805+ this.eq_dragging = false;
5806+ this.nudge_band(|b| b.gain_db = 0., cx);
5807+ return;
5808+ }
5573 this.eq_dragging = true;5809 this.eq_dragging = true;
5574- this.drag_band(event.position.y, cx);5810+ this.drag_band(event.position, cx);
5575 }),5811 }),
5576 )5812 )
5577 .child(bounds_probe(self.eq_graph.clone()))5813 .child(bounds_probe(self.eq_graph.clone()))
@@ -5663,7 +5899,7 @@ impl Player {
5663 })5899 })
5664 .child(5900 .child(
5665 div()5901 div()
5666- .w(px(KEYS_W))5902+ .w(px(eq_card_w(f32::from(viewport.width))))
5667 .flex()5903 .flex()
5668 .flex_col()5904 .flex_col()
5669 .gap(px(2.))5905 .gap(px(2.))
@@ -5684,28 +5920,15 @@ impl Player {
5684 .text_size(px(11.))5920 .text_size(px(11.))
5685 .text_color(rgb(INK_DIM))5921 .text_color(rgb(INK_DIM))
5686 .child(self.notice.clone().unwrap_or_else(|| {5922 .child(self.notice.clone().unwrap_or_else(|| {
5687- "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into()5923+ "drag a handle, or a digit picks a band — ←→ moves it, ↑↓ its gain, shift+←→ its width; a adds, x removes, f flattens it, r all, s spectrum, esc closes".into()
5688 })),5924 })),
5689 )5925 )
5690 .child(graph)5926 .child(graph)
5691- // Which band the keyboard is holding and what it is set5927+ // Which band the keyboard is holding and every number it
5692- // to: the curve shows the sum, and a band pushed against5928+ // is set to, each with the pair of buttons that moves it:
5693- // one pulling the other way is not readable off it.5929+ // the curve shows the sum, and a band pushed against one
5694- .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(5930+ // pulling the other way is not readable off it.
5695- match picked {5931+ .child(self.eq_numbers(picked, cx))
5696- // Q as well as the two the curve shows: it is
5697- // how wide the hump under the handle is, and
5698- // nothing else on the card says so.
5699- Some(band) => format!(
5700- "{} {} {:+.1} dB — Q {:.2}",
5701- self.eq_band + 1,
5702- band_label(band),
5703- band.gain_db,
5704- band.q
5705- ),
5706- None => "no bands".into(),
5707- },
5708- ))
5709 .child(5932 .child(
5710 div()5933 div()
5711 .mt(px(4.))5934 .mt(px(4.))
@@ -5729,7 +5952,45 @@ impl Player {
5729 }5952 }
5730 this.commit_eq(cx);5953 this.commit_eq(cx);
5731 }))5954 }))
5732- .child("Flatten"),5955+ .child("Flatten all"),
5956+ )
5957+ // The two that change how many bands there are.
5958+ // The engine takes any cascade -- the count was
5959+ // only ever fixed because this card had no way
5960+ // to say otherwise.
5961+ .child(
5962+ div()
5963+ .id("eq-add")
5964+ .flex()
5965+ .flex_1()
5966+ .h(px(CONTROL_H))
5967+ .items_center()
5968+ .justify_center()
5969+ .rounded(px(3.))
5970+ .bg(rgb(CHROME))
5971+ .cursor_pointer()
5972+ .hover(|s| s.bg(rgb(HOVER)))
5973+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
5974+ this.add_band(cx)
5975+ }))
5976+ .child("Add band"),
5977+ )
5978+ .child(
5979+ div()
5980+ .id("eq-remove")
5981+ .flex()
5982+ .flex_1()
5983+ .h(px(CONTROL_H))
5984+ .items_center()
5985+ .justify_center()
5986+ .rounded(px(3.))
5987+ .bg(rgb(CHROME))
5988+ .cursor_pointer()
5989+ .hover(|s| s.bg(rgb(HOVER)))
5990+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
5991+ this.remove_band(cx)
5992+ }))
5993+ .child("Remove band"),
5733 )5994 )
5734 // The analyser's switch, next to the one other5995 // The analyser's switch, next to the one other
5735 // button the card has: `s` does the same, and a5996 // button the card has: `s` does the same, and a
@@ -5764,6 +6025,103 @@ impl Player {
5764 )6025 )
5765 }6026 }
5766 6027
6028+ /// The picked band's three numbers -- where it sits, how far it pushes and
6029+ /// how wide it is -- each beside the pair of buttons that moves it. The
6030+ /// arrows do the same three things, but a value only a key can change is a
6031+ /// value a hand on the pointer cannot reach at all, which is the same reason
6032+ /// [`Player::mbps_steppers`] exists.
6033+ fn eq_numbers(&self, picked: Option<&Band>, cx: &mut Context<Self>) -> impl IntoElement {
6034+ let row = div()
6035+ .flex_none()
6036+ .flex()
6037+ .items_center()
6038+ .gap(px(10.))
6039+ .px(px(6.))
6040+ .text_size(px(11.));
6041+ let Some(band) = picked.copied() else {
6042+ return row.child("no bands — a adds one");
6043+ };
6044+ let step = |id: &'static str,
6045+ label: &'static str,
6046+ change: fn(&mut Band),
6047+ cx: &mut Context<Self>| {
6048+ div()
6049+ .id(id)
6050+ .flex()
6051+ .w(px(HIT_MIN))
6052+ .h(px(HIT_MIN))
6053+ .items_center()
6054+ .justify_center()
6055+ .rounded(px(3.))
6056+ .bg(rgb(CHROME))
6057+ .cursor_pointer()
6058+ .hover(|s| s.bg(rgb(HOVER)))
6059+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
6060+ this.nudge_band(change, cx)
6061+ }))
6062+ .child(label)
6063+ };
6064+ let number = |value: String,
6065+ ids: (&'static str, &'static str),
6066+ by: (fn(&mut Band), fn(&mut Band)),
6067+ cx: &mut Context<Self>| {
6068+ div()
6069+ .flex()
6070+ .items_center()
6071+ .gap(px(4.))
6072+ .child(div().child(value))
6073+ .child(step(ids.0, "−", by.0, cx))
6074+ .child(step(ids.1, "+", by.1, cx))
6075+ };
6076+ row.child(format!(
6077+ "Band {} of {}",
6078+ self.eq_band + 1,
6079+ self.eq_params.bands.len()
6080+ ))
6081+ .child(number(
6082+ band_label(&band),
6083+ ("eq-freq-down", "eq-freq-up"),
6084+ (
6085+ |b| b.freq_hz /= EQ_FREQ_STEP,
6086+ |b| b.freq_hz *= EQ_FREQ_STEP,
6087+ ),
6088+ cx,
6089+ ))
6090+ .child(number(
6091+ format!("{:+.1} dB", band.gain_db),
6092+ ("eq-gain-down", "eq-gain-up"),
6093+ (|b| b.gain_db -= EQ_STEP, |b| b.gain_db += EQ_STEP),
6094+ cx,
6095+ ))
6096+ // Q is width, so its buttons are labelled by what they *do* to the
6097+ // hump rather than by which way the number goes: a wider band is a
6098+ // smaller Q, and nobody should have to know that to use the card.
6099+ .child(number(
6100+ format!("Q {:.2}", band.q),
6101+ ("eq-q-wider", "eq-q-narrower"),
6102+ (|b| b.q /= EQ_Q_STEP, |b| b.q *= EQ_Q_STEP),
6103+ cx,
6104+ ))
6105+ .child(
6106+ div()
6107+ .id("eq-flat-band")
6108+ .flex()
6109+ .h(px(HIT_MIN))
6110+ .px(px(8.))
6111+ .items_center()
6112+ .rounded(px(3.))
6113+ .bg(rgb(CHROME))
6114+ .cursor_pointer()
6115+ .hover(|s| s.bg(rgb(HOVER)))
6116+ .on_click(
6117+ cx.listener(|this, _: &ClickEvent, _, cx| {
6118+ this.nudge_band(|b| b.gain_db = 0., cx)
6119+ }),
6120+ )
6121+ .child("Flatten this"),
6122+ )
6123+ }
6124+
5767 /// The colour card: the graded frame's histogram over a row per control,6125 /// The colour card: the graded frame's histogram over a row per control,
5768 /// each row a bar the pointer drags straight to a value -- no stepper6126 /// each row a bar the pointer drags straight to a value -- no stepper
5769 /// buttons, because a slider is a thing to pull, and the arrow keys still6127 /// buttons, because a slider is a thing to pull, and the arrow keys still
@@ -6823,6 +7181,19 @@ impl Player {
6823 // it, so all of them move together when it does. No bed width is needed7181 // it, so all of them move together when it does. No bed width is needed
6824 // to place them any more -- a second is so many pixels wherever it is.7182 // to place them any more -- a second is so many pixels wherever it is.
6825 let scale = self.scale;7183 let scale = self.scale;
7184+ // How much bed there is to be seen on, measured off the ruler's own
7185+ // probe like every other question about it: what a box draws *inside*
7186+ // itself is clipped to this ([`visible_slice`]), because a box at a deep
7187+ // zoom is far wider than the strip it is being watched through.
7188+ let bed = f32::from(self.ruler.get().size.width);
7189+ // Where the snap line stands, in the same pixels every box is placed
7190+ // through -- and only while a gesture is actually live: gpui drops a
7191+ // drag without telling anyone, so this asks whether one is in flight
7192+ // (`App::has_active_drag`) rather than remembering that one was.
7193+ let cue = self
7194+ .snap_cue
7195+ .filter(|_| self.trim.is_some() || cx.has_active_drag())
7196+ .map(|frame| scale.px_at(f64::from(frame) / self.fps));
6826 let clips = self7197 let clips = self
6827 .session7198 .session
6828 .as_ref()7199 .as_ref()
@@ -6969,7 +7340,12 @@ impl Player {
6969 // the window, which took it from the release that fired7340 // the window, which took it from the release that fired
6970 // this (gpui window.rs:3602).7341 // this (gpui window.rs:3602).
6971 .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| {7342 .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| {
6972- let at = this.frame_under(window.mouse_position().x);7343+ // Onto the edges near it, exactly as a clip carried by
7344+ // hand lands: the line drawn while it was in flight is
7345+ // the frame it goes down on.
7346+ let x = window.mouse_position().x;
7347+ let marks = this.snap_targets(None);
7348+ let (at, _) = this.snap_to(this.frame_under(x), 0, &marks);
6973 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)7349 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)
6974 }))7350 }))
6975 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))7351 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
@@ -6978,10 +7354,21 @@ impl Player {
6978 // to -- its own included, which is the drag that moves a7354 // to -- its own included, which is the drag that moves a
6979 // take along its track.7355 // take along its track.
6980 .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| {7356 .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| {
6981- this.move_clip(drag.lane, drag.idx, lane, window.mouse_position().x, cx)7357+ // Against the lane as it is *now* ([`Player::dragged`]),
7358+ // and then snapped by `move_clip` like any other drop:
7359+ // which clip is being moved and where it lands are two
7360+ // questions, and this is the first one.
7361+ let Some(idx) = this.dragged(drag) else {
7362+ return;
7363+ };
7364+ this.move_clip(drag.lane, idx, lane, window.mouse_position().x, cx)
6982 }))7365 }))
6983 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))7366 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
6984 .children(clips.iter().enumerate().map(|(i, clip)| {7367 .children(clips.iter().enumerate().map(|(i, clip)| {
7368+ // The clip as the lane holds it, for the drag payload:
7369+ // what a drop looks itself up by has to be the placed
7370+ // clip, never the preview an edge drag is drawing.
7371+ let placed = *clip;
6985 // What a drag on an edge is showing, which is the clip7372 // What a drag on an edge is showing, which is the clip
6986 // itself while nothing is being dragged.7373 // itself while nothing is being dragged.
6987 let clip = &self.trimmed(lane, i, *clip);7374 let clip = &self.trimmed(lane, i, *clip);
@@ -7007,15 +7394,30 @@ impl Player {
7007 .unwrap_or(clip.source),7394 .unwrap_or(clip.source),
7008 );7395 );
7009 let width = scale.width_px(len);7396 let width = scale.width_px(len);
7397+ let left = scale.px_at(start);
7398+ // The slice of this box that is on the bed: where its
7399+ // name, its badge and its waveform go, so none of the
7400+ // three is drawn out at a zoomed-in box's own edges.
7401+ let (vis_x, vis_w) = visible_slice(left, width, bed);
7010 let label = sources.get(clip.source).map(|s| file_name(&s.path));7402 let label = sources.get(clip.source).map(|s| file_name(&s.path));
7011 let wave = sources7403 let wave = sources
7012 .get(clip.source)7404 .get(clip.source)
7013 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))7405 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
7014 .cloned();7406 .cloned();
7015- let (from, to) = (7407+ // The source seconds that slice plays -- not the clip's
7016- f64::from(clip.in_frame) / self.fps,7408+ // whole range: the envelope is drawn for the part of the
7017- f64::from(clip.out_frame) / self.fps,7409+ // box that can be seen, at the resolution of the pixels
7018- );7410+ // it actually has, and never one column per two pixels
7411+ // of a box millions of pixels wide.
7412+ let along = |x: f32| match width > 0. {
7413+ true => {
7414+ f64::from(clip.in_frame)
7415+ + f64::from(clip.out_frame - clip.in_frame)
7416+ * f64::from(x / width)
7417+ }
7418+ false => f64::from(clip.in_frame),
7419+ };
7420+ let (from, to) = (along(vis_x) / self.fps, along(vis_x + vis_w) / self.fps);
7019 let tip = tip.clone();7421 let tip = tip.clone();
7020 // What the pointer carries on the way to another lane:7422 // What the pointer carries on the way to another lane:
7021 // the file the box is showing, the same ghost a library7423 // the file the box is showing, the same ghost a library
@@ -7038,7 +7440,7 @@ impl Player {
7038 // off the left edge: the bed clips what hangs out7440 // off the left edge: the bed clips what hangs out
7039 // of it, so a half-visible clip is drawn as the7441 // of it, so a half-visible clip is drawn as the
7040 // half of itself that is on screen.7442 // half of itself that is on screen.
7041- .left(px(scale.px_at(start)))7443+ .left(px(left))
7042 .w(px(width))7444 .w(px(width))
7043 .overflow_hidden()7445 .overflow_hidden()
7044 .rounded(px(3.))7446 .rounded(px(3.))
@@ -7059,9 +7461,14 @@ impl Player {
7059 // starts the drag still selects, so picking a clip7461 // starts the drag still selects, so picking a clip
7060 // up and putting it back down where it was is7462 // up and putting it back down where it was is
7061 // exactly a click.7463 // exactly a click.
7062- .on_drag(ClipDrag { lane, idx: i }, move |_, _, _, cx| {7464+ .on_drag(
7063- cx.new(|_| Tip(ghost.clone()))7465+ ClipDrag {
7064- })7466+ lane,
7467+ idx: i,
7468+ clip: placed,
7469+ },
7470+ move |_, _, _, cx| cx.new(|_| Tip(ghost.clone())),
7471+ )
7065 .on_mouse_down(7472 .on_mouse_down(
7066 MouseButton::Left,7473 MouseButton::Left,
7067 cx.listener(move |this, event: &MouseDownEvent, _, cx| {7474 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
@@ -7120,7 +7527,7 @@ impl Player {
7120 zone7527 zone
7121 }))7528 }))
7122 // Under the label row, never through it.7529 // Under the label row, never through it.
7123- .children(wave.filter(|_| audio).and_then(|wave| {7530+ .children(wave.filter(|_| audio && vis_w > 0.).and_then(|wave| {
7124 let inner: AnyElement = match wave {7531 let inner: AnyElement = match wave {
7125 Wave::Peaks(peaks) => {7532 Wave::Peaks(peaks) => {
7126 waveform(peaks, from, to).into_any_element()7533 waveform(peaks, from, to).into_any_element()
@@ -7156,8 +7563,8 @@ impl Player {
7156 Some(7563 Some(
7157 div()7564 div()
7158 .absolute()7565 .absolute()
7159- .left_0()7566+ .left(px(vis_x))
7160- .right_0()7567+ .w(px(vis_w))
7161 .top(px(LABEL_H))7568 .top(px(LABEL_H))
7162 .bottom_0()7569 .bottom_0()
7163 .child(inner),7570 .child(inner),
@@ -7168,24 +7575,44 @@ impl Player {
7168 // cannot say whether a short clip is a trim or a7575 // cannot say whether a short clip is a trim or a
7169 // clip at 4x, and that is the difference between a7576 // clip at 4x, and that is the difference between a
7170 // cut and a re-time.7577 // cut and a re-time.
7171- .when(!clip.speed.is_normal(), |d| {7578+ // Against the right edge of what is *visible* of the
7579+ // box, not of the box: zoomed in, the box's own
7580+ // right edge is off the screen and the badge with
7581+ // it, which is a clip that stops saying it is
7582+ // speeded exactly when it is being looked at
7583+ // closely.
7584+ .when(!clip.speed.is_normal() && vis_w > 0., |d| {
7172 d.child(7585 d.child(
7173 div()7586 div()
7174 .absolute()7587 .absolute()
7175 .top_0()7588 .top_0()
7176- .right_0()7589+ .left(px(vis_x))
7177- .px(px(3.))7590+ .w(px(vis_w))
7178- .rounded(px(3.))7591+ .flex()
7179- .bg(rgb(ACCENT))7592+ .justify_end()
7180- .text_size(px(9.))7593+ .overflow_hidden()
7181- .text_color(rgb(SURFACE))7594+ .child(
7182- .child(format!("{}", clip.speed)),7595+ div()
7596+ .flex_none()
7597+ .px(px(3.))
7598+ .rounded(px(3.))
7599+ .bg(rgb(ACCENT))
7600+ .text_size(px(9.))
7601+ .text_color(rgb(SURFACE))
7602+ .child(format!("{}", clip.speed)),
7603+ ),
7183 )7604 )
7184 })7605 })
7185- .when_some(label.filter(|_| show_label(width)), |d, label| {7606+ // ...and the name sits at the left edge of the same
7607+ // slice, for the same reason: a box scrolled half
7608+ // off names itself on the half that is on screen.
7609+ .when_some(label.filter(|_| show_label(vis_w)), |d, label| {
7186 d.child(7610 d.child(
7187 div()7611 div()
7188- .relative()7612+ .absolute()
7613+ .top_0()
7614+ .left(px(vis_x))
7615+ .w(px(vis_w))
7189 .h(px(LABEL_H))7616 .h(px(LABEL_H))
7190 .px(px(4.))7617 .px(px(4.))
7191 .truncate()7618 .truncate()
@@ -7213,6 +7640,20 @@ impl Player {
7213 .bg(rgba(0x4a9effaa))7640 .bg(rgba(0x4a9effaa))
7214 }),7641 }),
7215 )7642 )
7643+ // What the gesture in flight is about to land on, drawn on
7644+ // every lane so a clip lining up with a take one track over
7645+ // can be seen to line up with it. Under the playhead's line
7646+ // and in another colour, since the two mean different
7647+ // things and often stand on the same pixel.
7648+ .children(cue.map(|x| {
7649+ div()
7650+ .absolute()
7651+ .top_0()
7652+ .h_full()
7653+ .left(px(x))
7654+ .w(px(1.))
7655+ .bg(rgb(INK))
7656+ }))
7216 // Last, so it is over the clips: the same fraction in both7657 // Last, so it is over the clips: the same fraction in both
7217 // lanes, which is the playhead being one line.7658 // lanes, which is the playhead being one line.
7218 .child(7659 .child(
@@ -7437,6 +7878,36 @@ fn eq_x(freq_hz: f32) -> f32 {
7437 ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)7878 ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
7438 }7879 }
7439 7880
7881+/// The frequency at a fraction across the graph -- [`eq_x`] backwards, which is
7882+/// how a drag and the curve's own sample points read one. Clamped to the axis
7883+/// either way, so a pointer that leaves the box stops at 20 Hz or 20 kHz.
7884+fn eq_freq(along: f32) -> f32 {
7885+ EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along.clamp(0., 1.))
7886+}
7887+
7888+/// The band an "add" makes: a flat peak half way -- in octaves, which is what
7889+/// the log axis draws -- between the picked band and whatever sits above it, so
7890+/// a new band lands in the gap on screen rather than on top of its neighbour.
7891+/// Above the topmost band the gap is the rest of the axis.
7892+fn inserted_band(bands: &[Band], after: usize) -> Band {
7893+ let below = bands.get(after).map_or(1000., |b| b.freq_hz);
7894+ let above = bands
7895+ .iter()
7896+ .map(|b| b.freq_hz)
7897+ .filter(|f| *f > below)
7898+ .min_by(f32::total_cmp)
7899+ .unwrap_or(EQ_FREQ_HIGH);
7900+ Band {
7901+ freq_hz: (below * above).sqrt().clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH),
7902+ gain_db: 0.,
7903+ // A shade narrower than the flat-shelf 0.707 the defaults use: a band
7904+ // someone asked for is a band they mean to aim, and a wide one aimed at
7905+ // 300 Hz is really a band at everything.
7906+ q: 1.,
7907+ kind: BandKind::Peak,
7908+ }
7909+}
7910+
7440 /// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,7911 /// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
7441 /// so a cut reads as a dip below the line it is a cut from. The inverse of7912 /// so a cut reads as a dip below the line it is a cut from. The inverse of
7442 /// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a7913 /// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a
@@ -7446,14 +7917,24 @@ fn eq_y(gain_db: f32) -> f32 {
7446 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.7917 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
7447 }7918 }
7448 7919
7920+/// A frequency as the card writes it. Two decimals of a kHz at most, with the
7921+/// zeroes trimmed, so "1 kHz" stays "1 kHz" and a band nudged off it reads as
7922+/// 1.12 kHz rather than as the same "1 kHz" it was before the keystroke -- a
7923+/// number that does not move under an edit is worse than no number.
7924+fn eq_freq_label(freq_hz: f32) -> String {
7925+ if freq_hz < 1000. {
7926+ return format!("{freq_hz:.0} Hz");
7927+ }
7928+ let khz = format!("{:.2}", freq_hz / 1000.);
7929+ let khz = khz.trim_end_matches('0').trim_end_matches('.');
7930+ format!("{khz} kHz")
7931+}
7932+
7449 /// What a band row calls itself: the corner or centre frequency, and for a7933 /// What a band row calls itself: the corner or centre frequency, and for a
7450 /// shelf the fact that it tilts everything past it -- which is the difference7934 /// shelf the fact that it tilts everything past it -- which is the difference
7451 /// between "12 kHz" moving the last octave and moving one band inside it.7935 /// between "12 kHz" moving the last octave and moving one band inside it.
7452 fn band_label(band: &Band) -> String {7936 fn band_label(band: &Band) -> String {
7453- let freq = match band.freq_hz >= 1000. {7937+ let freq = eq_freq_label(band.freq_hz);
7454- true => format!("{:.0} kHz", band.freq_hz / 1000.),
7455- false => format!("{:.0} Hz", band.freq_hz),
7456- };
7457 match band.kind {7938 match band.kind {
7458 BandKind::LowShelf => format!("{freq} low shelf"),7939 BandKind::LowShelf => format!("{freq} low shelf"),
7459 BandKind::HighShelf => format!("{freq} high shelf"),7940 BandKind::HighShelf => format!("{freq} high shelf"),
@@ -7826,6 +8307,15 @@ fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<Str
7826 })8307 })
7827 }8308 }
7828 8309
8310+/// How wide the equalizer card is drawn in a window this wide: all of it bar a
8311+/// margin, up to [`EQ_W_MAX`]. The card is a graph, and a graph of twenty
8312+/// thousand hertz on 320 px spends four pixels on the octave below middle C --
8313+/// so it takes the room a big window has and stays inside a small one. Floored
8314+/// at the other cards' width, which is the last size the rows still read at.
8315+fn eq_card_w(window_w: f32) -> f32 {
8316+ (window_w - EQ_W_MARGIN).clamp(KEYS_W, EQ_W_MAX)
8317+}
8318+
7829 /// What the media list is given of the window. A share of it, so a narrow8319 /// What the media list is given of the window. A share of it, so a narrow
7830 /// window gives the panel less rather than giving the picture nothing, floored8320 /// window gives the panel less rather than giving the picture nothing, floored
7831 /// where a name stops being readable and capped at a third of the window --8321 /// where a name stops being readable and capped at a third of the window --
@@ -8693,6 +9183,97 @@ fn show_label(w: f32) -> bool {
8693 w >= LABEL_MIN_W9183 w >= LABEL_MIN_W
8694 }9184 }
8695 9185
9186+/// The clip a trim is *showing*, worked out the way `Project::trim` will write
9187+/// it: the timeline room the edge leaves is turned into source frames by the one
9188+/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from
9189+/// that. The preview and the commit are then the same arithmetic -- a box let go
9190+/// of stays where the hand left it at every rate. Assigning the timeline count
9191+/// straight to the source field, as this used to, drew a speeded clip's tail
9192+/// moving at the wrong rate (it snapped on release) and drew a *head* trim
9193+/// moving the clip's other edge, since the length it implied was not the length
9194+/// the release would commit.
9195+///
9196+/// A still grows forward from source frame 0 instead: every frame of it is the
9197+/// same picture, so there is no earlier one for an in-point to walk back to.
9198+///
9199+/// Room too narrow to hold one source frame is the edit the engine refuses, and
9200+/// the box is drawn unchanged rather than as something that will not be
9201+/// committed.
9202+fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip {
9203+ // An edge that has not moved is not an edit, and `Project::trim` refuses it
9204+ // as one: the press that starts a drag must draw the clip it pressed, not a
9205+ // clip a rounding narrower.
9206+ if to
9207+ == match edge {
9208+ Edge::Start => clip.start,
9209+ Edge::End => clip.end(),
9210+ }
9211+ {
9212+ return clip;
9213+ }
9214+ match edge {
9215+ Edge::Start => {
9216+ // What survives is measured from the *end* -- the frames that stay
9217+ // play what they always played, which is what makes this a trim.
9218+ let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else {
9219+ return clip;
9220+ };
9221+ match still {
9222+ true => Clip {
9223+ in_frame: 0,
9224+ out_frame: keep,
9225+ start: to,
9226+ ..clip
9227+ },
9228+ false => Clip {
9229+ in_frame: clip.out_frame - keep.min(clip.out_frame),
9230+ start: to,
9231+ ..clip
9232+ },
9233+ }
9234+ }
9235+ Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) {
9236+ Some(keep) => Clip {
9237+ out_frame: clip.in_frame + keep,
9238+ ..clip
9239+ },
9240+ None => clip,
9241+ },
9242+ }
9243+}
9244+
9245+/// Which index on its own lane a dragged clip is at *now*: the one it was picked
9246+/// up at while nothing has moved, and wherever the clip itself has slid to when
9247+/// an edit during the drag rippled the lane's indices -- a delete, an undo or a
9248+/// paste from a stroke, none of which gpui's frozen drag payload hears about.
9249+/// `None` when the clip is gone altogether, and then the drop is not an edit at
9250+/// all: moving whatever slid into its place is the one thing the hand did not
9251+/// ask for. A lane's clips are disjoint and sorted, so at most one of them can
9252+/// be the clip that was picked up.
9253+fn live_idx(clips: &[Clip], idx: usize, clip: Clip) -> Option<usize> {
9254+ match clips.get(idx) {
9255+ Some(&at) if at == clip => Some(idx),
9256+ _ => clips.iter().position(|&c| c == clip),
9257+ }
9258+}
9259+
9260+/// The part of a clip's box that is on the bed, in the box's own pixels:
9261+/// `(left, width)` of its intersection with the visible strip. Everything drawn
9262+/// *inside* a box -- its waveform, its name, its speed badge -- is placed in
9263+/// here rather than at the box's own edges, which at a deep zoom sit thousands
9264+/// of pixels off either side of the screen: a label out there is a label nobody
9265+/// can read, and a waveform out there is a path with a point per two pixels of a
9266+/// width nobody can see. A bed that has not been measured yet answers with the
9267+/// whole box, which is what was drawn before there was a bed to clip to.
9268+fn visible_slice(left: f32, width: f32, bed: f32) -> (f32, f32) {
9269+ if bed <= 0. {
9270+ return (0., width);
9271+ }
9272+ let from = (-left).clamp(0., width);
9273+ let to = (bed - left).clamp(from, width);
9274+ (from, to - from)
9275+}
9276+
8696 /// Scales an envelope to its own loudest sample, so a quietly mastered source9277 /// Scales an envelope to its own loudest sample, so a quietly mastered source
8697 /// still draws as a shape. The fixtures peak around an eighth of full scale, and9278 /// still draws as a shape. The fixtures peak around an eighth of full scale, and
8698 /// an eighth of a 30 px lane is a flat line -- which says "silent" about a file9279 /// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
@@ -8717,7 +9298,7 @@ fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f3
8717 if peaks.is_empty() || w <= 0. || h <= 0. {9298 if peaks.is_empty() || w <= 0. || h <= 0. {
8718 return Vec::new();9299 return Vec::new();
8719 }9300 }
8720- let cols = (w / WAVE_COL).ceil().max(1.) as usize;9301+ let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX);
8721 let mid = h / 2.;9302 let mid = h / 2.;
8722 (0..=cols)9303 (0..=cols)
8723 .map(|col| {9304 .map(|col| {
@@ -8970,6 +9551,56 @@ fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
8970 best.map_or(raw, |(_, start)| start)9551 best.map_or(raw, |(_, start)| start)
8971 }9552 }
8972 9553
9554+/// The edges worth landing on, off *every* lane: both ends of every clip on the
9555+/// timeline, less `skip` -- the clip being dragged, which does not snap to where
9556+/// it already is -- and less the other halves of its group, which travel with
9557+/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead
9558+/// and the head of the timeline go on the end: a clip meets the cursor and the
9559+/// start of the show as readily as it meets another take.
9560+///
9561+/// All lanes rather than the one being dropped on, because a cut is made across
9562+/// the timeline: a title on V2 lines up with the shot under it, and a sound
9563+/// effect lines up with the frame it belongs to.
9564+fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec<u32> {
9565+ let link = skip
9566+ .and_then(|(lane, idx)| lanes.get(lane)?.get(idx))
9567+ .and_then(|clip| clip.link);
9568+ let mut marks: Vec<u32> = lanes
9569+ .iter()
9570+ .enumerate()
9571+ .flat_map(|(lane, clips)| {
9572+ clips
9573+ .iter()
9574+ .enumerate()
9575+ .filter(move |&(idx, clip)| {
9576+ Some((lane, idx)) != skip && !(link.is_some() && clip.link == link)
9577+ })
9578+ .flat_map(|(_, clip)| [clip.start, clip.end()])
9579+ })
9580+ .collect();
9581+ marks.push(playhead);
9582+ marks.push(0);
9583+ marks
9584+}
9585+
9586+/// [`snapped`], and the mark that pulled it there -- the line the bed draws
9587+/// while the hand is still moving. `None` when nothing was near enough: a line
9588+/// standing over open bed would promise a landing that is not going to happen.
9589+/// The head is read before the tail, exactly as [`snapped`] prefers it.
9590+///
9591+/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
9592+/// draws no line at all, which is the whole point of being able to turn it off.
9593+fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option<u32>) {
9594+ if !on {
9595+ return (raw, None);
9596+ }
9597+ let start = snapped(raw, len, tol, marks);
9598+ let mark = [start, start.saturating_add(len)]
9599+ .into_iter()
9600+ .find(|mark| marks.contains(mark));
9601+ (start, mark)
9602+}
9603+
8973 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin9604 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin
8974 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An9605 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
8975 /// element that was never painted reads as its middle -- flat, the one answer9606 /// element that was never painted reads as its middle -- flat, the one answer
@@ -9173,11 +9804,15 @@ fn eq_spectrum_curve(levels: Vec<f32>) -> impl IntoElement {
9173 .size_full()9804 .size_full()
9174 }9805 }
9175 9806
9176-/// The cascade's frequency response, drawn as one line across the graph.9807+/// The cascade's frequency response, drawn as one line across the graph, with
9808+/// each band's own response threaded dimly under it.
9177 ///9809 ///
9178 /// Every point comes from `EqParams::response_db`, which reads the very9810 /// Every point comes from `EqParams::response_db`, which reads the very
9179 /// coefficients the samples are filtered through: the curve cannot drift from9811 /// coefficients the samples are filtered through: the curve cannot drift from
9180-/// what is heard, because there is no second copy of the maths.9812+/// what is heard, because there is no second copy of the maths. A single band's
9813+/// thread is that same call on a cascade of one, so the two cannot disagree
9814+/// either -- and it is what makes a boost sitting inside a cut visible at all,
9815+/// where the sum alone would draw a flat line and say nothing.
9181 ///9816 ///
9182 /// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the9817 /// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
9183 /// curve then rides the edge of the box; upgrade = a wider dB axis with the9818 /// curve then rides the edge of the box; upgrade = a wider dB axis with the
@@ -9187,16 +9822,37 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement {
9187 |_, _, _| (),9822 |_, _, _| (),
9188 move |bounds, _, window, _| {9823 move |bounds, _, window, _| {
9189 let (o, s) = (bounds.origin, bounds.size);9824 let (o, s) = (bounds.origin, bounds.size);
9190- let points: Vec<_> = (0..=EQ_CURVE_STEPS)9825+ let line = |of: &EqParams| -> Vec<_> {
9191- .map(|step| {9826+ (0..=EQ_CURVE_STEPS)
9192- let along = step as f32 / EQ_CURVE_STEPS as f32;9827+ .map(|step| {
9193- let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);9828+ let along = step as f32 / EQ_CURVE_STEPS as f32;
9194- point(9829+ point(
9195- o.x + s.width * along,9830+ o.x + s.width * along,
9196- o.y + s.height * eq_y(params.response_db(freq, sample_rate)),9831+ o.y + s.height
9197- )9832+ * eq_y(of.response_db(eq_freq(along), sample_rate)),
9833+ )
9834+ })
9835+ .collect()
9836+ };
9837+ // One thread per band, first, so the sum is drawn over them.
9838+ for band in &params.bands {
9839+ let mut bell = PathBuilder::stroke(px(1.));
9840+ for (step, at) in line(&EqParams {
9841+ bands: vec![*band],
9198 })9842 })
9199- .collect();9843+ .into_iter()
9844+ .enumerate()
9845+ {
9846+ match step {
9847+ 0 => bell.move_to(at),
9848+ _ => bell.line_to(at),
9849+ }
9850+ }
9851+ if let Ok(bell) = bell.build() {
9852+ window.paint_path(bell, rgba(EQ_BELL_INK));
9853+ }
9854+ }
9855+ let points = line(&params);
9200 // The area between the curve and 0 dB, closed along that line: a9856 // The area between the curve and 0 dB, closed along that line: a
9201 // boost and a cut wind opposite ways around it, which is exactly9857 // boost and a cut wind opposite ways around it, which is exactly
9202 // what makes both of them fill and the flat parts stay empty.9858 // what makes both of them fill and the flat parts stay empty.
@@ -9298,26 +9954,31 @@ fn timecode(t: f64, fps: f64) -> String {
9298 #[cfg(test)]9954 #[cfg(test)]
9299 mod tests {9955 mod tests {
9300 use super::{9956 use super::{
9301- ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx,9957+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, EQ_BANDS_MAX,
9302- EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,9958+ EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H,
9303- EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,9959+ EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE,
9960+ EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,
9304 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,9961 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,
9305 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,9962 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
9306 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,9963 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
9307 MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,9964 MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,
9308 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,9965 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo,
9309- Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, band_label, bitrate_refusal,9966+ Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,
9310- can_add, cancels_export, clipboard_after_remove, color_snap, containers, enable, envelope,9967+ bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers,
9311- eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key,9968+ enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,
9969+ estimated_mb, export_path, export_settings, format_key,
9312 format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram,9970 format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram,
9313- is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at, next_container,9971+ inserted_band, is_bare_modifier, is_project, keymap, keys_rows, lanes_h, marked, menu_at,
9972+ next_container,
9314 normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,9973 normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due,
9315- show_label, silence_rate, snapped, source_tint, span_partner, speed_at, summary_head,9974+ show_label, silence_rate, snap_cue, snap_marks, snapped, source_tint, span_partner,
9316- summary_tail, timecode, transport, unseen_paths, unseen_sources, whole_take, window_title,9975+ speed_at, summary_head, summary_tail, timecode, transport, unseen_paths, unseen_sources,
9976+ whole_take, window_title,
9317 };9977 };
9318 use super::{9978 use super::{
9319- LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP,9979+ Edge, LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES,
9320- file_name, file_uri, library_rows, px_along, repeats, span_label, unscannable,9980+ ZOOM_STEP, file_name, file_uri, library_rows, live_idx, px_along, repeats, span_label,
9981+ trimmed_clip, unscannable, visible_slice,
9321 };9982 };
9322 9983
9323 /// What the file manager is handed: the parts a path keeps as they are, and9984 /// What the file manager is handed: the parts a path keeps as they are, and
@@ -9900,6 +10561,10 @@ mod tests {
9900 "{action:?} is reachable by keyboard only"10561 "{action:?} is reachable by keyboard only"
9901 );10562 );
9902 }10563 }
10564+ // The snap has a door of its own as well as its row on the card: the
10565+ // button beside the zoom, which says which way it is set as well as
10566+ // setting it.
10567+ assert!(element("snap"), "no snap button beside the zoom");
9903 // And the card is a door the pointer can open: the panel's own button.10568 // And the card is a door the pointer can open: the panel's own button.
9904 assert!(element("keys"), "no way to open the actions card");10569 assert!(element("keys"), "no way to open the actions card");
9905 // The card-local strokes have the same rule, and each of them is a thing10570 // The card-local strokes have the same rule, and each of them is a thing
@@ -10582,6 +11247,62 @@ mod tests {
10582 assert_eq!(snapped(2, 40, 4, &marks), 0);11247 assert_eq!(snapped(2, 40, 4, &marks), 0);
10583 }11248 }
10584 11249
11250+ /// Where those edges come from: every lane, not the one being dropped on --
11251+ /// and never the clip in the hand or the half of it one track down.
11252+ #[test]
11253+ fn the_marks_are_every_lane_the_playhead_and_the_start() {
11254+ let clip = |start: u32, frames: u32, link| Clip {
11255+ start,
11256+ in_frame: 0,
11257+ out_frame: frames,
11258+ source: 0,
11259+ link,
11260+ eq: None,
11261+ color: None,
11262+ fit: Default::default(),
11263+ speed: Default::default(),
11264+ };
11265+ // A grouped take across two lanes at 100..160, and a lone one on the
11266+ // audio lane at 400..430.
11267+ let video = [clip(100, 60, Some(7))];
11268+ let audio = [clip(100, 60, Some(7)), clip(400, 30, None)];
11269+ let lanes: [&[Clip]; 2] = [&video, &audio];
11270+
11271+ // Nothing in the hand: both lanes' edges, the playhead, and 0.
11272+ let mut all = snap_marks(&lanes, None, 300);
11273+ all.sort_unstable();
11274+ assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]);
11275+
11276+ // The video half in the hand: its own edges are gone, and so are its
11277+ // group's on the other lane -- both boxes travel with the drag. The
11278+ // lone audio clip is still a target, which is the whole point: a take
11279+ // being carried on V1 lands flush with a sound on A1.
11280+ let mut carried = snap_marks(&lanes, Some((0, 0)), 300);
11281+ carried.sort_unstable();
11282+ assert_eq!(carried, [0, 300, 400, 430]);
11283+
11284+ // An index that names no clip skips nothing and still answers.
11285+ assert_eq!(snap_marks(&[], Some((3, 9)), 0), [0, 0]);
11286+ }
11287+
11288+ /// The line the bed draws, and the switch that turns the whole thing off.
11289+ #[test]
11290+ fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() {
11291+ let marks = [100, 160, 300, 0];
11292+ // Pulled by the tail: the clip lands at 60 and the line stands on the
11293+ // edge its *tail* met, 100 -- not on the head it happens to have.
11294+ assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100)));
11295+ // Pulled by the head: line and landing are the same frame.
11296+ assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160)));
11297+ // A trim carries no length, so only its own edge lands.
11298+ assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300)));
11299+ // Open bed: nothing moves and nothing is drawn.
11300+ assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None));
11301+ // Switched off, a gesture that would have snapped lands raw and draws
11302+ // no line -- the frame-by-frame placement the toggle is for.
11303+ assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
11304+ }
11305+
10585 #[test]11306 #[test]
10586 fn timecode_counts_frames_inside_the_second() {11307 fn timecode_counts_frames_inside_the_second() {
10587 assert_eq!(timecode(0., 30.), "00:00:00:00");11308 assert_eq!(timecode(0., 30.), "00:00:00:00");
@@ -11162,6 +11883,9 @@ mod tests {
11162 "12 kHz high shelf"11883 "12 kHz high shelf"
11163 ]11884 ]
11164 );11885 );
11886+ // A band moved off a round number reads as where it *is*: a keystroke
11887+ // that changes the filter and not the number on the card is a keystroke
11888+ // nobody can aim.
11165 assert_eq!(11889 assert_eq!(
11166 band_label(&Band {11890 band_label(&Band {
11167 freq_hz: 2600.,11891 freq_hz: 2600.,
@@ -11169,23 +11893,38 @@ mod tests {
11169 q: 1.,11893 q: 1.,
11170 kind: BandKind::Peak11894 kind: BandKind::Peak
11171 }),11895 }),
11172- "3 kHz",11896+ "2.6 kHz"
11173- "rounded, because a band label is not a measurement"11897+ );
11898+ assert_eq!(eq_freq_label(1122.), "1.12 kHz");
11899+ assert_eq!(eq_freq_label(12000.), "12 kHz", "no zeroes to read past");
11900+ assert_eq!(eq_freq_label(80.), "80 Hz");
11901+
11902+ // The card fits the smallest window and takes the room a bigger one has
11903+ // -- it is a graph, and the width *is* the frequency resolution.
11904+ assert!(eq_card_w(640.) <= 640. - 24., "card too wide for 640");
11905+ assert!(eq_card_w(1280.) > eq_card_w(640.), "card ignores the window");
11906+ assert_eq!(eq_card_w(1920.), EQ_W_MAX, "card grows without end");
11907+ assert!(eq_card_w(320.) >= KEYS_W, "card narrower than a row of text");
11908+ // At the smallest window the graph is still a graph: three across for
11909+ // one down, so an octave is wide enough to put a handle in.
11910+ assert!(
11911+ eq_card_w(640.) - 24. >= 3. * EQ_GRAPH_H,
11912+ "graph too square to aim at"
11174 );11913 );
11175 11914
11176 // The same shape as the other two cards, so it fits where they do: the11915 // The same shape as the other two cards, so it fits where they do: the
11177 // graph stands where the export card's rows do, and is shorter than11916 // graph stands where the export card's rows do, and is shorter than
11178- // they are.11917+ // they are. The numbers row is a row of buttons now, so it is one of
11179- let (title, status, readout, gaps, padding) = (17., 28., 17., 4. * 2., 24.);11918+ // those tall rather than one line of text.
11919+ let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.);
11180 assert!(11920 assert!(
11181- title + status + EQ_GRAPH_H + readout + gaps + padding + CONTROL_H <= 360.,11921+ title + status + EQ_GRAPH_H + HIT_MIN + gaps + padding + CONTROL_H <= 360.,
11182 "card too tall"11922 "card too tall"
11183 );11923 );
11184 assert!(11924 assert!(
11185 EQ_GRAPH_H <= EXPORT_ROWS_H,11925 EQ_GRAPH_H <= EXPORT_ROWS_H,
11186 "graph taller than a card of rows"11926 "graph taller than a card of rows"
11187 );11927 );
11188- assert!(KEYS_W <= 640., "card too wide");
11189 // What is dragged is the whole graph -- the handle is a 10 px dot, but11928 // What is dragged is the whole graph -- the handle is a 10 px dot, but
11190 // a press anywhere in the box takes the band nearest it -- so WCAG11929 // a press anywhere in the box takes the band nearest it -- so WCAG
11191 // 2.5.8 is satisfied by the box, which is far past the minimum.11930 // 2.5.8 is satisfied by the box, which is far past the minimum.
@@ -11197,6 +11936,83 @@ mod tests {
11197 assert!(KEYS_ROW_H >= HIT_MIN);11936 assert!(KEYS_ROW_H >= HIT_MIN);
11198 }11937 }
11199 11938
11939+ /// Editing a band, which is what the card is *for*: the pointer reads a
11940+ /// frequency off the axis the same way the axis draws one, a new band lands
11941+ /// in the gap beside the picked one rather than on top of it, and every band
11942+ /// the card will hold has a digit that picks it.
11943+ #[test]
11944+ fn a_band_can_be_moved_added_and_reached() {
11945+ use engine::eq::{Band, BandKind, EqParams};
11946+ // Across the graph and back: a drag sets the frequency the handle is
11947+ // then drawn at, so the two mappings have to be one another's inverse or
11948+ // the handle walks away from the pointer.
11949+ for freq in [20., 80., 250., 1000., 4000., 12000., 20000.] {
11950+ let read = eq_freq(eq_x(freq));
11951+ assert!(
11952+ (read / freq - 1.).abs() < 1e-3,
11953+ "{freq} Hz read back as {read}"
11954+ );
11955+ }
11956+ // Off the box either end stops at the axis, never past it.
11957+ assert_eq!(eq_freq(-1.), EQ_FREQ_LOW);
11958+ assert_eq!(eq_freq(2.), EQ_FREQ_HIGH);
11959+
11960+ // A step of the frequency keys is a real move on screen -- a keystroke
11961+ // that changes nothing visible is a keystroke that reads as broken --
11962+ // and small enough to aim with.
11963+ let step = eq_x(1000. * EQ_FREQ_STEP) - eq_x(1000.);
11964+ assert!(step > 0.01 && step < 0.06, "frequency key steps {step}");
11965+
11966+ // A new band lands between the picked one and the next one up, in
11967+ // octaves: 250 Hz and 1 kHz put it at 500, which is a gap on screen.
11968+ let bands = EqParams::default_layout().bands;
11969+ let added = inserted_band(&bands, 1);
11970+ assert!((added.freq_hz - 500.).abs() < 1., "landed at {added:?}");
11971+ assert_eq!(added.gain_db, 0., "a new band changes nothing until moved");
11972+ assert_eq!(added.kind, BandKind::Peak, "a new band is not a shelf");
11973+ assert!(eq_x(added.freq_hz) - eq_x(bands[1].freq_hz) > 0.1);
11974+ // Above the topmost band the gap is the rest of the axis, and the band
11975+ // still lands on it rather than off the end.
11976+ let top = inserted_band(&bands, bands.len() - 1);
11977+ assert!(
11978+ top.freq_hz > bands[4].freq_hz && top.freq_hz <= EQ_FREQ_HIGH,
11979+ "landed at {top:?}"
11980+ );
11981+ // Bands out of frequency order (a drag may cross two over) still get a
11982+ // sane neighbour: the next one *up*, not the next one along the list.
11983+ let crossed = vec![
11984+ Band {
11985+ freq_hz: 4000.,
11986+ gain_db: 0.,
11987+ q: 1.,
11988+ kind: BandKind::Peak,
11989+ },
11990+ Band {
11991+ freq_hz: 100.,
11992+ gain_db: 0.,
11993+ q: 1.,
11994+ kind: BandKind::Peak,
11995+ },
11996+ ];
11997+ let between = inserted_band(&crossed, 1);
11998+ assert!(
11999+ (between.freq_hz - 632.).abs() < 2.,
12000+ "landed at {between:?}, not between 100 and 4000"
12001+ );
12002+
12003+ // Every band the card will hold is one digit away: the keyboard has ten
12004+ // digits, which is exactly why the cap is what it is.
12005+ assert!(
12006+ EQ_BANDS_MAX <= 10,
12007+ "a band past the tenth has no key that picks it"
12008+ );
12009+ assert!(EQ_BANDS_MAX > EqParams::default_layout().bands.len());
12010+ // The Q range holds the default, so a file's band never opens out of
12011+ // range and needs dragging back in before it can be edited.
12012+ assert!((EQ_Q_LOW..=EQ_Q_HIGH).contains(&0.707));
12013+ assert!(EQ_Q_STEP > 1.);
12014+ }
12015+
11200 /// The analyser drawn behind the curve: a tone has to land on its own12016 /// The analyser drawn behind the curve: a tone has to land on its own
11201 /// frequency, or the backdrop is a decoration rather than a reading of what12017 /// frequency, or the backdrop is a decoration rather than a reading of what
11202 /// is playing -- and someone shaping a band against it would be aiming at12018 /// is playing -- and someone shaping a band against it would be aiming at
@@ -12206,6 +13022,141 @@ mod tests {
12206 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());13022 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
12207 }13023 }
12208 13024
13025+ /// A box laid out wider than any screen -- a long clip at a deep zoom -- is
13026+ /// still one screen's worth of columns: the path a repaint has to build is
13027+ /// bounded by what can be seen, not by what the layout says the box is.
13028+ /// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points
13029+ /// per frame, and the repaint that stalls on it is the waveform that
13030+ /// "disappeared".
13031+ #[test]
13032+ fn an_envelope_never_costs_more_points_than_a_screen_can_show() {
13033+ let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect();
13034+ // The width a 5 s clip is laid out at when the bed shows 8 frames of it.
13035+ let huge = 5. * 30. / 8. * 1200.;
13036+ let cols = envelope(&peaks, 0., 5., huge, 30.);
13037+ assert!(
13038+ cols.len() <= WAVE_COLS_MAX + 1,
13039+ "{} columns for a {huge} px box",
13040+ cols.len()
13041+ );
13042+ // ...and the slice actually painted is the part of the box on the bed,
13043+ // which is where that width stops mattering: a column per two visible
13044+ // pixels, at every zoom.
13045+ let (x, w) = visible_slice(-huge / 2., huge, 1200.);
13046+ assert_eq!((x, w), (huge / 2., 1200.));
13047+ assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601);
13048+ // A box entirely off the bed has no slice, and one that has never been
13049+ // measured is drawn whole -- what was drawn before there was a bed.
13050+ assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.));
13051+ assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.));
13052+ assert_eq!(visible_slice(-40., 500., 0.), (0., 500.));
13053+ // Half on, at either edge.
13054+ assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.));
13055+ assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.));
13056+ }
13057+
13058+ /// The box a trim draws is the box its release commits, at every speed. The
13059+ /// preview used to hand the *timeline* frame count to a source-frame field:
13060+ /// at 2x a tail moved twice as fast as the pointer and snapped back on
13061+ /// release, and a head drag moved the clip's other edge.
13062+ #[test]
13063+ fn a_trim_preview_lands_where_the_release_commits() {
13064+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
13065+ session.set_gain(0.0);
13066+ for permille in SPEED_PRESETS {
13067+ // Live, so the loop owes it no undo step: the speeds are the axis
13068+ // this walks, and the trims below are what is undone.
13069+ session
13070+ .set_speed_live(Lane::V1, 0, Speed::from_permille(permille))
13071+ .expect("a clip alone on its lane may be speeded");
13072+ for edge in [Edge::Start, Edge::End] {
13073+ let clip = session.lane_clips(Lane::V1)[0];
13074+ let (lo, hi) = session
13075+ .trim_room(Lane::V1, 0, edge)
13076+ .expect("clip 0 is there");
13077+ // Both walls and the middle of the room: the whole range a
13078+ // pointer can be clamped to.
13079+ for to in [lo, (lo + hi) / 2, hi] {
13080+ let preview = trimmed_clip(clip, edge, to, false);
13081+ // The drag is one edit and one undo step, so the next `to`
13082+ // is measured from the same clip this one was.
13083+ if session.trim_clip(Lane::V1, 0, edge, to) {
13084+ assert_eq!(
13085+ preview,
13086+ session.lane_clips(Lane::V1)[0],
13087+ "{edge:?} to {to} at {permille} per mille"
13088+ );
13089+ assert!(session.undo(), "the trim is one undo step");
13090+ } else {
13091+ // An edge already where it was asked to go is not an
13092+ // edit, and the preview draws the clip unchanged.
13093+ assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille");
13094+ }
13095+ assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
13096+ }
13097+ }
13098+ }
13099+ }
13100+
13101+ /// A still trims the same way, and the preview knows it: its head grows
13102+ /// forward from source frame 0 -- every frame of it is the same picture --
13103+ /// so the box stretches instead of sliding left.
13104+ #[test]
13105+ fn a_stills_trim_preview_grows_forward_like_the_commit() {
13106+ let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens");
13107+ for edge in [Edge::Start, Edge::End] {
13108+ let clip = session.lane_clips(Lane::V1)[0];
13109+ let (lo, hi) = session
13110+ .trim_room(Lane::V1, 0, edge)
13111+ .expect("clip 0 is there");
13112+ for to in [lo, (lo + hi) / 2, hi] {
13113+ let preview = trimmed_clip(clip, edge, to, true);
13114+ match session.trim_clip(Lane::V1, 0, edge, to) {
13115+ true => {
13116+ assert_eq!(
13117+ preview,
13118+ session.lane_clips(Lane::V1)[0],
13119+ "a still {edge:?} to {to}"
13120+ );
13121+ assert!(session.undo(), "the trim is one undo step");
13122+ }
13123+ false => assert_eq!(preview, clip, "a still {edge:?} to {to}"),
13124+ }
13125+ assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
13126+ }
13127+ }
13128+ }
13129+
13130+ /// gpui freezes a drag's payload for the whole gesture, and nothing stops a
13131+ /// stroke from editing the lane under it: the drop has to find the clip that
13132+ /// was picked up, not whatever slid into its index.
13133+ #[test]
13134+ fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() {
13135+ let at = |start: u32| Clip {
13136+ start,
13137+ in_frame: 0,
13138+ out_frame: 30,
13139+ source: 0,
13140+ link: None,
13141+ eq: None,
13142+ color: None,
13143+ fit: FitPolicy::Fit,
13144+ speed: Speed::NORMAL,
13145+ };
13146+ let lane = [at(0), at(30), at(60)];
13147+ let dragged = lane[2];
13148+ assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
13149+ // A delete in front of it: the clip is now index 1, and the index the
13150+ // drag froze names a clip nobody grabbed.
13151+ let after = [at(0), at(60)];
13152+ assert_eq!(live_idx(&after, 2, dragged), Some(1));
13153+ assert_eq!(live_idx(&after, 1, dragged), Some(1));
13154+ // Deleted mid-drag: there is nothing to move, and moving its neighbour
13155+ // instead is exactly the bug this exists for.
13156+ assert_eq!(live_idx(&[at(0)], 2, dragged), None);
13157+ assert_eq!(live_idx(&[], 0, dragged), None);
13158+ }
13159+
12209 #[test]13160 #[test]
12210 fn a_quiet_source_still_draws_as_a_shape() {13161 fn a_quiet_source_still_draws_as_a_shape() {
12211 // An eighth of full scale, which is about where the fixtures sit.13162 // An eighth of full scale, which is about where the fixtures sit.
@@ -12553,6 +13504,8 @@ fn main() {
12553 scrubbing: false,13504 scrubbing: false,
12554 trim: None,13505 trim: None,
12555 grab: 0,13506 grab: 0,
13507+ snap: true,
13508+ snap_cue: None,
12556 last_scrub: Instant::now(),13509 last_scrub: Instant::now(),
12557 last_target: 0,13510 last_target: 0,
12558 export: None,13511 export: None,