forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

eq.rs563 lines, 27.2 KiBHistoryRawDownload
1//! The EQ card and its band numbers.
2
3use super::common::*;
4use super::numedit;
5use crate::ui::icons::{Icon, IconSize};
6use crate::ui::kit;
7use crate::ui::type_scale::{self, Typeset};
8use crate::ui::widgets::overlay_tip_hover;
9use crate::*;
10
11/// The left gutter the dB labels sit in, outside the plot.
12const EQ_AXIS_L: f32 = 52.;
13/// The strip over the plot the "Play to see sound" note sits in.
14const EQ_NOTE_H: f32 = 18.;
15/// The row under the plot the frequency labels sit in.
16const EQ_LABEL_H: f32 = 14.;
17/// The frequencies the axis names, the ends left to the box's own edges.
18const EQ_NAMED_HZ: [f32; 3] = [100., 1000., 10000.];
19/// A knob's radius. The plot is inset by it on the top, right and bottom, so a
20/// band at +12 or -12 dB is drawn wholly inside the box and never on a label.
21const EQ_KNOB_R: f32 = EQ_HANDLE / 2.;
22/// The gains the plot rules a line across: the two limits, the two halves and 0 dB.
23const EQ_DB_LINES: [f32; 5] = [EQ_GAIN_LIMIT, EQ_DB_GRID[0], 0., EQ_DB_GRID[1], -EQ_GAIN_LIMIT];
24
25/// A frequency as its axis label: "20 Hz", "100 Hz", "1 kHz", "10 kHz", "20 kHz".
26fn eq_hz_label(freq: f32) -> String {
27 if freq >= 1000. {
28 format!("{:.0} kHz", freq / 1000.)
29 } else {
30 format!("{freq:.0} Hz")
31 }
32}
33
34/// A gain as its axis label, with a real minus sign. Only the top label carries the unit.
35fn eq_db_label(db: f32, top: bool) -> String {
36 let number = match db {
37 d if d > 0. => format!("+{d:.0}"),
38 d if d < 0. => format!("\u{2212}{:.0}", -d),
39 _ => "0".to_string(),
40 };
41 if top { format!("{number} dB") } else { number }
42}
43
44/// What a band's shape does, in plain words: the one line under its name.
45fn eq_shape_why(kind: BandKind) -> &'static str {
46 match kind {
47 BandKind::LowCut => "Removes rumble below the frequency",
48 BandKind::LowShelf => "Raises or lowers everything below",
49 BandKind::Peak => "Raises or lowers around the frequency",
50 BandKind::HighShelf => "Raises or lowers everything above",
51 BandKind::HighCut => "Removes hiss above the frequency",
52 }
53}
54
55impl Player {
56 /// The equalizer of one audio clip: its frequency response drawn as a
57 /// curve, a handle per band sitting on it, each band's own bell under the
58 /// sum, and a row that reads and moves the picked band's three numbers. The
59 /// curve is the clip's actual filter (`EqParams::response_db` reads the
60 /// coefficients the samples go through), and it is redrawn on every pointer
61 /// sample of a drag, so the shape bends under the hand.
62 ///
63 /// Wider than the other cards and wider still on a bigger window
64 /// ([`eq_card_w`]): every pixel across is frequency resolution, which none
65 /// of the row-shaped cards have any use for. The same scrim and the same
66 /// plain divs -- nothing here takes focus, so the root keeps the keyboard
67 /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`,
68 /// `s`) reach it.
69 ///
70 /// Every change is written at the clip as it is made
71 /// ([`Player::commit_eq`]), so what the card shows is always what is
72 /// playing: there is no OK button to forget, and closing it changes
73 /// nothing. What takes a curve back off is undo, like every other edit.
74 pub(crate) fn eq_card(
75 &self,
76 viewport: Size<Pixels>,
77 cx: &mut Context<Self>,
78 ) -> Option<impl IntoElement> {
79 let (lane, idx) = self.eq_open?;
80 // The rate the engine filters this timeline at, so the drawn curve is
81 // the one those coefficients make -- near the top of the axis a 44.1 kHz
82 // clip and a 48 kHz one are not the same shape.
83 let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate);
84 let picked = self.eq_params.bands.get(self.eq_band);
85 // What is playing, drawn behind the curve -- and only while something
86 // *is* playing: the tap freezes with the device, and a still spectrum
87 // under a paused timeline would look like sound that is not there.
88 let spectrum = self
89 .eq_spectrum
90 .then_some(self.session.as_ref())
91 .flatten()
92 .filter(|session| session.is_playing())
93 .and_then(PlaybackSession::audio_tap)
94 .map(|(samples, rate)| eq_spectrum(&samples, rate))
95 .filter(|levels| !levels.is_empty())
96 .map(eq_spectrum_curve);
97 let playing = self.session.as_ref().is_some_and(PlaybackSession::is_playing);
98 let handles: Vec<_> = self
99 .eq_params
100 .bands
101 .iter()
102 .enumerate()
103 .map(|(i, band)| {
104 // The hit area, centred on the point: it hangs off the graph's
105 // corner, so it is pulled back by half of itself both ways.
106 // The dot is drawn in the middle of it.
107 div()
108 .absolute()
109 .left(relative(eq_x(band.freq_hz)))
110 .top(relative(eq_y(if eq_takes_gain(band.kind) { band.gain_db } else { 0. })))
111 .ml(px(-EQ_HIT / 2.))
112 .mt(px(-EQ_HIT / 2.))
113 .w(px(EQ_HIT))
114 .h(px(EQ_HIT))
115 .flex()
116 .items_center()
117 .justify_center()
118 .child({
119 let d = if i == self.eq_band { EQ_HANDLE * 1.6 } else { EQ_HANDLE };
120 div()
121 .w(px(d))
122 .h(px(d))
123 .rounded(px(d / 2.))
124 .bg(rgb(if i == self.eq_band { INK1() } else { INK3() }))
125 })
126 })
127 .collect();
128 // Maximized used to claim a fixed 320 px slice for the graph
129 // regardless of how much room a small bench actually left the card,
130 // so the numbers/buttons rows below it were the ones squeezed into a
131 // scroll -- docked, at the same bench, showed all of them with no
132 // scroll at all. `flex_1` between the docked floor and the maximized
133 // ceiling lets the graph take whatever is *actually* left after the
134 // rows below it claim their own natural height first, the same
135 // leftover-space idiom `dock_stance::dock_sources` already uses for
136 // its own scroll region.
137 let graph_maximized = self.card_maximized;
138 // The plot is inset from the box: its edges are where ±12 dB and the
139 // ends of the frequency axis fall, and the knobs there are drawn half
140 // outside them. The labels live in the gutters the inset leaves.
141 let plot = div()
142 .absolute()
143 .left(px(EQ_AXIS_L))
144 .right(px(EQ_KNOB_R))
145 .top(px(EQ_NOTE_H + EQ_KNOB_R))
146 .bottom(px(EQ_KNOB_R + EQ_LABEL_H))
147 // The probe measures the plot, so a pointer's x and y map onto the
148 // same inset axis the curve is drawn on.
149 .child(bounds_probe(self.eq_graph.clone()))
150 // The analyser first, so everything else is drawn on top of it.
151 .children(spectrum)
152 // The decades, so a hump can be read as "around 200 Hz" without
153 // dropping the eye to the labels along the bottom. The two ends
154 // are the plot's own edges and rule nothing.
155 .children(
156 EQ_TICKS
157 .iter()
158 .filter(|(freq, _)| *freq > EQ_FREQ_LOW && *freq < EQ_FREQ_HIGH)
159 .map(|(freq, _)| {
160 div()
161 .absolute()
162 .left(relative(eq_x(*freq)))
163 .w(px(1.))
164 .h_full()
165 .bg(rgb(DARK_HAIRLINE()))
166 })
167 .collect::<Vec<_>>(),
168 )
169 // The gain rules, the limits and 0 dB included: each one a line the
170 // curve can be read against, with its number beside it in the gutter.
171 .children(EQ_DB_LINES.map(|db| {
172 div()
173 .absolute()
174 .top(relative(eq_y(db)))
175 .w_full()
176 .h(px(1.))
177 .bg(rgb(DARK_HAIRLINE()))
178 }))
179 .children(EQ_DB_LINES.iter().enumerate().map(|(i, &db)| {
180 div()
181 .absolute()
182 .left(px(-EQ_AXIS_L))
183 .w(px(EQ_AXIS_L - EQ_KNOB_R - 4.))
184 .top(relative(eq_y(db)))
185 .mt(px(-7.))
186 .whitespace_nowrap()
187 .text_align(TextAlign::Right)
188 .map(|d| d.type_style(type_scale::caption()).text_color(rgb(INK3())))
189 .child(eq_db_label(db, i == 0))
190 }))
191 .child(eq_curve(self.eq_params.clone(), sample_rate))
192 .children(handles)
193 // The frequency labels under the plot, one row, each centred under its own
194 // grid line. The range is the box's own edges, so only the three names in
195 // the middle are written.
196 .children(EQ_TICKS.iter().filter(|(freq, _)| EQ_NAMED_HZ.contains(freq)).map(|(freq, _)| {
197 let text = eq_hz_label(*freq);
198 let w = eq_tick_end_w(&text, type_scale::CHORD_METADATA_MIN_PX) + 8.;
199 div()
200 .absolute()
201 .top(relative(1.))
202 .mt(px(EQ_KNOB_R))
203 .h(px(EQ_LABEL_H))
204 .w(px(w))
205 .left(relative(eq_x(*freq)))
206 .ml(px(-w / 2.))
207 .whitespace_nowrap()
208 .text_align(TextAlign::Center)
209 .map(|d| d.type_style(type_scale::caption()).text_color(rgb(INK3())))
210 .child(text)
211 }));
212 let graph = div()
213 // Ided like the band rows it replaces: what the pointer presses on
214 // is one element with its own hitbox, which is what a drag is
215 // tracked from.
216 .id("eq-graph")
217 .relative()
218 .when(graph_maximized, |d| {
219 d.flex_1().min_h(px(EQ_GRAPH_H)).max_h(px(EQ_GRAPH_MAX_H))
220 })
221 .when(!graph_maximized, |d| d.flex_none().h(px(eq_graph_h(false))))
222 .rounded(px(3.))
223 .bg(rgb(DARK_HAIRLINE()))
224 .cursor_pointer()
225 // The press picks the band under it *and* is already the first
226 // sample of the drag, so a plain click sets a value. A second click
227 // takes that band back to flat instead: the gesture that undoes one
228 // handle, with no modifier to remember.
229 .on_mouse_down(
230 MouseButton::Left,
231 cx.listener(|this, event: &MouseDownEvent, _, cx| {
232 this.eq_band = this.nearest_band(event.position.x);
233 if event.click_count >= 2 {
234 this.eq_dragging = false;
235 this.nudge_band(|b| b.gain_db = 0., cx);
236 return;
237 }
238 this.eq_dragging = true;
239 this.drag_band(event.position, cx);
240 }),
241 )
242 // A switched-on analyser over a stopped timeline would draw
243 // nothing, which reads as broken: say what it is waiting for, in the
244 // strip over the plot where no knob or curve can reach it.
245 .children((self.eq_spectrum && !playing).then(eq_listen_note))
246 .child(plot);
247 // The bottom of the axis is not named: -12 dB would land in the same
248 // corner as the 20 Hz tick, and the two lines above it (+6 and -6)
249 // already say what the box is worth per pixel.
250 //
251 // The same affordance the column itself carries, read back off the
252 // card's own handle: this is the tallest card in the inspector -- a
253 // 132 px graph with a row of numbers and a row of buttons under it --
254 // and at the 360 px floor it is taller than the column it is docked in.
255 let can_scroll = f32::from(self.eq_scroll.max_offset().height) > 1.;
256 let below = px_below(
257 f32::from(self.eq_scroll.max_offset().height),
258 f32::from(self.eq_scroll.offset().y),
259 );
260 Some(
261 self.card_outer(viewport, cx)
262 .child(
263 div()
264 // A cap, not a width: the card is docked in the
265 // inspector now, and that column is narrower than the
266 // floor a graph wants -- asking for [`eq_card_w`]
267 // outright hung the card's right-hand third off the edge
268 // of the window. The two cards beside it are built this
269 // way for the same reason.
270 .id("eq-card")
271 .w_full()
272 .max_w(px(eq_card_w(f32::from(viewport.width), self.card_maximized)))
273 // And a cap the other way, for the same reason the width
274 // has one: the card is docked in a column now, and at the
275 // 360 px floor it is taller than that column -- its title
276 // ran off the top and its buttons off the bottom, with
277 // neither reachable. The card itself owns that scroll:
278 // every child, including the below-fold line, is in its
279 // wheel surface rather than a fixed sibling dead zone.
280 .max_h(relative(1.))
281 .overflow_y_scroll()
282 .track_scroll(&self.eq_scroll)
283 // Maximized also *claims* the room the cap above
284 // only allows: `flex_1()`/`max_h` on the graph below
285 // has nothing to grow into if the card itself still
286 // hugs its own content height.
287 .when(graph_maximized, |d| d.h(relative(1.)))
288 .on_mouse_down(MouseButton::Left, swallow)
289 .flex()
290 .flex_col()
291 .gap(px(CARD_GAP))
292 .map(|d| self.card_surface(d))
293 .child(
294 div()
295 .id("eq-card-rows")
296 // A non-maximized card exposes the body's full
297 // natural height to its parent scroll surface;
298 // maximized fills the claimed card room so the
299 // graph can consume only the leftover height.
300 .when(!graph_maximized, |d| d.flex_none())
301 .when(graph_maximized, |d| d.flex_1())
302 .flex()
303 .flex_col()
304 .gap(px(2.))
305 // Which clip, because the card is modal and the lane it
306 // was opened from is behind a scrim by the time it is up.
307 .map(|d| {
308 d.child(dark_card_head_reset(
309 "Equalizer",
310 Some(format!("{} clip {}", lane.label(), idx + 1).into()),
311 Some("drag a handle, or tab/shift+tab picks a band — ←→ moves it, ↑↓ its gain, shift+←→ its width; a adds, x removes, f flattens it, r all, s spectrum, m fills the room".into()),
312 Some(self.card_maximized),
313 Some(reset_eq_layout),
314 cx,
315 ))
316 })
317
318
319 .child(graph)
320 // Which band the keyboard is holding and every number it
321 // is set to, each with the pair of buttons that moves it:
322 // the curve shows the sum, and a band pushed against one
323 // pulling the other way is not readable off it.
324 .child(self.eq_numbers(picked, cx))
325 .child(self.eq_shape_row(picked, cx))
326 .child(kit::switch_row(
327 "eq-spectrum",
328 "Show spectrum",
329 Some("Draws the sound that is playing behind the curve".into()),
330 self.eq_spectrum,
331 None,
332 {
333 let me = cx.entity();
334 move |_, app| {
335 me.update(app, |this, cx| {
336 this.eq_spectrum = !this.eq_spectrum;
337 cx.notify();
338 })
339 }
340 },
341 ))
342 .child(
343 div()
344 .mt(px(4.))
345 .flex()
346 .items_center()
347 .gap(px(4.))
348 .child(kit::icon_ghost("eq-add", Icon::Plus, "Add band", None, {
349 let me = cx.entity();
350 move |_, app| me.update(app, |this, cx| this.add_band(cx))
351 }))
352 .child(kit::icon_ghost("eq-remove", Icon::Trash2, "Remove band", None, {
353 let me = cx.entity();
354 move |_, app| me.update(app, |this, cx| this.remove_band(cx))
355 }))
356 .child(div().flex_1())
357 .child(
358 kit::Button::new("eq-reset")
359 .label("Flatten all")
360 .build()
361 .tooltip(crate::ui::widgets::overlay_tip_hover("Flatten all", "r", None))
362 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
363 for band in &mut this.eq_params.bands {
364 band.gain_db = 0.;
365 }
366 this.commit_eq(cx);
367 })),
368 ),
369 ),
370 )
371 // The column's own line, on the card that needs it for
372 // the column's reason: a row nobody knows is under the
373 // fold is a row that is not there.
374 .when(can_scroll, |d| {
375 d.child(dark_help(match below > 1. {
376 true => "more below — scroll the card",
377 false => "the end — scroll up for the rest",
378 }))
379 })
380 ,
381 ),
382 )
383 }
384
385 /// The picked band's three numbers -- where it sits, how far it pushes and
386 /// how wide it is -- each beside the pair of buttons that moves it. The
387 /// arrows do the same three things, but a value only a key can change is a
388 /// value a hand on the pointer cannot reach at all, which is the same reason
389 /// [`Player::mbps_steppers`] exists.
390 pub(crate) fn eq_numbers(
391 &self,
392 picked: Option<&Band>,
393 cx: &mut Context<Self>,
394 ) -> impl IntoElement {
395 let row = div()
396 .flex_none()
397 .w_full()
398 .flex()
399 .flex_col()
400 .gap(px(4.))
401 .px(px(6.));
402 let Some(band) = picked.copied() else {
403 return row.child(dark_help("no bands — a adds one"));
404 };
405 // Gain and width are number fields: drag to scrub, click to type. The
406 // name carries its own tooltip, so the plain meaning is one hover away.
407 let number = |name: &'static str,
408 id: &'static str,
409 why: &'static str,
410 target: numedit::NumTarget,
411 value: f32,
412 cx: &mut Context<Self>| {
413 div()
414 .w_full()
415 .flex()
416 .items_center()
417 .gap(px(6.))
418 .child(
419 div()
420 .id((id, 1_usize))
421 .flex_1()
422 .min_w(px(0.))
423 .child(dark_row_label(name, false))
424 .tooltip(overlay_tip_hover(name, "", Some(why))),
425 )
426 .child(numedit::field(id, name, target, f64::from(value), cx))
427 };
428 let count = self.eq_params.bands.len();
429 let pills: Vec<kit::Segment> = (1..=count).map(|i| kit::Segment::text(i.to_string())).collect();
430 let picker = kit::segmented_wrap("eq-band", &pills, self.eq_band, true, None, {
431 let me = cx.entity();
432 move |i, _, app| {
433 me.update(app, |this, cx| {
434 this.eq_band = i;
435 cx.notify();
436 })
437 }
438 });
439 row.child(div().w_full().flex().flex_col().gap(px(4.)).child(dark_row_label("Band", false)).child(picker))
440 .child(number("Frequency", "eq-freq-field", "Where the band sits on the scale", numedit::NumTarget::Freq, band.freq_hz, cx))
441 // A cut has no level, so a gain row under one would be a number that
442 // does nothing -- it is left out rather than shown and ignored.
443 .children(eq_takes_gain(band.kind).then(|| {
444 number("Gain", "eq-gain-field", "How far the band lifts or cuts", numedit::NumTarget::Gain, band.gain_db, cx)
445 }))
446 .child(number("Width", "eq-q-field", "How wide the change is. Lower is wider.", numedit::NumTarget::Width, band.q, cx))
447 .child(numedit::catcher(cx))
448 .child(dark_ghost_button(
449 "eq-flat-band",
450 "Flatten band",
451 "f",
452 false,
453 cx.listener(|this, _: &ClickEvent, _, cx| this.nudge_band(|b| b.gain_db = 0., cx)),
454 ))
455 }
456
457 /// The picked band's shape as a dropdown, the way the Effects card picks a
458 /// blend mode: the list says what each shape does in one plain line, and the
459 /// line under the field says it for the one picked. Changing it is one edit
460 /// like any other, so it goes through the same nudge as the numbers.
461 fn eq_shape_row(&self, picked: Option<&Band>, cx: &mut Context<Self>) -> Div {
462 let row = div().px(px(6.)).w_full().flex().flex_col().gap(px(4.));
463 let Some(band) = picked else {
464 return row;
465 };
466 let t = crate::ui::theme::tokens();
467 let open = self.eq_shape_open;
468 let current = EQ_KINDS.iter().position(|(k, ..)| *k == band.kind).unwrap_or(0);
469 let field = kit::dropdown_field("eq-kind", EQ_KINDS[current].1, true).on_click(cx.listener(
470 |this, _: &ClickEvent, _, cx| {
471 this.eq_shape_open = !this.eq_shape_open;
472 cx.notify();
473 },
474 ));
475 let list = open.then(|| {
476 let backdrop = div().absolute().top(px(-4000.)).left(px(-4000.)).size(px(8000.)).on_mouse_down(
477 MouseButton::Left,
478 cx.listener(|this, _: &MouseDownEvent, _, cx| {
479 this.eq_shape_open = false;
480 cx.stop_propagation();
481 cx.notify();
482 }),
483 );
484 let mut plate = kit::plate(6.)
485 .id("eq-kind-list")
486 .w_full()
487 .max_h(px(284.))
488 .overflow_y_scroll()
489 .p(px(crate::layout::MENU_PAD))
490 .flex()
491 .flex_col()
492 .occlude();
493 for (k, (kind, name, _)) in EQ_KINDS.iter().enumerate() {
494 let kind = *kind;
495 plate = plate.child(
496 div()
497 .id(("eq-kind-row", k))
498 .flex_none()
499 .px(px(8.))
500 .py(px(4.))
501 .flex()
502 .items_start()
503 .gap(px(8.))
504 .rounded(px(4.))
505 .cursor_pointer()
506 .hover(|s| s.bg(rgba(crate::ui::theme::WASH_HOVER)))
507 .child(div().flex_none().size(px(16.)).children((k == current).then(|| Icon::Check.el(IconSize::Inline, t.accent))))
508 .child(
509 div()
510 .flex_1()
511 .min_w(px(0.))
512 .flex()
513 .flex_col()
514 .child(div().type_style(type_scale::body_strong()).text_color(rgb(t.ink1)).child(*name))
515 .child(dark_help(eq_shape_why(kind))),
516 )
517 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
518 this.eq_shape_open = false;
519 this.nudge_band(|b| b.kind = kind, cx);
520 })),
521 );
522 }
523 gpui::deferred(
524 div()
525 .absolute()
526 .top(px(crate::layout::redesign::CONTROL_M + 2.))
527 .left(px(0.))
528 .w_full()
529 .child(backdrop)
530 .child(plate),
531 )
532 });
533 row.child(dark_row_label("Shape", false))
534 .child(div().relative().w_full().child(field).children(list))
535 .child(dark_help(eq_shape_why(band.kind)))
536 }
537}
538
539/// The card's `Reset all`: the five-band layout a clip opens on, flat. The
540/// picked band is kept inside the shorter list it may land in.
541fn reset_eq_layout(this: &mut Player, cx: &mut Context<Player>) {
542 this.eq_params = EqParams::default_layout();
543 this.eq_band = this.eq_band.min(this.eq_params.bands.len() - 1);
544 this.commit_eq(cx);
545}
546
547/// The analyser is switched on but nothing is playing, so there is no sound to
548/// draw. Said in the strip over the plot, right-aligned, where no curve reaches.
549fn eq_listen_note() -> impl IntoElement {
550 div()
551 .absolute()
552 .top(px(1.))
553 .right(px(4.))
554 .h(px(16.))
555 .flex()
556 .items_center()
557 .type_style(type_scale::label_tabular(
558 type_scale::CHORD_METADATA_MIN_PX,
559 gpui::FontWeight::MEDIUM,
560 ))
561 .text_color(rgb(INK3()))
562 .child("Play to see sound")
563}