forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

numedit.rs236 lines, 8.1 KiBHistoryRawDownload
1//! The EQ band's number fields: drag to scrub, click to type.
2//!
3//! The edit state is one pair of cells per window thread, since only one number is ever being
4//! pressed or typed at a time; `typing` is what the key handler asks before the keymap sees a
5//! stroke.
6
7use super::tools::drag_catcher;
8use crate::player::text_field::FieldKey;
9use crate::ui::kit::{self, NumberEdit};
10use crate::ui::widgets::{slider_key, slider_typing};
11use crate::*;
12use std::cell::RefCell;
13
14/// The numbers this module edits.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub(crate) enum NumTarget {
17 Freq,
18 Gain,
19 Width,
20}
21
22impl NumTarget {
23 fn range(self) -> (f64, f64) {
24 match self {
25 Self::Freq => (f64::from(EQ_FREQ_LOW), f64::from(EQ_FREQ_HIGH)),
26 Self::Gain => (-f64::from(EQ_GAIN_LIMIT), f64::from(EQ_GAIN_LIMIT)),
27 Self::Width => (f64::from(EQ_Q_LOW), f64::from(EQ_Q_HIGH)),
28 }
29 }
30
31 fn per_px(self) -> f64 {
32 match self {
33 Self::Gain => 0.1,
34 Self::Width => 0.01,
35 // Unused: a frequency scrubs by ratio ([`scrub`]).
36 Self::Freq => 0.,
37 }
38 }
39
40 /// The number as the field shows and the buffer opens on it.
41 pub(crate) fn shown(self, v: f64) -> String {
42 match self {
43 Self::Freq if v.round() < 1000. => format!("{v:.0}"),
44 // kHz from 1 kHz up, always one decimal: "1.0", "12.5".
45 Self::Freq => format!("{:.1}", v / 1000.),
46 // A real minus sign, the same one the axis labels carry.
47 Self::Gain => format!("{v:+.1}").replace('-', "\u{2212}"),
48 Self::Width => format!("{v:.2}"),
49 }
50 }
51
52 /// The unit the field wears beside [`Self::shown`]: a frequency reads in kHz from 1 kHz up.
53 pub(crate) fn unit(self, v: f64) -> &'static str {
54 match self {
55 Self::Freq if v.round() >= 1000. => "kHz",
56 Self::Freq => "Hz",
57 Self::Gain => "dB",
58 Self::Width => "Q",
59 }
60 }
61
62 /// What the buffer opens on: a frequency as whole Hz (a bare number types as Hz).
63 fn typed(self, v: f64) -> String {
64 match self {
65 Self::Freq => format!("{v:.0}"),
66 _ => self.shown(v).replace('\u{2212}', "-"),
67 }
68 }
69
70 /// The value a drag of `dx` pixels from `v0` lands on: a frequency moves by octaves (an
71 /// octave per 50 px, a tenth of that fine), the rest by a fixed amount a pixel.
72 pub(crate) fn scrub(self, v0: f64, dx: f32, fine: bool) -> f64 {
73 let (lo, hi) = self.range();
74 match self {
75 Self::Freq => {
76 let per = if fine { 0.002 } else { 0.02 };
77 (v0 * (f64::from(dx) * per).exp2()).clamp(lo, hi)
78 }
79 _ => kit::scrub_value(v0, dx, self.per_px(), fine, lo, hi),
80 }
81 }
82
83 fn get(self, p: &Player) -> f64 {
84 let band = p.eq_params.bands.get(p.eq_band);
85 match self {
86 Self::Freq => band.map_or(1000., |b| f64::from(b.freq_hz)),
87 Self::Gain => band.map_or(0., |b| f64::from(b.gain_db)),
88 Self::Width => band.map_or(1., |b| f64::from(b.q)),
89 }
90 }
91
92 fn set(self, p: &mut Player, v: f64) -> bool {
93 match self {
94 Self::Freq => p.set_band(|b| b.freq_hz = v as f32),
95 Self::Gain => p.set_band(|b| b.gain_db = v as f32),
96 Self::Width => p.set_band(|b| b.q = v as f32),
97 }
98 }
99}
100
101#[derive(Clone, Copy)]
102struct Drag {
103 target: NumTarget,
104 x0: f32,
105 v0: f64,
106 moved: bool,
107}
108
109#[derive(Default)]
110struct State {
111 drag: Option<Drag>,
112 edit: Option<(NumTarget, NumberEdit)>,
113}
114
115thread_local! {
116 static STATE: RefCell<State> = RefCell::new(State::default());
117}
118
119/// Whether a number is being typed: the keyboard is the field's until Enter or Escape. A slider's
120/// value typed in on a card counts too, since the key handler asks here for both.
121pub(crate) fn typing() -> bool {
122 STATE.with(|s| s.borrow().edit.is_some()) || slider_typing()
123}
124
125/// Drops any press or edit (the card closed under it).
126pub(crate) fn cancel() {
127 STATE.with(|s| *s.borrow_mut() = State::default());
128}
129
130/// A number field for `target` showing `value`; a press scrubs on drag and types on click.
131pub(crate) fn field(
132 id: &'static str,
133 label: &'static str,
134 target: NumTarget,
135 value: f64,
136 cx: &mut Context<Player>,
137) -> Stateful<Div> {
138 let editing = STATE.with(|s| s.borrow().edit.clone().filter(|(t, _)| *t == target).map(|(_, e)| e));
139 let unit = if editing.is_some() && target == NumTarget::Freq { "Hz" } else { target.unit(value) };
140 kit::number_field(id, 96., target.shown(value), Some(unit), editing.as_ref(), true)
141 .tooltip(crate::ui::widgets::overlay_tip_hover(label, "", Some("Drag to change, click to type")))
142 .on_mouse_down(
143 MouseButton::Left,
144 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
145 cx.stop_propagation();
146 let v0 = target.get(this);
147 STATE.with(|s| {
148 s.borrow_mut().drag = Some(Drag { target, x0: f32::from(event.position.x), v0, moved: false })
149 });
150 cx.notify();
151 }),
152 )
153}
154
155/// The window-wide catcher that carries a press on one of the fields through its drag.
156pub(crate) fn catcher(cx: &mut Context<Player>) -> impl IntoElement {
157 let live = STATE.with(|s| s.borrow().drag.is_some());
158 drag_catcher(cx.entity(), live, move_to, release)
159}
160
161fn move_to(this: &mut Player, x: f32, fine: bool, cx: &mut Context<Player>) {
162 let Some(d) = STATE.with(|s| s.borrow().drag) else {
163 return;
164 };
165 let dx = x - d.x0;
166 if !d.moved && dx.abs() < 3. {
167 return;
168 }
169 STATE.with(|s| s.borrow_mut().drag = Some(Drag { moved: true, ..d }));
170 if d.target.set(this, d.target.scrub(d.v0, dx, fine)) {
171 cx.notify();
172 }
173}
174
175fn release(this: &mut Player, cx: &mut Context<Player>) {
176 let Some(d) = STATE.with(|s| s.borrow_mut().drag.take()) else {
177 return;
178 };
179 if d.moved {
180 this.commit_eq(cx);
181 } else {
182 let shown = d.target.typed(d.target.get(this));
183 STATE.with(|s| s.borrow_mut().edit = Some((d.target, NumberEdit::begin(&shown))));
184 }
185 cx.notify();
186}
187
188/// One key while a number is typed: Enter writes it, Escape drops it.
189pub(crate) fn key(this: &mut Player, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Player>) {
190 if slider_typing() {
191 slider_key(key, ctrl, alt, key_char, cx);
192 cx.notify();
193 return;
194 }
195 let Some((target, mut edit)) = STATE.with(|s| s.borrow().edit.clone()) else {
196 return;
197 };
198 if this.eq_open.is_none() {
199 cancel();
200 return;
201 }
202 // The buffer takes digits only, so a "k" reads the number so far as kHz and writes it out in Hz.
203 if target == NumTarget::Freq && !ctrl && !alt && key_char.is_some_and(|c| c.eq_ignore_ascii_case("k")) {
204 if let Some(hz) = parse_freq(&format!("{}k", edit.text())) {
205 edit = NumberEdit::begin(&format!("{hz:.0}"));
206 }
207 STATE.with(|s| s.borrow_mut().edit = Some((target, edit)));
208 cx.notify();
209 return;
210 }
211 let done = edit.key(key, ctrl, alt, key_char);
212 if done == FieldKey::Commit {
213 let (lo, hi) = target.range();
214 let typed = if target == NumTarget::Freq { parse_freq(edit.text()).map(|v| v.clamp(lo, hi)) } else { edit.commit(lo, hi) };
215 if let Some(v) = typed {
216 target.set(this, v);
217 this.commit_eq(cx);
218 }
219 }
220 STATE.with(|s| {
221 s.borrow_mut().edit = match done {
222 FieldKey::Edited => Some((target, edit)),
223 FieldKey::Commit | FieldKey::Cancel => None,
224 }
225 });
226 cx.notify();
227}
228
229/// A typed frequency in Hz: "80", "11100", "11.1k", "11.1 kHz" (a bare number is Hz).
230fn parse_freq(text: &str) -> Option<f64> {
231 let t = text.trim().to_lowercase().replace(',', ".");
232 let t = t.strip_suffix("hz").unwrap_or(&t).trim();
233 let (num, mult) = t.strip_suffix('k').map_or((t, 1.), |n| (n.trim(), 1000.));
234 let v: f64 = num.parse().ok()?;
235 (v.is_finite() && v > 0.).then_some(v * mult)
236}