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 {
7878 Speed,
7979 Silence,
8080 Mix,
81+ ToggleSnap,
8182 CancelExport,
8283 }
8384
8485 impl ActionId {
8586 /// Display order everywhere -- the editor lists them in it and
8687 /// [`Keymap::defaults`] binds them in it.
87- pub const ALL: [ActionId; 39] = [
88+ pub const ALL: [ActionId; 40] = [
8889 ActionId::Play,
8990 ActionId::StepBack,
9091 ActionId::StepForward,
@@ -123,6 +124,7 @@ impl ActionId {
123124 ActionId::Speed,
124125 ActionId::Silence,
125126 ActionId::Mix,
127+ ActionId::ToggleSnap,
126128 ActionId::CancelExport,
127129 ];
128130
@@ -167,6 +169,7 @@ impl ActionId {
167169 ActionId::Speed => "Speed (tape)…",
168170 ActionId::Silence => "Silences: cut or speed up…",
169171 ActionId::Mix => "Mix: track volumes and the limiter…",
172+ ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
170173 ActionId::CancelExport => "Cancel export",
171174 }
172175 }
@@ -213,6 +216,7 @@ impl ActionId {
213216 ActionId::Speed => "speed",
214217 ActionId::Silence => "silence",
215218 ActionId::Mix => "mix",
219+ ActionId::ToggleSnap => "toggle-snap",
216220 ActionId::CancelExport => "cancel-export",
217221 }
218222 }
@@ -265,6 +269,9 @@ impl ActionId {
265269 | ActionId::AddVideoLane
266270 | ActionId::AddAudioLane
267271 | 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
268275 | ActionId::RemoveAudioLane => Category::Editing,
269276 ActionId::ToggleMute
270277 | ActionId::VolumeUp
@@ -326,7 +333,7 @@ pub struct Fixed {
326333 pub category: Category,
327334 }
328335
329-pub const FIXED: [Fixed; 21] = [
336+pub const FIXED: [Fixed; 26] = [
330337 // Not a chord at all but a way of pressing one, and the only place the
331338 // editor can say so: holding a key that moves a *value* runs it, and
332339 // holding anything else still does what one press did.
@@ -394,7 +401,7 @@ pub const FIXED: [Fixed; 21] = [
394401 // its own: a band nothing but a drag can reach is a band half the users of
395402 // this editor cannot move at all. Card-local, so none of them is bindable.
396403 Fixed {
397- chord: "1–5",
404+ chord: "1–9, 0",
398405 label: "Pick an equalizer band",
399406 category: Category::Audio,
400407 },
@@ -408,6 +415,31 @@ pub const FIXED: [Fixed; 21] = [
408415 label: "Lower the picked band 1 dB",
409416 category: Category::Audio,
410417 },
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+ },
411443 Fixed {
412444 chord: "r",
413445 label: "Flatten every band",
@@ -645,6 +677,9 @@ impl Keymap {
645677 // machine's volume and not the project's -- two things one key
646678 // must not mean.
647679 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),
648683 b(ActionId::CancelExport, "escape", false),
649684 ],
650685 }
@@ -907,7 +942,7 @@ mod tests {
907942 #[test]
908943 fn every_default_stroke_reaches_its_action() {
909944 let k = Keymap::defaults();
910- assert_eq!(k.entries().len(), 41);
945+ assert_eq!(k.entries().len(), 42);
911946 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
912947 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
913948 // ends of the timeline.
@@ -1141,7 +1176,8 @@ mod tests {
11411176 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
11421177 // The label is the editor's column, and never the file's word for it.
11431178 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");
11451181 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
11461182 }
11471183
crates/app/src/main.rsmodified+1141 -188
@@ -19,11 +19,11 @@ use engine::project::{Edge, Lane, LaneKind, Source, Speed};
1919 use engine::scale::FitPolicy;
2020 use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
2121 use gpui::{
22- AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
23- KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
24- Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign,
25- TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px,
26- relative, rgb, rgba, size,
22+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, DragMoveEvent,
23+ FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
24+ PathBuilder, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size,
25+ Stateful, TextAlign, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img,
26+ point, prelude::*, px, relative, rgb, rgba, size,
2727 };
2828
2929 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -85,6 +85,13 @@ const WAVE_BPS: u32 = 40;
8585 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
8686 /// and a path with a point per pixel is a path per repaint.
8787 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;
8895 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
8996 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.
9097 const HIT_MIN: f32 = 24.;
@@ -281,6 +288,13 @@ struct AssetDrag(PathBuf, usize);
281288 struct ClipDrag {
282289 lane: Lane,
283290 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,
284298 }
285299
286300 /// 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.;
569583 /// and short enough that the card still fits a 360 px window.
570584 const EQ_GRAPH_H: f32 = 132.;
571585
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+
572616 /// How many points the curve is drawn from. One per ~3 px across the card:
573617 /// past that the line is smooth and the extra biquad evaluations are wasted.
574618 const EQ_CURVE_STEPS: usize = 96;
@@ -617,6 +661,11 @@ const EQ_SPECTRUM_INK: u32 = 0x7f95ad66;
617661 /// its weight: it is what makes a boost read as a hill rather than as a wire.
618662 const EQ_FILL_INK: u32 = 0x4a9eff26;
619663
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+
620669 /// The colour card's four controls, in the order it lists them: what each is
621670 /// called and the range it moves in. The order is `ColorParams`' own, which is
622671 /// what [`color_band`] indexes.
@@ -790,6 +839,16 @@ struct Player {
790839 /// the value being dragged, and stale between drags, which costs nothing --
791840 /// no drag starts without a press on the box it moves.
792841 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>,
793852 last_scrub: Instant,
794853 last_target: u32,
795854 /// The running export. While it owns the UI the editor is read-only.
@@ -1133,12 +1192,26 @@ impl Player {
11331192 ActionId::Speed => self.open_speed(cx),
11341193 ActionId::Silence => self.open_silence(cx),
11351194 ActionId::Mix => self.open_mix(None, cx),
1195+ ActionId::ToggleSnap => self.toggle_snap(cx),
11361196 // Nothing to cancel while nothing is exporting; the export guard in
11371197 // the key handler is what answers this one while there is.
11381198 ActionId::CancelExport => {}
11391199 }
11401200 }
11411201
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+
11421215 /// Whether the editor can be asked for `action` right now, and why not when
11431216 /// it cannot. `on` is the clip the question is about -- the one a clip menu
11441217 /// was opened on -- and `None` asks about the marked clip instead, which is
@@ -2016,41 +2089,78 @@ impl Player {
20162089 cx.notify();
20172090 }
20182091
2019- /// Moves one band and says whether anything changed. Live only: the write
2020- /// is [`commit_eq`](Player::commit_eq)'s.
2021- fn set_band(&mut self, band: usize, gain_db: f32) -> bool {
2022- let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
2023- match self.eq_params.bands.get_mut(band) {
2024- Some(b) if b.gain_db != gain_db => {
2025- b.gain_db = gain_db;
2026- true
2027- }
2028- _ => false,
2092+ /// Changes the picked band in place and says whether anything moved. Every
2093+ /// edit of a band goes through here -- the drag, each key, each stepper
2094+ /// button -- so the card has exactly one place that clamps a band into what
2095+ /// the graph can draw, and no caller has to remember the limits.
2096+ fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
2097+ let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
2098+ return false;
2099+ };
2100+ let was = *band;
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);
20292113 }
20302114 }
20312115
2032- /// The keyboard's version of a drag: one step on the picked band, committed
2033- /// straight away -- a keystroke has no release to wait for.
2034- fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {
2035- let gain = self
2036- .eq_params
2037- .bands
2038- .get(self.eq_band)
2039- .map_or(0., |b| b.gain_db);
2040- if self.set_band(self.eq_band, gain + by) {
2041- self.commit_eq(cx);
2116+ /// Where the pointer sits in the graph, as the picked band's frequency and
2117+ /// gain: across is the frequency axis and down is the gain one, so the
2118+ /// handle follows the hand both ways rather than sliding up a rail. Called
2119+ /// on every pointer sample, so the curve bends under it; the write is the
2120+ /// release's ([`commit_eq`](Player::commit_eq)).
2121+ fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
2122+ let bounds = self.eq_graph.get();
2123+ let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
2124+ let freq = eq_freq(frac_along(at.x, bounds));
2125+ if self.set_band(|b| {
2126+ b.gain_db = gain;
2127+ b.freq_hz = freq;
2128+ }) {
2129+ cx.notify();
20422130 }
20432131 }
20442132
2045- /// Where the pointer sits down the graph, as a gain on the picked band: the
2046- /// middle is flat and the top and bottom edges are the limit either way.
2047- /// Called on every pointer sample, so the curve bends under the hand; the
2048- /// write is the release's ([`commit_eq`](Player::commit_eq)).
2049- fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {
2050- let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT;
2051- if self.set_band(self.eq_band, gain) {
2133+ /// A band added beside the picked one, at the frequency with the most room
2134+ /// around it ([`inserted_band`]), and picked so the next keystroke moves the
2135+ /// band that was just made. Refused rather than silently ignored at the cap.
2136+ fn add_band(&mut self, cx: &mut Context<Self>) {
2137+ if self.eq_params.bands.len() >= EQ_BANDS_MAX {
2138+ self.notice = Some(
2139+ format!(
2140+ "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
2141+ )
2142+ .into(),
2143+ );
20522144 cx.notify();
2145+ return;
20532146 }
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);
20542164 }
20552165
20562166 /// Which band a press on the graph grabs: the nearest one along the
@@ -2450,8 +2560,8 @@ impl Player {
24502560 if self.exporting().is_some() {
24512561 return;
24522562 }
2453- let (Some(start), Some(was)) = (
2454- self.drop_frame(from, idx, to, x),
2563+ let (Some((start, _)), Some(was)) = (
2564+ self.drop_frame(from, idx, x),
24552565 self.session
24562566 .as_ref()
24572567 .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
@@ -2513,26 +2623,70 @@ impl Player {
25132623 /// the scroll clamp pins the bed's right edge to the duration, and the
25142624 /// pointer has no pixel past it. The upgrade is to let the scroll clamp
25152625 /// 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> {
2517- let session = self.session.as_ref()?;
2518- let clip = session.lane_clips(from).get(idx).copied()?;
2626+ fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
2627+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
25192628 let raw = self.frame_under(x).saturating_sub(self.grab);
2520- // The edges worth landing on: both ends of every clip already on the
2521- // lane it is being let go over, the playhead, and the head of the
2522- // timeline. Never the group's own boxes -- a clip does not snap to
2523- // where it already is.
2524- let mut marks: Vec<u32> = session
2525- .lane_clips(to)
2526- .iter()
2527- .enumerate()
2528- .filter(|&(i, c)| {
2529- (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link)
2530- })
2531- .flat_map(|(_, c)| [c.start, c.end()])
2532- .collect();
2533- marks.push(frame_at(session.now(), self.fps));
2534- marks.push(0);
2535- Some(snapped(raw, clip.frames(), self.snap_frames(), &marks))
2629+ let marks = self.snap_targets(Some((from, idx)));
2630+ Some(self.snap_to(raw, clip.frames(), &marks))
2631+ }
2632+
2633+ /// Which index the clip in the hand is at *now*: [`live_idx`] against the
2634+ /// lane the drag named, since a stroke during the gesture moves the indices
2635+ /// gpui froze into the payload. Both halves of a drag ask it -- the line
2636+ /// drawn in flight and the drop that commits -- so the promise and the
2637+ /// landing are made about one clip.
2638+ fn dragged(&self, drag: &ClipDrag) -> Option<usize> {
2639+ let session = self.session.as_ref()?;
2640+ live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip)
2641+ }
2642+
2643+ /// The line while the clip is still in the hand: the very answer
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)
25362690 }
25372691
25382692 /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
@@ -2596,14 +2750,25 @@ impl Player {
25962750 /// against the same duration the boxes are drawn to, so the edge tracks the
25972751 /// pointer exactly.
25982752 fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
2599- let at = self.frame_under(x);
2600- let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
2753+ let Some(trim) = self.trim else {
26012754 return;
26022755 };
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 {
26042765 return;
26052766 };
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 });
26072772 cx.notify();
26082773 }
26092774
@@ -2645,39 +2810,13 @@ impl Player {
26452810 }) else {
26462811 return clip;
26472812 };
2648- match trim.edge {
2649- // A still grows forward from source frame 0 instead, exactly as
2650- // `Project::trim` writes it: with the in-point clamped at 0 the box
2651- // below would slide left rather than stretch, and the release would
2652- // then commit a wider clip than the drag drew.
2653- Edge::Start
2654- if self.session.as_ref().is_some_and(|session| {
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- }
2813+ let still = self.session.as_ref().is_some_and(|session| {
2814+ session
2815+ .sources()
2816+ .get(clip.source)
2817+ .is_some_and(|s| engine::is_image(&s.path))
2818+ });
2819+ trimmed_clip(clip, trim.edge, trim.to, still)
26812820 }
26822821
26832822 /// How long the timeline is *drawn* as: its own length, and while a tail is
@@ -2685,6 +2824,15 @@ impl Player {
26852824 /// at the last frame has nowhere to put a pointer that means "longer", so
26862825 /// without this the last clip on the timeline could be pulled in and never
26872826 /// 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.
26882836 fn drawn_duration(&self) -> f64 {
26892837 let Some(session) = &self.session else {
26902838 return 0.;
@@ -3715,31 +3863,55 @@ impl Render for Player {
37153863 // cannot move at all, and every one of them is listed in the
37163864 // keys menu (keymap.rs `FIXED`) rather than being a secret.
37173865 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;
37183871 if key == ESCAPE {
37193872 // Nothing to undo: every change is already at the clip,
37203873 // and undo is undo's own key.
37213874 this.eq_open = None;
37223875 this.eq_dragging = false;
37233876 } else if key == "up" {
3724- this.nudge_band(EQ_STEP, cx);
3877+ this.nudge_band(|b| b.gain_db += EQ_STEP, cx);
37253878 } 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);
37273888 } else if key == "r" {
37283889 for band in &mut this.eq_params.bands {
37293890 band.gain_db = 0.;
37303891 }
37313892 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);
37323901 } else if key == "s" {
37333902 // The analyser off and on. Nothing is committed: it is
37343903 // what the card *shows*, so it survives no further than
37353904 // this window.
37363905 this.eq_spectrum = !this.eq_spectrum;
37373906 } else if let Ok(digit) = key.parse::<usize>() {
3738- // 1-based, as the rows are numbered on screen; a digit
3739- // past the last band picks nothing rather than panics.
3740- if let Some(band) = digit.checked_sub(1)
3741- && band < this.eq_params.bands.len()
3742- {
3907+ // As the keys are laid out: 1-9 then 0 for the tenth,
3908+ // which is the cap ([`EQ_BANDS_MAX`]). A digit past the
3909+ // last band picks nothing rather than panics.
3910+ let band = match digit {
3911+ 0 => EQ_BANDS_MAX - 1,
3912+ n => n - 1,
3913+ };
3914+ if band < this.eq_params.bands.len() {
37433915 this.eq_band = band;
37443916 }
37453917 }
@@ -3878,6 +4050,26 @@ impl Render for Player {
38784050 }
38794051 }
38804052 }))
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+ )
38814073 // Scrubbing is tracked on the root because the pointer leaves the
38824074 // 6 px ruler on the first drag and its own listeners then stop
38834075 // firing; the root's hitbox is the whole window.
@@ -3886,7 +4078,7 @@ impl Render for Player {
38864078 // the equalizer drag is tracked here for the ruler's reason.
38874079 if this.eq_dragging {
38884080 if event.pressed_button == Some(MouseButton::Left) {
3889- this.drag_band(event.position.y, cx);
4081+ this.drag_band(event.position, cx);
38904082 } else {
38914083 // Released outside the window: the up below never came,
38924084 // so this is where the gesture ends -- and it still owes
@@ -3956,7 +4148,7 @@ impl Render for Player {
39564148 if std::mem::take(&mut this.eq_dragging) {
39574149 // The release lands exactly, then the gesture is written
39584150 // once -- the append-only table's whole reason.
3959- this.drag_band(event.position.y, cx);
4151+ this.drag_band(event.position, cx);
39604152 this.commit_eq(cx);
39614153 return;
39624154 }
@@ -4058,7 +4250,7 @@ impl Render for Player {
40584250 // column, and only one of the two is ever up.
40594251 .children(self.keys_overlay(cx))
40604252 .children(self.export_card(window.viewport_size(), cx))
4061- .children(self.eq_card(cx))
4253+ .children(self.eq_card(window.viewport_size(), cx))
40624254 .children(self.color_card(cx))
40634255 .children(self.speed_card(cx))
40644256 .children(self.silence_card(cx))
@@ -4643,6 +4835,25 @@ impl Player {
46434835 live,
46444836 cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)),
46454837 ))
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+ ))
46464857 // Import is not here: it belongs to the media list it adds
46474858 // to, and two doors into one action is a question about
46484859 // which one is the real one.
@@ -4715,10 +4926,20 @@ impl Player {
47154926 .gap(px(12.))
47164927 // Fixed width and one line: changing digits must not push
47174928 // 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.
47184934 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
47194935 "{} / {}",
47204936 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+ )
47224943 )))
47234944 .child(
47244945 div()
@@ -5498,20 +5719,28 @@ impl Player {
54985719 }
54995720
55005721 /// 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 them
5502- /// all. The curve is the clip's actual filter (`EqParams::response_db`
5503- /// reads the coefficients the samples go through), and it is redrawn on
5504- /// every pointer sample of a drag, so the shape bends under the hand.
5722+ /// curve, a handle per band sitting on it, each band's own bell under the
5723+ /// sum, and a row that reads and moves the picked band's three numbers. The
5724+ /// curve is the clip's actual filter (`EqParams::response_db` reads the
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.
55055727 ///
5506- /// The same scrim and width as the other two cards, and the same plain divs
5507- /// -- nothing here takes focus, so the root keeps the keyboard and the
5508- /// card's own strokes (`1`–`5`, up, down, `r`) reach it.
5728+ /// Wider than the other cards and wider still on a bigger window
5729+ /// ([`eq_card_w`]): every pixel across is frequency resolution, which none
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.
55095734 ///
55105735 /// Every change is written at the clip as it is made
55115736 /// ([`Player::commit_eq`]), so what the card shows is always what is
55125737 /// playing: there is no OK button to forget, and closing it changes
55135738 /// 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> {
55155744 let (lane, idx) = self.eq_open?;
55165745 // The rate the engine filters this timeline at, so the drawn curve is
55175746 // the one those coefficients make -- near the top of the axis a 44.1 kHz
@@ -5565,13 +5794,20 @@ impl Player {
55655794 .bg(rgb(HOVER_DIM))
55665795 .cursor_pointer()
55675796 // 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.
55695800 .on_mouse_down(
55705801 MouseButton::Left,
55715802 cx.listener(|this, event: &MouseDownEvent, _, cx| {
55725803 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+ }
55735809 this.eq_dragging = true;
5574- this.drag_band(event.position.y, cx);
5810+ this.drag_band(event.position, cx);
55755811 }),
55765812 )
55775813 .child(bounds_probe(self.eq_graph.clone()))
@@ -5663,7 +5899,7 @@ impl Player {
56635899 })
56645900 .child(
56655901 div()
5666- .w(px(KEYS_W))
5902+ .w(px(eq_card_w(f32::from(viewport.width))))
56675903 .flex()
56685904 .flex_col()
56695905 .gap(px(2.))
@@ -5684,28 +5920,15 @@ impl Player {
56845920 .text_size(px(11.))
56855921 .text_color(rgb(INK_DIM))
56865922 .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()
56885924 })),
56895925 )
56905926 .child(graph)
5691- // Which band the keyboard is holding and what it is set
5692- // to: the curve shows the sum, and a band pushed against
5693- // one pulling the other way is not readable off it.
5694- .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(
5695- match picked {
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- ))
5927+ // Which band the keyboard is holding and every number it
5928+ // is set to, each with the pair of buttons that moves it:
5929+ // the curve shows the sum, and a band pushed against one
5930+ // pulling the other way is not readable off it.
5931+ .child(self.eq_numbers(picked, cx))
57095932 .child(
57105933 div()
57115934 .mt(px(4.))
@@ -5729,7 +5952,45 @@ impl Player {
57295952 }
57305953 this.commit_eq(cx);
57315954 }))
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"),
57335994 )
57345995 // The analyser's switch, next to the one other
57355996 // button the card has: `s` does the same, and a
@@ -5764,6 +6025,103 @@ impl Player {
57646025 )
57656026 }
57666027
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+
57676125 /// The colour card: the graded frame's histogram over a row per control,
57686126 /// each row a bar the pointer drags straight to a value -- no stepper
57696127 /// buttons, because a slider is a thing to pull, and the arrow keys still
@@ -6823,6 +7181,19 @@ impl Player {
68237181 // it, so all of them move together when it does. No bed width is needed
68247182 // to place them any more -- a second is so many pixels wherever it is.
68257183 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));
68267197 let clips = self
68277198 .session
68287199 .as_ref()
@@ -6969,7 +7340,12 @@ impl Player {
69697340 // the window, which took it from the release that fired
69707341 // this (gpui window.rs:3602).
69717342 .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);
69737349 this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx)
69747350 }))
69757351 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
@@ -6978,10 +7354,21 @@ impl Player {
69787354 // to -- its own included, which is the drag that moves a
69797355 // take along its track.
69807356 .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)
69827365 }))
69837366 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
69847367 .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;
69857372 // What a drag on an edge is showing, which is the clip
69867373 // itself while nothing is being dragged.
69877374 let clip = &self.trimmed(lane, i, *clip);
@@ -7007,15 +7394,30 @@ impl Player {
70077394 .unwrap_or(clip.source),
70087395 );
70097396 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);
70107402 let label = sources.get(clip.source).map(|s| file_name(&s.path));
70117403 let wave = sources
70127404 .get(clip.source)
70137405 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
70147406 .cloned();
7015- let (from, to) = (
7016- f64::from(clip.in_frame) / self.fps,
7017- f64::from(clip.out_frame) / self.fps,
7018- );
7407+ // The source seconds that slice plays -- not the clip's
7408+ // whole range: the envelope is drawn for the part of the
7409+ // box that can be seen, at the resolution of the pixels
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);
70197421 let tip = tip.clone();
70207422 // What the pointer carries on the way to another lane:
70217423 // the file the box is showing, the same ghost a library
@@ -7038,7 +7440,7 @@ impl Player {
70387440 // off the left edge: the bed clips what hangs out
70397441 // of it, so a half-visible clip is drawn as the
70407442 // half of itself that is on screen.
7041- .left(px(scale.px_at(start)))
7443+ .left(px(left))
70427444 .w(px(width))
70437445 .overflow_hidden()
70447446 .rounded(px(3.))
@@ -7059,9 +7461,14 @@ impl Player {
70597461 // starts the drag still selects, so picking a clip
70607462 // up and putting it back down where it was is
70617463 // exactly a click.
7062- .on_drag(ClipDrag { lane, idx: i }, move |_, _, _, cx| {
7063- cx.new(|_| Tip(ghost.clone()))
7064- })
7464+ .on_drag(
7465+ ClipDrag {
7466+ lane,
7467+ idx: i,
7468+ clip: placed,
7469+ },
7470+ move |_, _, _, cx| cx.new(|_| Tip(ghost.clone())),
7471+ )
70657472 .on_mouse_down(
70667473 MouseButton::Left,
70677474 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
@@ -7120,7 +7527,7 @@ impl Player {
71207527 zone
71217528 }))
71227529 // 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| {
71247531 let inner: AnyElement = match wave {
71257532 Wave::Peaks(peaks) => {
71267533 waveform(peaks, from, to).into_any_element()
@@ -7156,8 +7563,8 @@ impl Player {
71567563 Some(
71577564 div()
71587565 .absolute()
7159- .left_0()
7160- .right_0()
7566+ .left(px(vis_x))
7567+ .w(px(vis_w))
71617568 .top(px(LABEL_H))
71627569 .bottom_0()
71637570 .child(inner),
@@ -7168,24 +7575,44 @@ impl Player {
71687575 // cannot say whether a short clip is a trim or a
71697576 // clip at 4x, and that is the difference between a
71707577 // 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| {
71727585 d.child(
71737586 div()
71747587 .absolute()
71757588 .top_0()
7176- .right_0()
7177- .px(px(3.))
7178- .rounded(px(3.))
7179- .bg(rgb(ACCENT))
7180- .text_size(px(9.))
7181- .text_color(rgb(SURFACE))
7182- .child(format!("{}", clip.speed)),
7589+ .left(px(vis_x))
7590+ .w(px(vis_w))
7591+ .flex()
7592+ .justify_end()
7593+ .overflow_hidden()
7594+ .child(
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+ ),
71837604 )
71847605 })
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| {
71867610 d.child(
71877611 div()
7188- .relative()
7612+ .absolute()
7613+ .top_0()
7614+ .left(px(vis_x))
7615+ .w(px(vis_w))
71897616 .h(px(LABEL_H))
71907617 .px(px(4.))
71917618 .truncate()
@@ -7213,6 +7640,20 @@ impl Player {
72137640 .bg(rgba(0x4a9effaa))
72147641 }),
72157642 )
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+ }))
72167657 // Last, so it is over the clips: the same fraction in both
72177658 // lanes, which is the playhead being one line.
72187659 .child(
@@ -7437,6 +7878,36 @@ fn eq_x(freq_hz: f32) -> f32 {
74377878 ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
74387879 }
74397880
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+
74407911 /// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
74417912 /// so a cut reads as a dip below the line it is a cut from. The inverse of
74427913 /// [`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 {
74467917 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
74477918 }
74487919
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+
74497933 /// What a band row calls itself: the corner or centre frequency, and for a
74507934 /// shelf the fact that it tilts everything past it -- which is the difference
74517935 /// between "12 kHz" moving the last octave and moving one band inside it.
74527936 fn band_label(band: &Band) -> String {
7453- let freq = match band.freq_hz >= 1000. {
7454- true => format!("{:.0} kHz", band.freq_hz / 1000.),
7455- false => format!("{:.0} Hz", band.freq_hz),
7456- };
7937+ let freq = eq_freq_label(band.freq_hz);
74577938 match band.kind {
74587939 BandKind::LowShelf => format!("{freq} low shelf"),
74597940 BandKind::HighShelf => format!("{freq} high shelf"),
@@ -7826,6 +8307,15 @@ fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<Str
78268307 })
78278308 }
78288309
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+
78298319 /// What the media list is given of the window. A share of it, so a narrow
78308320 /// window gives the panel less rather than giving the picture nothing, floored
78318321 /// where a name stops being readable and capped at a third of the window --
@@ -8693,6 +9183,97 @@ fn show_label(w: f32) -> bool {
86939183 w >= LABEL_MIN_W
86949184 }
86959185
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+
86969277 /// Scales an envelope to its own loudest sample, so a quietly mastered source
86979278 /// still draws as a shape. The fixtures peak around an eighth of full scale, and
86989279 /// 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
87179298 if peaks.is_empty() || w <= 0. || h <= 0. {
87189299 return Vec::new();
87199300 }
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);
87219302 let mid = h / 2.;
87229303 (0..=cols)
87239304 .map(|col| {
@@ -8970,6 +9551,56 @@ fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
89709551 best.map_or(raw, |(_, start)| start)
89719552 }
89729553
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+
89739604 /// Where down an element a pointer sits, 0..1 from the top: the vertical twin
89749605 /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
89759606 /// 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 {
91739804 .size_full()
91749805 }
91759806
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.
91779809 ///
91789810 /// Every point comes from `EqParams::response_db`, which reads the very
91799811 /// 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.
91819816 ///
91829817 /// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
91839818 /// 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 {
91879822 |_, _, _| (),
91889823 move |bounds, _, window, _| {
91899824 let (o, s) = (bounds.origin, bounds.size);
9190- let points: Vec<_> = (0..=EQ_CURVE_STEPS)
9191- .map(|step| {
9192- let along = step as f32 / EQ_CURVE_STEPS as f32;
9193- let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);
9194- point(
9195- o.x + s.width * along,
9196- o.y + s.height * eq_y(params.response_db(freq, sample_rate)),
9197- )
9825+ let line = |of: &EqParams| -> Vec<_> {
9826+ (0..=EQ_CURVE_STEPS)
9827+ .map(|step| {
9828+ let along = step as f32 / EQ_CURVE_STEPS as f32;
9829+ point(
9830+ o.x + s.width * along,
9831+ o.y + s.height
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],
91989842 })
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);
92009856 // The area between the curve and 0 dB, closed along that line: a
92019857 // boost and a cut wind opposite ways around it, which is exactly
92029858 // what makes both of them fill and the flat parts stay empty.
@@ -9298,26 +9954,31 @@ fn timecode(t: f64, fps: f64) -> String {
92989954 #[cfg(test)]
92999955 mod tests {
93009956 use super::{
9301- ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx,
9302- EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,
9303- EQ_SPECTRUM_DB, EQ_TICKS, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,
9957+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, EQ_BANDS_MAX,
9958+ EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H,
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,
93049961 Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK,
93059962 INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
93069963 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
93079964 MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS,
93089965 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,
9310- can_add, cancels_export, clipboard_after_remove, color_snap, containers, enable, envelope,
9311- eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key,
9966+ Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,
9967+ bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, containers,
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,
93129970 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,
93149973 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,
9316- summary_tail, timecode, transport, unseen_paths, unseen_sources, whole_take, window_title,
9974+ show_label, silence_rate, snap_cue, snap_marks, snapped, source_tint, span_partner,
9975+ speed_at, summary_head, summary_tail, timecode, transport, unseen_paths, unseen_sources,
9976+ whole_take, window_title,
93179977 };
93189978 use super::{
9319- LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP,
9320- file_name, file_uri, library_rows, px_along, repeats, span_label, unscannable,
9979+ Edge, LaneKind, PPS_DEFAULT, Repeat, Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES,
9980+ ZOOM_STEP, file_name, file_uri, library_rows, live_idx, px_along, repeats, span_label,
9981+ trimmed_clip, unscannable, visible_slice,
93219982 };
93229983
93239984 /// What the file manager is handed: the parts a path keeps as they are, and
@@ -9900,6 +10561,10 @@ mod tests {
990010561 "{action:?} is reachable by keyboard only"
990110562 );
990210563 }
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");
990310568 // And the card is a door the pointer can open: the panel's own button.
990410569 assert!(element("keys"), "no way to open the actions card");
990510570 // The card-local strokes have the same rule, and each of them is a thing
@@ -10582,6 +11247,62 @@ mod tests {
1058211247 assert_eq!(snapped(2, 40, 4, &marks), 0);
1058311248 }
1058411249
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+
1058511306 #[test]
1058611307 fn timecode_counts_frames_inside_the_second() {
1058711308 assert_eq!(timecode(0., 30.), "00:00:00:00");
@@ -11162,6 +11883,9 @@ mod tests {
1116211883 "12 kHz high shelf"
1116311884 ]
1116411885 );
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.
1116511889 assert_eq!(
1116611890 band_label(&Band {
1116711891 freq_hz: 2600.,
@@ -11169,23 +11893,38 @@ mod tests {
1116911893 q: 1.,
1117011894 kind: BandKind::Peak
1117111895 }),
11172- "3 kHz",
11173- "rounded, because a band label is not a measurement"
11896+ "2.6 kHz"
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"
1117411913 );
1117511914
1117611915 // The same shape as the other two cards, so it fits where they do: the
1117711916 // graph stands where the export card's rows do, and is shorter than
11178- // they are.
11179- let (title, status, readout, gaps, padding) = (17., 28., 17., 4. * 2., 24.);
11917+ // they are. The numbers row is a row of buttons now, so it is one of
11918+ // those tall rather than one line of text.
11919+ let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.);
1118011920 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.,
1118211922 "card too tall"
1118311923 );
1118411924 assert!(
1118511925 EQ_GRAPH_H <= EXPORT_ROWS_H,
1118611926 "graph taller than a card of rows"
1118711927 );
11188- assert!(KEYS_W <= 640., "card too wide");
1118911928 // What is dragged is the whole graph -- the handle is a 10 px dot, but
1119011929 // a press anywhere in the box takes the band nearest it -- so WCAG
1119111930 // 2.5.8 is satisfied by the box, which is far past the minimum.
@@ -11197,6 +11936,83 @@ mod tests {
1119711936 assert!(KEYS_ROW_H >= HIT_MIN);
1119811937 }
1119911938
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+
1120012016 /// The analyser drawn behind the curve: a tone has to land on its own
1120112017 /// frequency, or the backdrop is a decoration rather than a reading of what
1120212018 /// is playing -- and someone shaping a band against it would be aiming at
@@ -12206,6 +13022,141 @@ mod tests {
1220613022 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
1220713023 }
1220813024
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+
1220913160 #[test]
1221013161 fn a_quiet_source_still_draws_as_a_shape() {
1221113162 // An eighth of full scale, which is about where the fixtures sit.
@@ -12553,6 +13504,8 @@ fn main() {
1255313504 scrubbing: false,
1255413505 trim: None,
1255513506 grab: 0,
13507+ snap: true,
13508+ snap_cue: None,
1255613509 last_scrub: Instant::now(),
1255713510 last_target: 0,
1255813511 export: None,