forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

widgets.rs1719 lines, 67.2 KiBHistoryRawDownload
1//! The small elements every region is built out of.
2
3use crate::player::text_field::FieldKey;
4use crate::ui::icons::{Icon, IconSize};
5use crate::ui::theme;
6use crate::ui::type_scale::{self, Typeset};
7use crate::*;
8use std::cell::{Cell, RefCell};
9use std::collections::BTreeSet;
10use std::path::{Path, PathBuf};
11use std::rc::Rc;
12
13/// How tall the "more below" fade is at the foot of a scrolled body.
14const MORE_BELOW_H: f32 = 32.;
15
16/// The soft fade (no words) over the foot of a scrolled body while more of it is below --
17/// the export sheet's (the third row of preset tiles cut mid-text read as
18/// the end of the list) and the Settings rows' (a short window cut them off
19/// mid-row). The body tracks `scroll`; this sits after it in a `relative`
20/// parent, over its last [`MORE_BELOW_H`] pixels. Painted, not laid out: the scroll handle's extent is only known
21/// after the body's own layout, and a canvas painted after it reads that
22/// frame's numbers rather than the last one's. No hitbox, so the tiles
23/// under it stay pressable.
24pub(crate) fn more_below(scroll: ScrollHandle) -> impl IntoElement {
25 canvas(
26 |_, _, _| (),
27 move |bounds, _, window, _| {
28 if !more_below_shows(f32::from(scroll.offset().y), f32::from(scroll.max_offset().height)) {
29 return;
30 }
31 let panel = rgb(DARK_PANEL());
32 let clear = gpui::Rgba { a: 0., ..panel };
33 window.paint_quad(gpui::fill(
34 bounds,
35 gpui::linear_gradient(
36 180.,
37 gpui::linear_color_stop(clear, 0.),
38 gpui::linear_color_stop(panel, 0.7),
39 ),
40 ));
41 },
42 )
43 .absolute()
44 .left_0()
45 .right_0()
46 .bottom_0()
47 .h(px(MORE_BELOW_H))
48}
49
50/// `ClickEvent::modifiers()` answers the mouse-*up* modifiers (gpui-0.2.2
51/// `interactive.rs`), so releasing ctrl before the button lands undoes a
52/// ctrl-held toggle decided on mouse-down. This reads the *press* modifiers
53/// instead -- the ones a ctrl-click decision (multi-pick, no collapse) was
54/// actually made under.
55pub(crate) fn press_modifiers(event: &ClickEvent) -> gpui::Modifiers {
56 match event {
57 ClickEvent::Mouse(m) => m.down.modifiers,
58 ClickEvent::Keyboard(_) => gpui::Modifiers::default(),
59 }
60}
61
62/// As [`waveform`], but in a caller-picked ink rather than the fixed
63/// secondary foreground -- the darkroom bench's own audio clips draw their
64/// envelope in the source's ink (DESIGN §5), which the legacy timeline never
65/// needed a colour for.
66pub(crate) fn waveform_ink(
67 peaks: Arc<Vec<(f32, f32)>>,
68 from: f64,
69 to: f64,
70 ink: u32,
71) -> impl IntoElement {
72 canvas(
73 |_, _, _| (),
74 move |bounds, _, window, _| {
75 let (o, s) = (bounds.origin, bounds.size);
76 let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height));
77 if cols.len() < 2 {
78 return;
79 }
80 // Down the tops and back along the bottoms: one closed outline of
81 // the whole envelope, which is one path rather than a path a column.
82 let mut points: Vec<Point<Pixels>> = cols
83 .iter()
84 .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top)))
85 .collect();
86 points.extend(
87 cols.iter()
88 .rev()
89 .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))),
90 );
91 let mut path = PathBuilder::fill();
92 path.add_polygon(&points, true);
93 if let Ok(path) = path.build() {
94 window.paint_path(path, rgb(ink));
95 }
96 },
97 )
98 .size_full()
99}
100
101/// An audio clip's fade, drawn as a translucent wedge over its box: silent
102/// (full shade) at the clip's own edge, clear by the fade's far side --
103/// [`is_in`] mirrors it for the tail's ramp-down. The same `canvas` +
104/// `PathBuilder` idiom [`waveform`] draws its envelope with, filled with the
105/// same wash the in/out range already paints the bed with
106/// (`ACCENT_WASH`, timeline.rs), so a fade reads as one more overlay on this
107/// bed rather than a shape borrowed from somewhere else.
108pub(crate) fn fade_wedge(is_in: bool) -> impl IntoElement {
109 canvas(
110 |_, _, _| (),
111 move |bounds, _, window, _| {
112 let (o, s) = (bounds.origin, bounds.size);
113 let (w, h) = (f32::from(s.width), f32::from(s.height));
114 if w <= 0. || h <= 0. {
115 return;
116 }
117 // A right triangle: the clip's silent corner (top of the clip's
118 // own edge) down to the bed and across to the fade's far side --
119 // the wedge shape every editor draws for a ramp.
120 let points = match is_in {
121 true => vec![
122 point(o.x, o.y),
123 point(o.x, o.y + px(h)),
124 point(o.x + px(w), o.y + px(h)),
125 ],
126 false => vec![
127 point(o.x + px(w), o.y),
128 point(o.x + px(w), o.y + px(h)),
129 point(o.x, o.y + px(h)),
130 ],
131 };
132 let mut path = PathBuilder::fill();
133 path.add_polygon(&points, true);
134 if let Ok(path) = path.build() {
135 window.paint_path(path, rgba(crate::ui::theme::with_alpha(0x000000, 0x33)));
136 }
137 },
138 )
139 .size_full()
140}
141
142/// A video clip's dissolve into its neighbour, drawn as a small X astride the
143/// join -- the box it is given is the last [`Clip::transition_out`] frames of
144/// the clip's own width, so the mark sits right at the edge it dissolves
145/// through. Two strokes rather than [`fade_wedge`]'s fill: a dissolve is not
146/// a ramp to or from silence, it is two clips overlapping, and an X reads as
147/// a splice the way a wedge reads as a fade.
148pub(crate) fn dissolve_glyph() -> impl IntoElement {
149 canvas(
150 |_, _, _| (),
151 move |bounds, _, window, _| {
152 let (o, s) = (bounds.origin, bounds.size);
153 let (w, h) = (f32::from(s.width), f32::from(s.height));
154 if w <= 0. || h <= 0. {
155 return;
156 }
157 let mut path = PathBuilder::stroke(px(1.5));
158 path.move_to(point(o.x, o.y));
159 path.line_to(point(o.x + px(w), o.y + px(h)));
160 path.move_to(point(o.x + px(w), o.y));
161 path.line_to(point(o.x, o.y + px(h)));
162 if let Ok(path) = path.build() {
163 window.paint_path(path, rgba(crate::ui::theme::with_alpha(0xffffff, 0xd9)));
164 }
165 },
166 )
167 .size_full()
168}
169
170/// The hover line every control in the room wears (the user, 2026-09-09:
171/// "each and every button gets hover over information" -- nobody could name
172/// the band's own glyphs). One shape, built from the same pair the hitmap
173/// already names the control by: `<name> · <chord>`, DESIGN §4's "every
174/// command wears its chord" and §8's no-prose rule -- never a sentence. A
175/// control the current state refuses says *why* in the chord's place: naming
176/// a stroke that will not fire is the lie §4 forbids.
177///
178/// The one-line form, kept for the test that pins it. The plates draw
179/// [`TipParts`] instead (DESIGN §4.5: the key sits beside the name, not after a
180/// dot, and a reason takes a line of its own).
181#[cfg_attr(not(test), allow(dead_code))]
182pub(crate) fn tip_line(name: &str, chord: &str, why: Option<&str>) -> SharedString {
183 match why {
184 Some(why) => format!("{name} · {why}"),
185 // `Keymap::chord`'s own "unbound" badge: a glyph with no stroke says
186 // its name and stops, rather than wearing `--` as if that were one.
187 None if chord.is_empty() || chord == "--" => name.to_string(),
188 None => format!("{name} · {chord}"),
189 }
190 .into()
191}
192
193/// What a hover plate says, in DESIGN §4.5's order: the name, the key beside
194/// it (mono, ink3, from `Keymap::display` for an action), and -- when the
195/// state refuses the control -- the reason on a line of its own in ink2.
196#[derive(Clone, Debug, PartialEq, Eq)]
197pub(crate) struct TipParts {
198 pub(crate) name: SharedString,
199 pub(crate) key: Option<SharedString>,
200 pub(crate) why: Option<SharedString>,
201}
202
203impl TipParts {
204 /// `""` and `"--"` are no key at all (`Keymap::chord`'s unbound badge). A
205 /// key that is words rather than a chord -- a mouse gesture such as "drag"
206 /// or "double-click", or any phrase -- is not a key: it is body text, under
207 /// the name, in the same ink as a reason. A keycap is one token ("Esc",
208 /// "Ctrl+K", "r").
209 pub(crate) fn new(name: &str, key: &str, why: Option<&str>) -> Self {
210 let (key, prose) = match key {
211 "" | "--" => (None, None),
212 key if is_keycap(key) => (Some(key.to_string().into()), None),
213 prose => (None, Some(prose)),
214 };
215 let why = match (prose, why) {
216 (Some(prose), Some(why)) => Some(format!("{prose}. {why}")),
217 (Some(prose), None) => Some(prose.to_string()),
218 (None, why) => why.map(str::to_string),
219 };
220 Self {
221 name: name.to_string().into(),
222 key,
223 why: why.map(|why| why.into()),
224 }
225 }
226}
227
228impl TipParts {
229 /// A keymap's own reading of an action's key (`↑ or ,`, `Ctrl+K`): always a keycap, never
230 /// reclassified as a phrase the way [`TipParts::new`] reads free text.
231 pub(crate) fn chord(name: &str, key: &str, why: Option<&str>) -> Self {
232 let mut parts = Self::new(name, "", why);
233 parts.key = match key {
234 "" | "--" => None,
235 key => Some(key.to_string().into()),
236 };
237 parts
238 }
239}
240
241/// Whether a tooltip's key text is a keycap (`Esc`, `Ctrl+K`, `↓ or .`). A key that
242/// names a mouse gesture or reads as a phrase ("drag", "click to type", "Video, audio or
243/// images") is a sentence the plate says as plain body text instead.
244fn is_keycap(key: &str) -> bool {
245 const PHRASE_WORDS: [&str; 6] = ["drag", "click", "double-click", "right-click", "type", "to"];
246 let lower = key.to_ascii_lowercase();
247 !key.contains(',') && !lower.split_whitespace().any(|word| PHRASE_WORDS.contains(&word))
248}
249
250/// The parts of an action's plate, read off the keymap and the enable answer
251/// the caller already holds -- so the key is whatever the keymap says now, and
252/// a refusal's reason is the oracle's own. Pulled out of [`action_hover`] so a
253/// test can check it without a window.
254pub(crate) fn action_parts(keymap: &Keymap, action: ActionId, enabled: Enable) -> TipParts {
255 TipParts::chord(action.label(), &keymap.display(action), enabled.why())
256}
257
258/// [`TipParts`] in the shape gpui's `.tooltip` takes. Every shared control
259/// constructor attaches this rather than building its own plate, which is
260/// what keeps the next control from shipping without a hover line.
261pub(crate) fn tip_hover(
262 name: &str,
263 key: &str,
264 why: Option<&str>,
265) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
266 let parts = TipParts::new(name, key, why);
267 move |_, cx| {
268 cx.new(|_| KeyTip {
269 parts: parts.clone(),
270 on_overlay: false,
271 })
272 .into()
273 }
274}
275
276/// [`tip_hover`] for a control drawn *on* a card or a menu, where an
277/// ordinary [`KeyTip`] stands aside (`OVERLAID`) and would show nothing.
278pub(crate) fn overlay_tip_hover(
279 name: &str,
280 key: &str,
281 why: Option<&str>,
282) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
283 let parts = TipParts::new(name, key, why);
284 move |_, cx| {
285 cx.new(|_| KeyTip {
286 parts: parts.clone(),
287 on_overlay: true,
288 })
289 .into()
290 }
291}
292
293/// [`tip_hover`] for a control that dispatches an action: the name and the
294/// key are read live off the keymap and the enable state, so a rebind or a
295/// refusal can never leave a stale plate under the pointer.
296pub(crate) fn action_hover(
297 player: &Player,
298 action: ActionId,
299) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
300 let parts = action_parts(&player.keymap, action, player.enable(action, None));
301 move |_, cx| {
302 cx.new(|_| KeyTip {
303 parts: parts.clone(),
304 on_overlay: false,
305 })
306 .into()
307 }
308}
309
310/// The keyboard focus ring (DESIGN §4.1): 2px of accent drawn *outside* the
311/// control as a zero-blur shadow, so a focused control never moves its
312/// neighbours. Applied through [`focus_ring`] on every control that can hold
313/// gpui focus; the ring shows exactly while its handle is focused.
314pub(crate) const FOCUS_RING_PX: f32 = 2.;
315
316/// The ring as a style: what `.focus(..)` paints.
317pub(crate) fn focus_ring_shadow() -> Vec<gpui::BoxShadow> {
318 vec![gpui::BoxShadow {
319 color: rgb(crate::ui::theme::tokens().accent).into(),
320 offset: point(px(0.), px(0.)),
321 blur_radius: px(0.),
322 spread_radius: px(FOCUS_RING_PX),
323 }]
324}
325
326/// Gives a control the focus ring. One door so toolbar, menu bar and widgets
327/// cannot drift apart on what a focused control looks like.
328pub(crate) fn focus_ring<E: InteractiveElement + Styled>(el: E) -> E {
329 el.focus(|s| s.shadow(focus_ring_shadow()))
330}
331
332/// A toolbar button: its glyph, its name, and its key on hover. `id` only buys
333/// `on_click` and the tooltip -- it is still not focusable, so the root's own
334/// key listener keeps working after a press, and the click lands on mouse-up
335/// inside the button (a press that slides off does nothing).
336///
337/// A button that would do nothing says so: dimmed, no pointer, no listener.
338#[allow(
339 clippy::too_many_arguments,
340 reason = "every button in the window takes this same set; a params struct would be built at all 20+ call sites for no gain"
341)]
342pub(crate) fn control(
343 id: &'static str,
344 // The rect the label is allowed to change inside: 0 hugs the text, anything
345 // else is reserved once and never moves again, which is what keeps a button
346 // that relabels itself ("Export"/"Cancel") from shoving its neighbours
347 // along the row every time its state changes.
348 w: f32,
349 // The plane the button stands on. One button in the window is the accent
350 // (Export, the primary action); everything else is `BG_RAISED`.
351 bg: u32,
352 glyph: Option<AnyElement>,
353 // Not `&'static str`: the volume button's label is its state.
354 label: impl Into<SharedString>,
355 shortcut: String,
356 enabled: bool,
357 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
358) -> impl IntoElement {
359 let label = label.into();
360 let tip = TipParts::new(&label, &shortcut, None);
361 focus_ring(div().id(id))
362 .flex_none()
363 .h(px(CONTROL_H))
364 .flex()
365 .items_center()
366 .justify_center()
367 .gap(px(6.))
368 .px(px(8.))
369 .when(w > 0., |d| d.w(px(w)).overflow_hidden())
370 .rounded(px(4.))
371 .bg(rgb(bg))
372 .when(bg == ACCENT_PRIMARY(), |d| d.text_color(rgb(BG_CANVAS())))
373 // A glyph sits in a box of its own width, never in the width it happens
374 // to draw: the pause bars are 12 px wide and the play triangle is 11, so
375 // pressing Play used to slide every button in the row one pixel left. A
376 // slot is the only fix that holds for the next glyph as well as this one.
377 .children(glyph.map(|glyph| {
378 div()
379 .flex_none()
380 .w(px(GLYPH_SLOT))
381 .flex()
382 .items_center()
383 .justify_center()
384 .child(glyph)
385 }))
386 .child(label)
387 .tooltip(move |_, cx| {
388 cx.new(|_| KeyTip {
389 parts: tip.clone(),
390 on_overlay: false,
391 })
392 .into()
393 })
394 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
395 .when(enabled, |d| {
396 // An accented button keeps its accent under the pointer: hovering it
397 // to the chrome's own hover colour reads as the primary action
398 // turning itself off.
399 d.cursor_pointer()
400 .hover(move |s| {
401 s.bg(rgb(match bg == ACCENT_PRIMARY() {
402 true => ACCENT_HOVER(),
403 false => BG_HOVER(),
404 }))
405 })
406 .on_click(on_click)
407 })
408}
409
410/// The monitoring level as something to drag: 4 px of bar to look at and the
411/// whole control's height to hit (WCAG 2.5.8), the split the speed bar and the
412/// colour sliders both make. Only the level -- mute is the button beside it, so
413/// a muted slider still shows what unmuting comes back to, drawn dim.
414///
415/// Whether a card or a menu is drawn over the window, as the hover labels see
416/// it: written once a frame by [`Player::render`], read by every [`Tip`] before
417/// it paints.
418///
419/// A tooltip already on screen when an overlay opens *stays* on screen in gpui:
420/// occluding the surface under it does not take it back, because the check that
421/// keeps it visible works off the element's absolute bounds and knows nothing
422/// about what was painted over it (`div.rs::handle_tooltip_mouse_move`, its own
423/// TODO). So the tip is what has to stand aside -- here, once, for every hover
424/// label in this window, rather than at fifteen call sites of which the
425/// sixteenth would be forgotten.
426pub(crate) static OVERLAID: AtomicBool = AtomicBool::new(false);
427
428/// Whether a tip is cleared to paint: an ordinary tip stands aside whenever
429/// `OVERLAID` is set (a card/menu is up over the underlying UI it belongs
430/// to), but a tip *anchored on the overlay itself* -- the `?` glyph on a
431/// card's own head, say -- was never the case `OVERLAID` meant to catch, so
432/// it paints regardless. One predicate, so [`Tip`] and [`OverlayTip`] can't
433/// drift apart on what "overlaid" is supposed to mean.
434pub(crate) fn tip_may_paint(anchored_on_overlay: bool) -> bool {
435 anchored_on_overlay || !OVERLAID.load(Ordering::Relaxed)
436}
437
438/// The name on a hover plate, and the reason beneath it (DESIGN §4.5: names
439/// are 14px, the key is the 13px mono the room gives every chord).
440const TIP_NAME_PX: f32 = 13.;
441/// The widest a plate grows before its text wraps (DESIGN §4.5).
442const TIP_MAX_W: f32 = 300.;
443/// gpui puts a tooltip's box one pixel below-right of the pointer, so a plate
444/// there covers the lower half of the control it describes. The box is padded
445/// by these clear margins (transparent), which pushes the visible plate off the
446/// control: down and to the right of where the pointer is.
447const TIP_CLEAR_Y: f32 = 26.;
448const TIP_CLEAR_X: f32 = 10.;
449
450/// The plate's definite width for these lines: wide enough for the longest on
451/// one line, never past [`TIP_MAX_W`], so the text wraps inside it. A definite
452/// width is what keeps gpui's measuring pass and its paint pass agreeing on
453/// the height; with a max width alone the text overflowed its own box and ran
454/// off the window's edge.
455fn tip_w(lines: &[&str]) -> f32 {
456 let widest = lines
457 .iter()
458 .map(|l| crate::ui::popup::text_w(l, TIP_NAME_PX, false))
459 .fold(0f32, f32::max);
460 (widest + 22.).clamp(60., TIP_MAX_W)
461}
462
463/// `text` broken into lines no wider than `max` px (by [`popup::text_w`]'s
464/// upper bound). Broken here, by hand, because gpui's own wrapping did not take
465/// the plate's width inside a tooltip (the text ran on past the plate's edge).
466fn tip_lines(text: &str, max: f32) -> Vec<String> {
467 let mut lines: Vec<String> = Vec::new();
468 for word in text.split_whitespace() {
469 match lines.last_mut() {
470 Some(last)
471 if crate::ui::popup::text_w(&format!("{last} {word}"), TIP_NAME_PX, false)
472 <= max =>
473 {
474 last.push(' ');
475 last.push_str(word);
476 }
477 _ => lines.push(word.to_string()),
478 }
479 }
480 lines
481}
482
483/// Where gpui hangs a tooltip box of `size` for a pointer at `mouse`: one pixel
484/// below-right, flipped to the left of / above the pointer where that would
485/// leave the window, then pinned inside. gpui's own rule (window.rs
486/// `prepaint_tooltip`), kept here so a test can hold it to "always inside".
487#[cfg(test)]
488pub(crate) fn tip_origin(mouse: (f32, f32), size: (f32, f32), window: (f32, f32)) -> (f32, f32) {
489 let mut x = mouse.0 + 1.;
490 let mut y = mouse.1 + 1.;
491 if x + size.0 > window.0 {
492 x = mouse.0 - size.0 - 1.;
493 }
494 if y + size.1 > window.1 {
495 y = mouse.1 - size.1 - 1.;
496 }
497 (x.max(0.), y.max(0.))
498}
499
500/// The dock's width, set every frame (`render.rs`): what a media row fits its meta lines to.
501pub(crate) static DOCK_W_BITS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
502
503/// The window y where the time band (transport, toolbar, ruler, lanes) begins, set every frame
504/// (`render.rs`); `0` while unknown.
505pub(crate) static TIMELINE_TOP_BITS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
506
507/// The depth of the timeline's own chrome band (toolbar, sequence tabs, overview, ruler) in
508/// which a plate is lifted above the region. Deeper (the lanes) a plate stays by the pointer:
509/// a tooltip is always next to the control it names, never a long way off.
510pub(crate) const TIP_LIFT_BAND: f32 = 100.;
511
512/// How far above a pointer at `mouse_y` a plate's bottom edge sits when the pointer is in the
513/// timeline's chrome band (`top` to `top + TIP_LIFT_BAND`): the plate hangs just above the region,
514/// `TIP_CLEAR_Y / 2` clear, so it never covers the ruler or the toolbar. `None` elsewhere,
515/// where the ordinary below-right place applies.
516pub(crate) fn tip_lift(mouse_y: f32, top: f32) -> Option<f32> {
517 (top > 0. && mouse_y >= top && mouse_y < top + TIP_LIFT_BAND).then(|| mouse_y + 1. - top + TIP_CLEAR_Y / 2.)
518}
519
520/// The plate inside its transparent clear margin ([`TIP_CLEAR_Y`]), below-right of the pointer
521/// (gpui flips it at the window's edge); with the pointer in the timeline's chrome band, above
522/// that region ([`tip_lift`]). The one placement rule for every tooltip.
523fn tip_boxed(plate: Div, w: f32, window: Option<&Window>) -> Div {
524 let top = f32::from_bits(TIMELINE_TOP_BITS.load(Ordering::Relaxed));
525 let lift = window.and_then(|window| {
526 let (mx, my) = (f32::from(window.mouse_position().x), f32::from(window.mouse_position().y));
527 tip_lift(my, top).map(|l| (l, mx + 1. + w - f32::from(window.viewport_size().width)))
528 });
529 match lift {
530 // A root of no size, so gpui's own flip at the window's edge has nothing
531 // to flip; the plate hangs off it, absolute.
532 Some((lift, over)) => div().w(px(0.)).h(px(0.)).child(plate.absolute().left(px(-over.max(0.))).bottom(px(lift))),
533 None => div().pt(px(TIP_CLEAR_Y)).pl(px(TIP_CLEAR_X)).child(plate),
534 }
535}
536
537/// One line of a hover plate: the keycap's height, so a label and its chips share a line box
538/// and the text centres on the chips.
539const TIP_LINE_PX: f32 = 18.;
540
541/// DESIGN §2.5 and §4.5: a tooltip is a floating plate, so it is a panel with a
542/// hairline, a 6px radius and the one shadow the room uses for floating plates
543/// (menus, the palette, sheets, toasts). Padded 10px on every side.
544fn tip_plate() -> Div {
545 crate::ui::kit::plate(6.)
546 .flex()
547 .flex_none()
548 .flex_col()
549 .gap(px(4.))
550 .p(px(10.))
551}
552
553/// A plain prose tooltip ([`Tip`], [`OverlayTip`]): one line in ink1 on the
554/// same plate, so a sentence-shaped hover still wears the room's one plate.
555fn tip_text(text: &SharedString, window: Option<&Window>) -> Div {
556 let name = crate::ui::type_scale::label(TIP_NAME_PX, gpui::FontWeight::MEDIUM);
557 let lines = tip_lines(text, TIP_MAX_W - 22.);
558 let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
559 let w = tip_w(&refs);
560 tip_boxed(
561 tip_plate()
562 .w(px(w))
563 .font(name.font)
564 .text_size(name.size)
565 .text_color(rgb(INK1()))
566 .children(lines.into_iter().map(|l| div().h(px(TIP_LINE_PX)).line_height(px(TIP_LINE_PX)).whitespace_nowrap().child(l))),
567 w,
568 window,
569 )
570}
571
572/// One tooltip's text: the name in ink1, the key beside it in mono ink3, and
573/// the reason (when the state refuses) on the line below in ink2.
574fn tip_card(parts: &TipParts, window: Option<&Window>) -> Div {
575 let name = crate::ui::type_scale::label(TIP_NAME_PX, gpui::FontWeight::MEDIUM);
576 // The name wraps by hand like every tip line ([`tip_lines`]); the key sits
577 // beside its last line.
578 let mut name_lines = tip_lines(&parts.name, TIP_MAX_W - 22.);
579 let last = name_lines.pop().unwrap_or_default();
580 let ink = |l: String, c: u32| {
581 div()
582 .h(px(TIP_LINE_PX))
583 .line_height(px(TIP_LINE_PX))
584 .flex()
585 .items_center()
586 .whitespace_nowrap()
587 .font(name.font.clone())
588 .text_size(name.size)
589 .text_color(rgb(c))
590 .child(l)
591 };
592 let row = div()
593 .flex()
594 .flex_col()
595 .children(name_lines.iter().cloned().map(|l| ink(l, INK1())))
596 .child(
597 div()
598 .h(px(TIP_LINE_PX))
599 .flex()
600 .flex_row()
601 .items_center()
602 .gap(px(8.))
603 .child(ink(last.clone(), INK1()))
604 .when_some(parts.key.clone(), |row, text| {
605 row.child(crate::ui::kit::keycaps(&text).whitespace_nowrap())
606 }),
607 );
608 let why_lines = parts
609 .why
610 .as_ref()
611 .map(|w| tip_lines(w, TIP_MAX_W - 22.))
612 .unwrap_or_default();
613 let head_w = crate::ui::popup::text_w(&last, TIP_NAME_PX, false)
614 + parts.key.as_ref().map_or(0., |k| crate::ui::kit::keycaps_w(k.as_ref()) + 8.)
615 + 22.;
616 let w = tip_w(
617 &name_lines
618 .iter()
619 .map(String::as_str)
620 .chain(why_lines.iter().map(String::as_str))
621 .collect::<Vec<_>>(),
622 )
623 .max(head_w.min(TIP_MAX_W + 40.));
624 tip_boxed(
625 tip_plate()
626 .w(px(w))
627 .child(row)
628 .children(
629 why_lines
630 .iter()
631 .map(|l| {
632 let l = l.clone();
633 div()
634 .h(px(TIP_LINE_PX))
635 .line_height(px(TIP_LINE_PX))
636 .flex()
637 .items_center()
638 .whitespace_nowrap()
639 .font(name.font.clone())
640 .text_size(name.size)
641 .text_color(rgb(INK2()))
642 .child(l)
643 }),
644 ),
645 w,
646 window,
647 )
648}
649
650/// A tooltip's entity, where the pointer was when it first painted, and whether it is dead.
651type TipBorn = (gpui::EntityId, (f32, f32), bool);
652
653thread_local! {
654 /// The pointer position of the last press (set once a frame by [`Player::render`]'s listener).
655 static CLICK_AT: Cell<Option<(f32, f32)>> = const { Cell::new(None) };
656 /// The tooltip last painted: its entity, where the pointer was when it first painted (which is
657 /// where gpui shows it), and whether it is already dead.
658 static TIP_BORN: Cell<Option<TipBorn>> = const { Cell::new(None) };
659}
660
661/// Notes a press at `at`: a tooltip that has not shown yet must not show for it afterwards.
662pub(crate) fn note_press(at: gpui::Point<Pixels>) {
663 CLICK_AT.with(|c| c.set(Some((f32::from(at.x), f32::from(at.y)))));
664}
665
666/// How far the pointer may drift from where a tooltip appeared before it is gone.
667const TIP_DRIFT: f32 = 12.;
668
669/// Whether the tooltip view `id` must paint nothing: the pointer has left the spot it was
670/// shown for (a stale plate, whatever kept gpui from hiding it), or it was born right under a
671/// press (a tip whose delay ran out after the click). gpui's own rule hides a *shown* tip on a
672/// press but lets a *waiting* one show afterwards; this is the one place that closes both.
673fn tip_gone(id: gpui::EntityId, window: &Window) -> bool {
674 let m = (f32::from(window.mouse_position().x), f32::from(window.mouse_position().y));
675 let (born, dead) = match TIP_BORN.with(Cell::get) {
676 Some((i, p, dead)) if i == id => (p, dead),
677 _ => {
678 let dead = CLICK_AT.with(Cell::get).is_some_and(|c| (c.0 - m.0).abs() < 1. && (c.1 - m.1).abs() < 1.);
679 (m, dead)
680 }
681 };
682 let dead = dead || (born.0 - m.0).abs() > TIP_DRIFT || (born.1 - m.1).abs() > TIP_DRIFT;
683 TIP_BORN.with(|c| c.set(Some((id, born, dead))));
684 dead
685}
686
687/// A tooltip is a view in gpui and nothing smaller, so this is the smallest one
688/// that carries a line of text. It paints outside the window's element tree and
689/// therefore owns its colours.
690pub(crate) struct Tip(pub(crate) SharedString);
691
692impl Render for Tip {
693 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
694 // A card or a menu is up: nothing. A line of text over the items of the
695 // menu that just opened under the pointer is the card being painted
696 // over by the window it covers. (This struct is every tooltip on the
697 // *underlying* UI -- grepped: `timeline.rs`, `library.rs`,
698 // `overlays.rs`, `spine_stance.rs`, `dock_stance.rs`,
699 // `timeband_stance.rs`, `preview.rs`, here -- so the fix belongs here
700 // once, not per call site.)
701 if !tip_may_paint(false) || (!cx.has_active_drag() && tip_gone(cx.entity_id(), window)) {
702 return div();
703 }
704 // A drag ghost follows the pointer; only a hover plate keeps off the dock.
705 tip_text(&self.0, (!cx.has_active_drag()).then_some(&*window))
706 }
707}
708
709/// Whether any `(start, len)` span holds `frame`.
710#[cfg_attr(not(test), allow(dead_code))]
711pub(crate) fn spans_cover(spans: impl IntoIterator<Item = (u32, u32)>, frame: u32) -> bool {
712 spans.into_iter().any(|(start, len)| frame >= start && frame < start + len)
713}
714
715/// A tip anchored on the overlay itself -- a card's own `?` glyph, drawn on
716/// its own card head. `OVERLAID` exists to hide a [`Tip`] on the UI *under*
717/// a card while the card sits over it; a tip painted on the card is not
718/// that case, so it is exempt (`tip_may_paint(true)` is always `true`).
719/// Everything else about it is [`Tip`]'s own plate.
720pub(crate) struct OverlayTip(pub(crate) SharedString);
721
722impl Render for OverlayTip {
723 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
724 if tip_gone(cx.entity_id(), window) {
725 return div();
726 }
727 tip_text(&self.0, Some(window))
728 }
729}
730
731/// The hover plate every shared control and action wears (DESIGN §4.5): the
732/// name, its key and, when refused, its reason. [`Tip`]'s rule applies: it
733/// stands aside while a card is over the UI it belongs to, unless it is
734/// anchored on the overlay (`on_overlay`, see [`tip_may_paint`]).
735pub(crate) struct KeyTip {
736 pub(crate) parts: TipParts,
737 pub(crate) on_overlay: bool,
738}
739
740impl Render for KeyTip {
741 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
742 if !tip_may_paint(self.on_overlay) || tip_gone(cx.entity_id(), window) {
743 return div();
744 }
745 tip_card(&self.parts, Some(window))
746 }
747}
748
749/// How much text the colour field will hold: `rgba(255, 255, 255, 255)` with
750/// room to spare. Every legal colour is far inside it; the cap is there so a
751/// held key cannot grow the buffer without bound.
752const COLOR_EDIT_CHARS: usize = 32;
753
754/// A colour being typed into a row that has no text field of its own: the
755/// free-text sibling of the kit number field, for the same reason it exists -- these
756/// rows take no gpui focus, so the text is held as state and driven by the
757/// root's key handler. One caller, the Clip tab's colour field
758/// ([`Player::edit_viz_hex`]): typing, backspace, enter that commits and
759/// escape that gives up, and a refusal in words when what is there is not a
760/// colour.
761#[derive(Clone, Debug, PartialEq, Eq)]
762pub(crate) struct ColorEdit {
763 pub(crate) text: String,
764 pub(crate) refusal: Option<String>,
765}
766
767impl ColorEdit {
768 /// Starts on the colour the row already shows, so backspace edits it
769 /// rather than the field opening empty over a colour still in force
770 /// (the number field's own rule).
771 pub(crate) fn new(seed: &str) -> Self {
772 ColorEdit {
773 text: seed.to_string(),
774 refusal: None,
775 }
776 }
777
778 /// One printable stroke. The one past the cap is refused *out loud*: a
779 /// keystroke dropped in silence is what leaves a field showing something
780 /// the user did not type (the number field's own reason).
781 pub(crate) fn typed(&mut self, c: char) {
782 if self.text.chars().count() >= COLOR_EDIT_CHARS {
783 self.refusal = Some(format!("{COLOR_EDIT_CHARS} characters is already past the field"));
784 return;
785 }
786 self.text.push(c);
787 self.refusal = None;
788 }
789
790 /// Erases the last character, and the refusal with it: the text on screen
791 /// has changed, so the reason the old one was refused no longer describes
792 /// it.
793 pub(crate) fn backspace(&mut self) {
794 self.text.pop();
795 self.refusal = None;
796 }
797
798 /// The colour, or `None` with the reason recorded where the row will read
799 /// it. Only the shapes the paint field can carry are read at all
800 /// (`engine::decode::viz_color_from_text`); anything else is refused
801 /// rather than guessed at, and the refusal says what a colour looks like
802 /// so the next try is a backspace away.
803 pub(crate) fn commit(&mut self) -> Option<(u8, u8)> {
804 match engine::decode::viz_color_from_text(&self.text) {
805 Some(hue_sat) => {
806 self.refusal = None;
807 Some(hue_sat)
808 }
809 None => {
810 self.refusal = Some("type a colour — #RRGGBB or rgb(r,g,b)".to_string());
811 None
812 }
813 }
814 }
815
816 /// What the row shows while it is being typed into: the text, the caret
817 /// that says it is landing *here*, and either the refusal or the two keys
818 /// that end the edit.
819 pub(crate) fn detail(&self) -> String {
820 format!(
821 "{}▏ {}",
822 self.text,
823 match &self.refusal {
824 Some(why) => why.as_str(),
825 None => "enter commits · esc cancels",
826 }
827 )
828 }
829}
830
831/// How many characters a cue's words may run to in the in-place editor. Well
832/// past any caption a viewer reads in the time it is up, so the cap only stops
833/// a held key from growing the buffer without bound.
834const CUE_EDIT_CHARS: usize = 500;
835
836/// A subtitle cue being retyped in place on its block: the free-text sibling of
837/// [`ColorEdit`], for the same reason -- the block takes no gpui focus, so the
838/// text is held as state and driven by the root's key handler
839/// ([`Player::open_cue_edit`], [`Player::commit_cue_edit`]). Unlike a colour it
840/// takes any printable character, not just ASCII, because a cue is words in
841/// whatever language the file is in.
842///
843/// `lane`, `track` and `cue` name the block being edited: `track` and `cue` are
844/// the palette row and its cue ([`engine::PlaybackSession::set_cue_text`]), so
845/// every placement of that track shows what is typed here on commit.
846#[derive(Clone, Debug, PartialEq, Eq)]
847pub(crate) struct CueEdit {
848 pub(crate) lane: Lane,
849 pub(crate) track: usize,
850 pub(crate) cue: usize,
851 pub(crate) text: String,
852 /// Where the caret is drawn: at the end, where every stroke lands. Kept as a
853 /// field so the draw and the buffer agree on where the caret is.
854 pub(crate) caret_at_end: bool,
855 pub(crate) refusal: Option<String>,
856 /// Typed in the Clip tab's caption panel rather than in the floating box over the block.
857 pub(crate) in_panel: bool,
858 /// Every word is selected (Ctrl+A): the next character or line break replaces them all.
859 pub(crate) all: bool,
860}
861
862impl CueEdit {
863 /// Starts on the words the cue already has, so backspace edits them rather
864 /// than the block opening empty over words still on the screen.
865 pub(crate) fn new(lane: Lane, track: usize, cue: usize, seed: &str) -> Self {
866 CueEdit {
867 lane,
868 track,
869 cue,
870 text: seed.to_string(),
871 caret_at_end: true,
872 refusal: None,
873 in_panel: false,
874 all: false,
875 }
876 }
877
878 /// Ctrl+A: every word is selected, and the next stroke that writes replaces it.
879 pub(crate) fn select_all(&mut self) {
880 self.all = true;
881 }
882
883 /// Drops the selected words before a stroke that writes (a selection is replaced, not added to).
884 fn replace_selection(&mut self) {
885 if self.all {
886 self.text.clear();
887 self.all = false;
888 }
889 }
890
891 /// One printable character. Control characters are ignored outright (a
892 /// stray tab or a bell is not a word); the one past the cap is refused out
893 /// loud, for the reason [`ColorEdit::typed`] gives.
894 pub(crate) fn typed(&mut self, c: char) {
895 if c.is_control() {
896 return;
897 }
898 self.replace_selection();
899 self.push(c);
900 }
901
902 /// Shift+Enter: a line break inside the cue, which a multi-line cue
903 /// carries as `\n` ([`engine::subtitle::Cue::text`]).
904 pub(crate) fn newline(&mut self) {
905 self.replace_selection();
906 self.push('\n');
907 }
908
909 fn push(&mut self, c: char) {
910 if self.text.chars().count() >= CUE_EDIT_CHARS {
911 self.refusal = Some(format!(
912 "{CUE_EDIT_CHARS} characters is the most a cue holds"
913 ));
914 return;
915 }
916 self.text.push(c);
917 self.refusal = None;
918 }
919
920 /// Erases the last character, and the refusal with it, for the reason
921 /// [`ColorEdit::backspace`] gives.
922 pub(crate) fn backspace(&mut self) {
923 if self.all {
924 self.text.clear();
925 self.all = false;
926 } else {
927 self.text.pop();
928 }
929 self.refusal = None;
930 }
931
932 /// The words to write, or `None` when they are the words the cue already
933 /// has -- an edit that changed nothing takes no undo step and writes
934 /// nothing, so opening a block and leaving it with enter is no edit.
935 pub(crate) fn commit(&self, current: &str) -> Option<String> {
936 (self.text != current).then(|| self.text.clone())
937 }
938}
939
940/// Which text of a marker the markers card is retyping.
941#[derive(Clone, Copy, Debug, PartialEq, Eq)]
942pub(crate) enum MarkerField {
943 Name,
944 Note,
945}
946
947/// A marker's name or note being retyped on the markers card: the free-text sibling of
948/// [`CueEdit`], driven by the root's key handler for the same reason (the card takes no
949/// gpui focus). `idx` is the marker's place in `PlaybackSession::markers`.
950#[derive(Clone, Debug, PartialEq, Eq)]
951pub(crate) struct MarkerEdit {
952 pub(crate) idx: usize,
953 pub(crate) field: MarkerField,
954 pub(crate) text: String,
955 /// Every word is selected (Ctrl+A): the next character replaces them all.
956 pub(crate) all: bool,
957}
958
959impl MarkerEdit {
960 /// Starts on the words the field already has. A name opens fully selected, so the first
961 /// letter replaces it (a rename); a note opens with the caret at its end.
962 pub(crate) fn new(idx: usize, field: MarkerField, seed: &str) -> Self {
963 MarkerEdit { idx, field, text: seed.to_string(), all: field == MarkerField::Name }
964 }
965
966 /// One printable character; control characters are ignored, and a held key stops at
967 /// the most the field holds.
968 pub(crate) fn typed(&mut self, c: char) {
969 let cap = match self.field {
970 MarkerField::Name => engine::project::MAX_MARKER_NAME_CHARS,
971 MarkerField::Note => engine::project::MAX_MARKER_NOTE_CHARS,
972 };
973 if self.all {
974 self.text.clear();
975 self.all = false;
976 }
977 if !c.is_control() && self.text.chars().count() < cap {
978 self.text.push(c);
979 }
980 }
981
982 /// Erases the last character.
983 pub(crate) fn backspace(&mut self) {
984 if self.all {
985 self.text.clear();
986 self.all = false;
987 } else {
988 self.text.pop();
989 }
990 }
991}
992
993/// Where a value sits on its slider, 0..1: the thumb's share of the track.
994/// A value past either end pins to that end, and a range with no width (or a
995/// value that is not a number) reads as the start rather than dividing by
996/// nothing.
997#[allow(dead_code, reason = "wave 2 panels mount these")]
998pub(crate) fn slider_fraction(value: f32, lo: f32, hi: f32) -> f32 {
999 let span = hi - lo;
1000 if span.is_nan() || span <= 0. || value.is_nan() {
1001 return 0.;
1002 }
1003 ((value - lo) / span).clamp(0., 1.)
1004}
1005
1006/// A slider press: window x of the sample, the card's own write.
1007pub(crate) type SliderPress<V> = Box<dyn Fn(&mut V, Pixels, &mut Context<V>)>;
1008/// A slider reset: back to the default.
1009pub(crate) type SliderReset<V> = Rc<dyn Fn(&mut V, &mut Context<V>)>;
1010
1011/// One card slider's row (DESIGN §9.1). The card builds it and [`slider_row`]
1012/// draws it, so every panel's slider reads the same and hits the same.
1013#[allow(dead_code, reason = "wave 2 panels mount these")]
1014pub(crate) struct SliderRow<V> {
1015 pub(crate) id: &'static str,
1016 pub(crate) label: SharedString,
1017 pub(crate) value: SharedString,
1018 /// Where the value sits on its range, 0..1 ([`slider_fraction`] maps it).
1019 pub(crate) fraction: f32,
1020 /// Off the default: the value reads ink1 and a Reset button appears.
1021 pub(crate) changed: bool,
1022 /// The track's box, recorded by a [`bounds_probe`] so a press can be turned
1023 /// into a fraction with [`frac_along`].
1024 pub(crate) bar: Rc<Cell<Bounds<Pixels>>>,
1025 /// A press or drag sample at window x. The card owns its own drag flag and
1026 /// its write, the way the other card sliders already do.
1027 pub(crate) on_press: SliderPress<V>,
1028 /// Back to the default. Double-clicking the value and the Reset button both
1029 /// call it; `None` leaves neither on the row.
1030 pub(crate) on_reset: Option<SliderReset<V>>,
1031 /// Typing the value in: a click on the value opens it as a field. `None` keeps
1032 /// the value drag-only.
1033 pub(crate) typed: Option<SliderTyped<V>>,
1034}
1035
1036/// Writes a typed slider value, already clamped, in the units the value reads.
1037pub(crate) type SliderSet<V> = Rc<dyn Fn(&mut V, f64, &mut Context<V>)>;
1038/// A typed value's write once it is due: it reaches the card's entity from outside the card.
1039type TypedCommit = Rc<dyn Fn(f64, &mut App)>;
1040
1041/// A slider's typed entry: the range a typed number clamps to and the write it makes,
1042/// both in the units the value reads ("12 px" is 12, "40%" is 40).
1043pub(crate) struct SliderTyped<V> {
1044 pub(crate) lo: f64,
1045 pub(crate) hi: f64,
1046 pub(crate) set: SliderSet<V>,
1047}
1048
1049/// A slider value being typed: which row (the identity of its track), the buffer, the unit the
1050/// value wears (" px", "%"), the range and the write a commit makes.
1051struct SliderEdit {
1052 row: usize,
1053 edit: crate::ui::kit::NumberEdit,
1054 unit: SharedString,
1055 lo: f64,
1056 hi: f64,
1057 commit: TypedCommit,
1058 /// The value takes the keyboard while it is typed (its keys stop there, before a card's own
1059 /// escape sees them), and hands it back to `back`, what had it before, when typing ends.
1060 focus: FocusHandle,
1061 back: Option<FocusHandle>,
1062}
1063
1064thread_local! {
1065 static SLIDER_EDIT: RefCell<Option<SliderEdit>> = const { RefCell::new(None) };
1066}
1067
1068/// Whether a slider value is being typed: the keyboard is its until Enter or Escape.
1069pub(crate) fn slider_typing() -> bool {
1070 SLIDER_EDIT.with(|s| s.borrow().is_some())
1071}
1072
1073/// One key while a slider value is typed: Enter writes it, Escape drops it, the rest is text.
1074pub(crate) fn slider_key(key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut App) {
1075 let Some(mut e) = SLIDER_EDIT.with(|s| s.borrow_mut().take()) else {
1076 return;
1077 };
1078 match e.edit.key(key, ctrl, alt, key_char) {
1079 FieldKey::Edited => SLIDER_EDIT.with(|s| *s.borrow_mut() = Some(e)),
1080 FieldKey::Commit => write_typed(&e, cx),
1081 FieldKey::Cancel => {}
1082 }
1083 cx.refresh_windows();
1084}
1085
1086/// Writes what was typed, once the update that delivered the keystroke or press is over: the
1087/// card's own entity is still being updated when a key reaches it, so the write waits its turn.
1088fn write_typed(e: &SliderEdit, cx: &mut App) {
1089 if let Some(v) = e.edit.commit(e.lo, e.hi) {
1090 let commit = e.commit.clone();
1091 cx.defer(move |app| commit(v, app));
1092 }
1093}
1094
1095/// The typed value is written when the press lands outside the value, the way a click away
1096/// from a field keeps what was typed.
1097fn slider_leave(row: usize, cx: &mut App) {
1098 let Some(e) = SLIDER_EDIT.with(|s| s.borrow_mut().take_if(|e| e.row == row)) else {
1099 return;
1100 };
1101 write_typed(&e, cx);
1102 cx.refresh_windows();
1103}
1104
1105/// The focus a typed value gives back when it ends.
1106fn slider_back(row: usize) -> Option<FocusHandle> {
1107 SLIDER_EDIT.with(|s| s.borrow().as_ref().filter(|e| e.row == row).and_then(|e| e.back.clone()))
1108}
1109
1110/// Drops a row's typed value without writing it (a double-click resets the value instead).
1111fn slider_forget(row: usize) {
1112 SLIDER_EDIT.with(|s| {
1113 s.borrow_mut().take_if(|e| e.row == row);
1114 });
1115}
1116
1117/// Splits a shown value into the number it opens on and the unit it wears: "12 px" is ("12",
1118/// " px"), "−90°" is ("-90", "°").
1119fn split_value(shown: &str) -> (String, String) {
1120 let cut = shown.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | '\u{2212}'))).unwrap_or(shown.len());
1121 let (num, unit) = shown.split_at(cut);
1122 (num.replace('\u{2212}', "-"), unit.to_owned())
1123}
1124
1125/// The key a readout's typing is kept under: its id, hashed. Every typed readout has an id of
1126/// its own, so one row's typing never shows in another's.
1127pub(crate) fn typed_key(id: &str) -> usize {
1128 use std::hash::{DefaultHasher, Hash, Hasher};
1129 let mut h = DefaultHasher::new();
1130 id.hash(&mut h);
1131 h.finish() as usize
1132}
1133
1134/// A value's box, which a click types in: the value pill of a slider and of the rows that draw
1135/// their own track. With `typed` set, a click opens the box as a field: Enter writes it, Escape
1136/// drops it and a press outside keeps it. With `reset` set, a double-click resets the value.
1137/// `open` is the number and unit the field opens on; `None` reads them off `shown`.
1138#[allow(clippy::too_many_arguments)]
1139pub(crate) fn typed_readout<V: 'static>(
1140 id: &'static str,
1141 shown: &str,
1142 open: Option<(String, String)>,
1143 min_w: f32,
1144 ink: u32,
1145 typed: Option<SliderTyped<V>>,
1146 reset: Option<SliderReset<V>>,
1147 cx: &mut Context<V>,
1148) -> Stateful<Div> {
1149 let t = theme::tokens();
1150 let row = typed_key(id);
1151 let typing_text = SLIDER_EDIT.with(|s| {
1152 s.borrow().as_ref().filter(|e| e.row == row).map(|e| (SharedString::from(e.edit.text().to_string()), e.unit.clone()))
1153 });
1154 let (num, unit) = open.unwrap_or_else(|| split_value(shown));
1155 let unit = SharedString::from(unit);
1156 // What a click on the value opens: the number it shows, and the write a commit makes.
1157 let entry = typed.map(|typed| {
1158 let me = cx.entity();
1159 let set = typed.set;
1160 let commit: TypedCommit = Rc::new(move |v, app: &mut App| {
1161 me.update(app, |this, cx| set(this, v, cx));
1162 });
1163 (typed.lo, typed.hi, commit)
1164 });
1165 // A click on the value types it in (the box keeps its size: the border is always there,
1166 // clear until it is typed in); a double-click resets it, as before.
1167 let editing = typing_text.is_some();
1168 let focus = SLIDER_EDIT.with(|s| s.borrow().as_ref().filter(|e| e.row == row).map(|e| e.focus.clone()));
1169 let on_down = (entry.is_some() || reset.is_some()).then(|| {
1170 let open = entry.clone();
1171 let (num, unit) = (num.clone(), unit.clone());
1172 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
1173 if event.click_count >= 2 {
1174 if let Some(back) = slider_back(row) {
1175 window.focus(&back);
1176 }
1177 slider_forget(row);
1178 if let Some(reset) = &reset {
1179 reset(this, cx);
1180 cx.notify();
1181 }
1182 } else if let Some((lo, hi, commit)) = &open {
1183 let focus = cx.focus_handle();
1184 let back = window.focused(cx);
1185 window.focus(&focus);
1186 let edit = SliderEdit {
1187 row,
1188 edit: crate::ui::kit::NumberEdit::begin(&num),
1189 unit: unit.clone(),
1190 lo: *lo,
1191 hi: *hi,
1192 commit: commit.clone(),
1193 focus,
1194 back,
1195 };
1196 SLIDER_EDIT.with(|s| *s.borrow_mut() = Some(edit));
1197 cx.notify();
1198 }
1199 })
1200 });
1201 let leave = entry.is_some().then(|| {
1202 cx.listener(move |_, _: &MouseDownEvent, window, cx| {
1203 let back = slider_back(row);
1204 slider_leave(row, cx);
1205 if let Some(back) = back {
1206 window.focus(&back);
1207 }
1208 })
1209 });
1210 // While typed, the value holds the keyboard: a key it does not take still ends at the value.
1211 let key = focus.is_some().then(|| {
1212 cx.listener(move |_, event: &KeyDownEvent, window, cx| {
1213 let k = &event.keystroke;
1214 let back = slider_back(row);
1215 slider_key(&k.key, k.modifiers.control, k.modifiers.alt, k.key_char.as_deref(), cx);
1216 if !slider_typing()
1217 && let Some(back) = back
1218 {
1219 window.focus(&back);
1220 }
1221 cx.stop_propagation();
1222 })
1223 });
1224 div()
1225 .id((id, row))
1226 .h(px(crate::layout::redesign::CONTROL_S))
1227 .px(px(8.))
1228 .min_w(px(min_w))
1229 .justify_end()
1230 .flex()
1231 .items_center()
1232 .rounded(px(4.))
1233 .border_1()
1234 .border_color(if editing { gpui::Hsla::from(rgb(t.accent)) } else { gpui::transparent_black() })
1235 .bg(rgb(t.e2))
1236 .type_style(type_scale::caption())
1237 .text_color(rgb(ink))
1238 .when(entry.is_some(), |d| d.cursor_pointer())
1239 .when_some(on_down, |d, on_down| d.on_mouse_down(MouseButton::Left, on_down))
1240 .when_some(leave, |d, leave| d.on_mouse_down_out(leave))
1241 .when_some(focus, |d, focus| d.track_focus(&focus))
1242 .when_some(key, |d, key| d.on_key_down(key))
1243 .when_some(typing_text, |d, (buf, suffix)| {
1244 d.child(buf).child(div().w(px(1.)).h(px(14.)).bg(rgb(t.accent))).child(suffix)
1245 })
1246 .when(!editing, |d| d.child(SharedString::from(shown.to_string())))
1247}
1248
1249/// A value pill with its Reset slot beside it, laid out the way [`crate::ui::kit::value_pill`]
1250/// lays one out, with the box typed by [`typed_readout`].
1251#[allow(clippy::too_many_arguments)]
1252pub(crate) fn typed_value_pill<V: 'static>(
1253 id: &'static str,
1254 shown: &str,
1255 open: Option<(String, String)>,
1256 min_w: f32,
1257 changed: bool,
1258 typed: Option<SliderTyped<V>>,
1259 on_reset: impl Fn(&mut Window, &mut App) + 'static,
1260 cx: &mut Context<V>,
1261) -> Div {
1262 let t = theme::tokens();
1263 let ink = if changed { t.ink1 } else { t.ink2 };
1264 div()
1265 .flex_none()
1266 .flex()
1267 .items_center()
1268 .gap(px(2.))
1269 .child(typed_readout(id, shown, open, min_w, ink, typed, None, cx))
1270 .child(crate::ui::kit::reset_slot(id, changed, on_reset))
1271}
1272
1273/// The slider row (DESIGN §9.1): label left in ink3, value right in mono, a
1274/// 4px track under them and a 14px thumb on it, the whole track one `HIT_MIN`
1275/// tall to hit. Arrow keys are the card's own nudge, not this row's.
1276#[allow(dead_code, reason = "wave 2 panels mount these")]
1277pub(crate) fn slider_row<V: 'static>(row: SliderRow<V>, cx: &mut Context<V>) -> impl IntoElement {
1278 slider_row_with(row, false, None, cx)
1279}
1280
1281/// [`slider_row`] whose label carries a tooltip saying what the setting is for.
1282pub(crate) fn slider_row_tip<V: 'static>(
1283 row: SliderRow<V>,
1284 tip: &'static str,
1285 cx: &mut Context<V>,
1286) -> impl IntoElement {
1287 slider_row_with(row, false, Some(tip), cx)
1288}
1289
1290/// [`slider_row`] on one line: label at the left, the track filling the middle, the value (and
1291/// reset slot) at the right, so a settings list can keep every row `CONTROL_H` tall.
1292pub(crate) fn slider_row_inline<V: 'static>(row: SliderRow<V>, cx: &mut Context<V>) -> impl IntoElement {
1293 slider_row_with(row, true, None, cx)
1294}
1295
1296fn slider_row_with<V: 'static>(
1297 row: SliderRow<V>,
1298 inline: bool,
1299 tip: Option<&'static str>,
1300 cx: &mut Context<V>,
1301) -> gpui::Stateful<Div> {
1302 const THUMB: f32 = 14.;
1303 let SliderRow {
1304 id,
1305 label,
1306 value,
1307 fraction,
1308 changed,
1309 bar,
1310 on_press,
1311 on_reset,
1312 typed,
1313 } = row;
1314 let fraction = slider_fraction(fraction, 0., 1.);
1315 let t = theme::tokens();
1316 let value_ink = if changed { t.ink1 } else { t.ink2 };
1317 let value_reset = on_reset.clone();
1318 // Always on the row, so a value change never moves anything: live when the
1319 // value is off its default, dimmed and inert while it sits there.
1320 let reset_button = on_reset.map(|reset| {
1321 // REDESIGN §3.9: a 16px `rotate-ccw` at the row's right edge, drawn
1322 // only while the value is off its default (the slot stays, so
1323 // nothing moves when it appears).
1324 div()
1325 .id(SharedString::from(format!("{id}-reset")))
1326 .flex_none()
1327 .size(px(16.))
1328 .flex()
1329 .items_center()
1330 .justify_center()
1331 .when(changed, |d| {
1332 d.cursor_pointer()
1333 .tooltip(overlay_tip_hover("Reset", "", None))
1334 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1335 reset(this, cx);
1336 cx.notify();
1337 }))
1338 .child(Icon::RotateCcw.el(IconSize::Inline, t.ink2))
1339 })
1340 });
1341 let label_el = div()
1342 .id(SharedString::from(format!("{id}-label")))
1343 .flex_none()
1344 .when(inline, |d| d.w(px(96.)))
1345 .when_some(tip, |d, tip| d.tooltip(overlay_tip_hover(&label, "", Some(tip))))
1346 .type_style(type_scale::body())
1347 .text_color(rgb(t.ink2))
1348 .child(label);
1349 let pill = typed_readout(id, &value, None, 56., value_ink, typed, value_reset, cx);
1350 // Inline, the reset slot sits before the value so the value ends at the row's edge like
1351 // every other row's control; stacked, the value is already clear of the track's end.
1352 let value_el = div().flex_none().flex().items_center().gap(px(8.));
1353 let value_el = match inline {
1354 true => value_el.children(reset_button).child(pill),
1355 false => value_el.child(pill).children(reset_button),
1356 };
1357 let track = div()
1358 .relative()
1359 .w_full()
1360 .h(px(HIT_MIN))
1361 .flex()
1362 .items_center()
1363 .cursor_pointer()
1364 .on_mouse_down(
1365 MouseButton::Left,
1366 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
1367 on_press(this, event.position.x, cx);
1368 }),
1369 )
1370 .child(bounds_probe(bar))
1371 .child(
1372 div()
1373 .w_full()
1374 .h(px(4.))
1375 .rounded(px(2.))
1376 .bg(rgb(t.e3))
1377 .child(
1378 div()
1379 .h_full()
1380 .w(relative(fraction))
1381 .rounded(px(2.))
1382 .bg(rgb(t.accent)),
1383 ),
1384 )
1385 .child(
1386 // Centred on its fraction: the thumb's own half width is the
1387 // margin, so the middle of the thumb, not its left edge, is
1388 // where the value reads.
1389 div()
1390 .absolute()
1391 .top(px((HIT_MIN - THUMB) / 2.))
1392 .left(relative(fraction))
1393 .ml(px(-THUMB / 2.))
1394 .size(px(THUMB))
1395 .rounded_full()
1396 .bg(rgb(t.ink1)),
1397 )
1398 .when(inline, |d| d.flex_1().w_auto().min_w(px(0.)));
1399 let root = div().id(id).w_full().flex();
1400 match inline {
1401 true => root.items_center().gap(px(12.)).child(label_el).child(track).child(value_el),
1402 false => root
1403 .flex_col()
1404 .gap(px(4.))
1405 .child(div().flex().justify_between().items_center().child(label_el).child(value_el))
1406 .child(track),
1407 }
1408}
1409
1410/// A bipolar slider's bare track, for a pan: the same track as [`slider_row`] with its
1411/// neutral point (the centre, 0) marked by two notches above and below, clear of the thumb's
1412/// footprint, and the fill running out from that centre to the value.
1413pub(crate) fn centred_track<V: 'static>(
1414 id: &'static str,
1415 fraction: f32,
1416 bar: Rc<Cell<Bounds<Pixels>>>,
1417 on_press: impl Fn(&mut V, Pixels, &mut Context<V>) + 'static,
1418 cx: &mut Context<V>,
1419) -> gpui::Stateful<Div> {
1420 const THUMB: f32 = 14.;
1421 const NOTCH: f32 = 4.;
1422 let t = theme::tokens();
1423 let fraction = slider_fraction(fraction, 0., 1.);
1424 let (from, to) = (fraction.min(0.5), fraction.max(0.5));
1425 div()
1426 .id(id)
1427 .relative()
1428 .w_full()
1429 .h(px(HIT_MIN))
1430 .flex()
1431 .items_center()
1432 .cursor_pointer()
1433 .on_mouse_down(
1434 MouseButton::Left,
1435 cx.listener(move |this, event: &MouseDownEvent, _, cx| on_press(this, event.position.x, cx)),
1436 )
1437 .child(bounds_probe(bar))
1438 .child(
1439 div().relative().w_full().h(px(4.)).rounded(px(2.)).bg(rgb(t.e3)).child(
1440 div()
1441 .absolute()
1442 .top_0()
1443 .bottom_0()
1444 .left(relative(from))
1445 .w(relative(to - from))
1446 .rounded(px(2.))
1447 .bg(rgb(t.accent)),
1448 ),
1449 )
1450 .child(div().absolute().top_0().left(relative(0.5)).w(px(1.)).h(px(NOTCH)).bg(rgb(t.ink3)))
1451 .child(div().absolute().bottom_0().left(relative(0.5)).w(px(1.)).h(px(NOTCH)).bg(rgb(t.ink3)))
1452 .child(
1453 div()
1454 .absolute()
1455 .top(px((HIT_MIN - THUMB) / 2.))
1456 .left(relative(fraction))
1457 .ml(px(-THUMB / 2.))
1458 .size(px(THUMB))
1459 .rounded_full()
1460 .bg(rgb(t.ink1)),
1461 )
1462}
1463
1464/// The `More` fold (DESIGN §9.1): a row that opens and closes a group the
1465/// card keeps hidden by default. The open state is the card's; keep it with
1466/// [`load_folds`] / [`save_folds`] so it is remembered per panel.
1467#[allow(dead_code, reason = "wave 2 panels mount these")]
1468pub(crate) fn more_fold<V: 'static>(
1469 id: &'static str,
1470 open: bool,
1471 on_toggle: impl Fn(&mut V, &mut Context<V>) + 'static,
1472 cx: &mut Context<V>,
1473) -> impl IntoElement {
1474 let t = crate::ui::theme::tokens();
1475 div()
1476 .id(id)
1477 .w_full()
1478 .h(px(HIT_MIN))
1479 .flex()
1480 .items_center()
1481 .gap(px(4.))
1482 .cursor_pointer()
1483 .type_style(type_scale::body_strong())
1484 .text_color(rgb(t.ink2))
1485 .hover(|s| s.text_color(rgb(crate::ui::theme::tokens().ink1)))
1486 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1487 on_toggle(this, cx);
1488 cx.notify();
1489 }))
1490 .child(
1491 if open { crate::ui::icons::Icon::ChevronDown } else { crate::ui::icons::Icon::ChevronRight }
1492 .el(crate::ui::icons::IconSize::Inline, t.ink3),
1493 )
1494 .child("More")
1495}
1496
1497/// Where the open `More …` folds live: next to the other small preference
1498/// files (`dock-tab`, `stance-splits`), one panel id per line. A fold the file
1499/// does not name is closed, which is the default.
1500#[allow(dead_code, reason = "wave 2 panels mount these")]
1501pub(crate) fn folds_config_path() -> PathBuf {
1502 crate::keymap::Keymap::config_path().with_file_name("panel-folds")
1503}
1504
1505#[allow(dead_code, reason = "wave 2 panels mount these")]
1506pub(crate) fn load_folds() -> BTreeSet<String> {
1507 load_folds_from(&folds_config_path())
1508}
1509
1510#[allow(dead_code, reason = "wave 2 panels mount these")]
1511pub(crate) fn load_folds_from(path: &Path) -> BTreeSet<String> {
1512 std::fs::read_to_string(path)
1513 .map(|text| {
1514 text.lines()
1515 .map(str::trim)
1516 .filter(|id| !id.is_empty())
1517 .map(str::to_owned)
1518 .collect()
1519 })
1520 .unwrap_or_default()
1521}
1522
1523#[allow(dead_code, reason = "wave 2 panels mount these")]
1524pub(crate) fn save_folds(open: &BTreeSet<String>) {
1525 save_folds_to(open, &folds_config_path());
1526}
1527
1528#[allow(dead_code, reason = "wave 2 panels mount these")]
1529pub(crate) fn save_folds_to(open: &BTreeSet<String>, path: &Path) {
1530 if let Some(dir) = path.parent() {
1531 let _ = std::fs::create_dir_all(dir);
1532 }
1533 let text: String = open.iter().map(|id| format!("{id}\n")).collect();
1534 let _ = std::fs::write(path, text);
1535}
1536
1537#[cfg(test)]
1538mod slider_fold_tests {
1539 use super::*;
1540
1541 #[test]
1542 fn a_marker_edit_types_printable_text_to_its_cap_and_backspaces() {
1543 let mut edit = MarkerEdit::new(0, MarkerField::Name, "Fix");
1544 edit.all = false; // the caret at the end, so the letters add to the words
1545 edit.typed('!');
1546 edit.typed('\n');
1547 edit.typed('é');
1548 assert_eq!(edit.text, "Fix!é", "a control character is not a letter");
1549 edit.backspace();
1550 assert_eq!(edit.text, "Fix!");
1551 let mut name = MarkerEdit::new(1, MarkerField::Name, "");
1552 name.all = false;
1553 for _ in 0..(engine::project::MAX_MARKER_NAME_CHARS + 10) {
1554 name.typed('x');
1555 }
1556 assert_eq!(name.text.chars().count(), engine::project::MAX_MARKER_NAME_CHARS);
1557 }
1558
1559 #[test]
1560 fn a_slider_fraction_is_the_share_of_its_range_and_pins_at_the_ends() {
1561 assert_eq!(slider_fraction(5., 0., 10.), 0.5);
1562 assert_eq!(slider_fraction(0., 0., 10.), 0.);
1563 assert_eq!(slider_fraction(10., 0., 10.), 1.);
1564 // A value past either end pins to it; a drag that slid off the bar
1565 // names the bar's end, never a number outside it.
1566 assert_eq!(slider_fraction(-3., 0., 10.), 0.);
1567 assert_eq!(slider_fraction(42., 0., 10.), 1.);
1568 // Speed runs 0.25x..4x, so 1x sits a little under the middle.
1569 let at_one = slider_fraction(1., 0.25, 4.);
1570 assert!((at_one - 0.2).abs() < 1e-6, "got {at_one}");
1571 }
1572
1573 #[test]
1574 fn a_range_with_no_width_or_a_value_that_is_not_a_number_reads_as_the_start() {
1575 assert_eq!(slider_fraction(3., 2., 2.), 0.);
1576 assert_eq!(slider_fraction(f32::NAN, 0., 10.), 0.);
1577 assert_eq!(slider_fraction(f32::INFINITY, 0., 10.), 1.);
1578 }
1579
1580 #[test]
1581 fn open_folds_survive_a_round_trip_and_a_missing_file_leaves_them_closed() {
1582 let dir = engine::scratch::Scratch::dir("edith-panel-folds");
1583 let path = dir.join("panel-folds");
1584 assert!(load_folds_from(&dir.join("nothing-here")).is_empty());
1585
1586 let open: BTreeSet<String> = ["eq", "speed"].into_iter().map(str::to_owned).collect();
1587 save_folds_to(&open, &path);
1588 assert_eq!(load_folds_from(&path), open);
1589
1590 // Blank lines and padding are not folds.
1591 std::fs::write(&path, " color \n\n\ntransform\n").expect("write");
1592 let loaded = load_folds_from(&path);
1593 assert_eq!(loaded.len(), 2);
1594 assert!(loaded.contains("color") && loaded.contains("transform"));
1595 }
1596}
1597
1598#[cfg(test)]
1599mod cue_edit_tests {
1600 use super::*;
1601
1602 fn edit(seed: &str) -> CueEdit {
1603 CueEdit::new(Lane::S1, 0, 0, seed)
1604 }
1605
1606 #[test]
1607 fn select_all_is_replaced_by_the_next_stroke_and_backspace_clears_it() {
1608 let mut e = edit("Intro");
1609 e.select_all();
1610 e.typed('O');
1611 assert_eq!(e.text, "O");
1612 assert!(!e.all);
1613 e.select_all();
1614 e.backspace();
1615 assert_eq!(e.text, "");
1616 let mut e = edit("ab");
1617 e.select_all();
1618 e.newline();
1619 assert_eq!(e.text, "\n");
1620 }
1621
1622 #[test]
1623 fn a_marker_name_opens_selected_whole_and_the_next_letter_replaces_it() {
1624 let mut m = MarkerEdit::new(0, MarkerField::Name, "Summer");
1625 assert!(m.all, "a rename opens with the whole name selected");
1626 assert!(!MarkerEdit::new(0, MarkerField::Note, "Summer").all);
1627 m.typed('I');
1628 assert_eq!(m.text, "I");
1629 assert!(!m.all);
1630 }
1631
1632 #[test]
1633 fn typing_takes_any_printable_character_not_just_ascii() {
1634 let mut e = edit("");
1635 for c in "Ça va — 界".chars() {
1636 e.typed(c);
1637 }
1638 assert_eq!(e.text, "Ça va — 界");
1639 e.typed('\u{7}');
1640 e.typed('\t');
1641 assert_eq!(e.text, "Ça va — 界", "control characters are not words");
1642 }
1643
1644 #[test]
1645 fn backspace_takes_back_one_whole_character_and_the_refusal_with_it() {
1646 let mut e = edit("é界");
1647 e.backspace();
1648 assert_eq!(e.text, "é", "one character, not one byte");
1649 e.refusal = Some("old".into());
1650 e.backspace();
1651 assert_eq!(e.text, "");
1652 assert_eq!(e.refusal, None);
1653 e.backspace();
1654 assert_eq!(e.text, "", "backspace on nothing is nothing");
1655 }
1656
1657 #[test]
1658 fn shift_enter_is_a_line_break_inside_the_cue() {
1659 let mut e = edit("first");
1660 e.newline();
1661 e.typed('x');
1662 assert_eq!(e.text, "first\nx");
1663 }
1664
1665 #[test]
1666 fn commit_writes_only_what_changed() {
1667 let mut e = edit("same");
1668 assert_eq!(e.commit("same"), None, "unchanged is no edit");
1669 e.typed('!');
1670 assert_eq!(e.commit("same"), Some("same!".to_string()));
1671 }
1672
1673 #[test]
1674 fn the_cap_refuses_out_loud_and_is_not_below_500() {
1675 let mut e = edit(&"a".repeat(CUE_EDIT_CHARS - 1));
1676 e.typed('b');
1677 assert_eq!(e.text.chars().count(), CUE_EDIT_CHARS);
1678 assert_eq!(e.refusal, None, "the last one still fits");
1679 e.typed('c');
1680 assert_eq!(e.text.chars().count(), CUE_EDIT_CHARS);
1681 assert!(e.refusal.is_some(), "the one past it is refused");
1682 }
1683}
1684
1685#[cfg(test)]
1686mod tip_place_tests {
1687 use super::*;
1688
1689 /// A tooltip box (the plate plus its clear margin) at the right and bottom
1690 /// edges of a 1280x720 window stays whole inside it, and a long sentence
1691 /// is capped to the plate's max width so it wraps rather than running on.
1692 #[test]
1693 fn a_tooltip_stays_inside_the_window_at_every_edge() {
1694 let window = (1280., 720.);
1695 let long = "Quieter than this counts as silence. Lower it to keep more of the room tone and quiet words, raise it to cut harder.";
1696 let w = tip_w(&[long]);
1697 assert!(w <= TIP_MAX_W);
1698 let size = (w + TIP_CLEAR_X, 120. + TIP_CLEAR_Y);
1699 for mouse in [(1270., 300.), (300., 710.), (1275., 715.), (5., 5.), (640., 360.)] {
1700 let (x, y) = tip_origin(mouse, size, window);
1701 assert!(x >= 0. && y >= 0., "{mouse:?}");
1702 assert!(x + size.0 <= window.0 && y + size.1 <= window.1, "{mouse:?} -> {x},{y}");
1703 }
1704 }
1705}
1706
1707/// A word that may change between two spellings (`Mute`/`Muted`, `Snap on`/
1708/// `Snap off`) without moving anything beside it: the slot is as wide as
1709/// `widest` (laid out but unseen), and the word is painted over it, left
1710/// aligned. Text metrics decide the width, so no pixel guess goes stale.
1711#[allow(dead_code, reason = "no worded toggle swaps spellings after REDESIGN §3.3; kept for the next one")]
1712pub(crate) fn steady_word(word: impl Into<SharedString>, widest: &'static str) -> Div {
1713 div()
1714 .relative()
1715 .flex_none()
1716 .whitespace_nowrap()
1717 .child(div().invisible().child(widest))
1718 .child(div().absolute().top_0().left_0().child(word.into()))
1719}