forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

widgets.rs566 lines, 22.5 KiBHistoryRawDownload
1//! The small elements every region is built out of.
2
3use crate::*;
4
5/// `ClickEvent::modifiers()` answers the mouse-*up* modifiers (gpui-0.2.2
6/// `interactive.rs`), so releasing ctrl before the button lands undoes a
7/// ctrl-held toggle decided on mouse-down. This reads the *press* modifiers
8/// instead -- the ones a ctrl-click decision (multi-pick, no collapse) was
9/// actually made under.
10pub(crate) fn press_modifiers(event: &ClickEvent) -> gpui::Modifiers {
11 match event {
12 ClickEvent::Mouse(m) => m.down.modifiers,
13 ClickEvent::Keyboard(_) => gpui::Modifiers::default(),
14 }
15}
16
17/// As [`waveform`], but in a caller-picked ink rather than the fixed
18/// secondary foreground -- the darkroom bench's own audio clips draw their
19/// envelope in the source's ink (DESIGN §5), which the legacy timeline never
20/// needed a colour for.
21pub(crate) fn waveform_ink(
22 peaks: Arc<Vec<(f32, f32)>>,
23 from: f64,
24 to: f64,
25 ink: u32,
26) -> impl IntoElement {
27 canvas(
28 |_, _, _| (),
29 move |bounds, _, window, _| {
30 let (o, s) = (bounds.origin, bounds.size);
31 let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height));
32 if cols.len() < 2 {
33 return;
34 }
35 // Down the tops and back along the bottoms: one closed outline of
36 // the whole envelope, which is one path rather than a path a column.
37 let mut points: Vec<Point<Pixels>> = cols
38 .iter()
39 .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top)))
40 .collect();
41 points.extend(
42 cols.iter()
43 .rev()
44 .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))),
45 );
46 let mut path = PathBuilder::fill();
47 path.add_polygon(&points, true);
48 if let Ok(path) = path.build() {
49 window.paint_path(path, rgb(ink));
50 }
51 },
52 )
53 .size_full()
54}
55
56/// An audio clip's fade, drawn as a translucent wedge over its box: silent
57/// (full shade) at the clip's own edge, clear by the fade's far side --
58/// [`is_in`] mirrors it for the tail's ramp-down. The same `canvas` +
59/// `PathBuilder` idiom [`waveform`] draws its envelope with, filled with the
60/// same wash the in/out range already paints the bed with
61/// (`ACCENT_WASH`, timeline.rs), so a fade reads as one more overlay on this
62/// bed rather than a shape borrowed from somewhere else.
63pub(crate) fn fade_wedge(is_in: bool) -> impl IntoElement {
64 canvas(
65 |_, _, _| (),
66 move |bounds, _, window, _| {
67 let (o, s) = (bounds.origin, bounds.size);
68 let (w, h) = (f32::from(s.width), f32::from(s.height));
69 if w <= 0. || h <= 0. {
70 return;
71 }
72 // A right triangle: the clip's silent corner (top of the clip's
73 // own edge) down to the bed and across to the fade's far side --
74 // the wedge shape every editor draws for a ramp.
75 let points = match is_in {
76 true => vec![
77 point(o.x, o.y),
78 point(o.x, o.y + px(h)),
79 point(o.x + px(w), o.y + px(h)),
80 ],
81 false => vec![
82 point(o.x + px(w), o.y),
83 point(o.x + px(w), o.y + px(h)),
84 point(o.x, o.y + px(h)),
85 ],
86 };
87 let mut path = PathBuilder::fill();
88 path.add_polygon(&points, true);
89 if let Ok(path) = path.build() {
90 window.paint_path(path, rgba(ACCENT_WASH()));
91 }
92 },
93 )
94 .size_full()
95}
96
97/// A video clip's dissolve into its neighbour, drawn as a small X astride the
98/// join -- the box it is given is the last [`Clip::transition_out`] frames of
99/// the clip's own width, so the mark sits right at the edge it dissolves
100/// through. Two strokes rather than [`fade_wedge`]'s fill: a dissolve is not
101/// a ramp to or from silence, it is two clips overlapping, and an X reads as
102/// a splice the way a wedge reads as a fade.
103pub(crate) fn dissolve_glyph() -> impl IntoElement {
104 canvas(
105 |_, _, _| (),
106 move |bounds, _, window, _| {
107 let (o, s) = (bounds.origin, bounds.size);
108 let (w, h) = (f32::from(s.width), f32::from(s.height));
109 if w <= 0. || h <= 0. {
110 return;
111 }
112 let mut path = PathBuilder::stroke(px(1.5));
113 path.move_to(point(o.x, o.y));
114 path.line_to(point(o.x + px(w), o.y + px(h)));
115 path.move_to(point(o.x + px(w), o.y));
116 path.line_to(point(o.x, o.y + px(h)));
117 if let Ok(path) = path.build() {
118 window.paint_path(path, rgba(ACCENT_WASH()));
119 }
120 },
121 )
122 .size_full()
123}
124
125/// The hover line every control in the room wears (the user, 2026-09-09:
126/// "each and every button gets hover over information" -- nobody could name
127/// the band's own glyphs). One shape, built from the same pair the hitmap
128/// already names the control by: `<name> · <chord>`, DESIGN §4's "every
129/// command wears its chord" and §8's no-prose rule -- never a sentence. A
130/// control the current state refuses says *why* in the chord's place: naming
131/// a stroke that will not fire is the lie §4 forbids.
132pub(crate) fn tip_line(name: &str, chord: &str, why: Option<&str>) -> SharedString {
133 match why {
134 Some(why) => format!("{name} · {why}"),
135 // `Keymap::chord`'s own "unbound" badge: a glyph with no stroke says
136 // its name and stops, rather than wearing `--` as if that were one.
137 None if chord.is_empty() || chord == "--" => name.to_string(),
138 None => format!("{name} · {chord}"),
139 }
140 .into()
141}
142
143/// [`tip_line`] in the shape gpui's `.tooltip` takes. Every shared control
144/// constructor attaches this rather than building its own plate, which is
145/// what keeps the next control from shipping without a hover line.
146pub(crate) fn tip_hover(
147 name: &str,
148 chord: &str,
149 why: Option<&str>,
150) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
151 let say = tip_line(name, chord, why);
152 move |_, cx| cx.new(|_| Tip(say.clone())).into()
153}
154
155/// [`tip_hover`] for a control drawn *on* a card or a menu, where an
156/// ordinary [`Tip`] stands aside (`OVERLAID`) and would show nothing.
157pub(crate) fn overlay_tip_hover(
158 name: &str,
159 chord: &str,
160 why: Option<&str>,
161) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
162 let say = tip_line(name, chord, why);
163 move |_, cx| cx.new(|_| OverlayTip(say.clone())).into()
164}
165
166/// [`tip_hover`] for a control that dispatches an action: the name and the
167/// stroke are read live off the keymap and the enable state, so a rebind or
168/// a refusal can never leave a stale plate under the pointer.
169pub(crate) fn action_hover(
170 player: &Player,
171 action: ActionId,
172) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
173 let enabled = player.enable(action, None);
174 let chord = player.keymap.chord(action);
175 tip_hover(action.label(), &chord, enabled.why())
176}
177
178/// A toolbar button: its glyph, its name, and its key on hover. `id` only buys
179/// `on_click` and the tooltip -- it is still not focusable, so the root's own
180/// key listener keeps working after a press, and the click lands on mouse-up
181/// inside the button (a press that slides off does nothing).
182///
183/// A button that would do nothing says so: dimmed, no pointer, no listener.
184pub(crate) fn control(
185 id: &'static str,
186 // The rect the label is allowed to change inside: 0 hugs the text, anything
187 // else is reserved once and never moves again, which is what keeps a button
188 // that relabels itself ("Export"/"Cancel") from shoving its neighbours
189 // along the row every time its state changes.
190 w: f32,
191 // The plane the button stands on. One button in the window is the accent
192 // (Export, the primary action); everything else is `BG_RAISED`.
193 bg: u32,
194 glyph: Option<AnyElement>,
195 // Not `&'static str`: the volume button's label is its state.
196 label: impl Into<SharedString>,
197 shortcut: String,
198 enabled: bool,
199 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
200) -> impl IntoElement {
201 let label = label.into();
202 let tip = tip_line(&label, &shortcut, None);
203 div()
204 .id(id)
205 .flex_none()
206 .h(px(CONTROL_H))
207 .flex()
208 .items_center()
209 .justify_center()
210 .gap(px(6.))
211 .px(px(8.))
212 .when(w > 0., |d| d.w(px(w)).overflow_hidden())
213 .rounded(px(4.))
214 .bg(rgb(bg))
215 .when(bg == ACCENT_PRIMARY(), |d| d.text_color(rgb(BG_CANVAS())))
216 // A glyph sits in a box of its own width, never in the width it happens
217 // to draw: the pause bars are 12 px wide and the play triangle is 11, so
218 // pressing Play used to slide every button in the row one pixel left. A
219 // slot is the only fix that holds for the next glyph as well as this one.
220 .children(glyph.map(|glyph| {
221 div()
222 .flex_none()
223 .w(px(GLYPH_SLOT))
224 .flex()
225 .items_center()
226 .justify_center()
227 .child(glyph)
228 }))
229 .child(label)
230 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
231 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
232 .when(enabled, |d| {
233 // An accented button keeps its accent under the pointer: hovering it
234 // to the chrome's own hover colour reads as the primary action
235 // turning itself off.
236 d.cursor_pointer()
237 .hover(move |s| {
238 s.bg(rgb(match bg == ACCENT_PRIMARY() {
239 true => ACCENT_HOVER(),
240 false => BG_HOVER(),
241 }))
242 })
243 .on_click(on_click)
244 })
245}
246
247/// The monitoring level as something to drag: 4 px of bar to look at and the
248/// whole control's height to hit (WCAG 2.5.8), the split the speed bar and the
249/// colour sliders both make. Only the level -- mute is the button beside it, so
250/// a muted slider still shows what unmuting comes back to, drawn dim.
251///
252/// Whether a card or a menu is drawn over the window, as the hover labels see
253/// it: written once a frame by [`Player::render`], read by every [`Tip`] before
254/// it paints.
255///
256/// A tooltip already on screen when an overlay opens *stays* on screen in gpui:
257/// occluding the surface under it does not take it back, because the check that
258/// keeps it visible works off the element's absolute bounds and knows nothing
259/// about what was painted over it (`div.rs::handle_tooltip_mouse_move`, its own
260/// TODO). So the tip is what has to stand aside -- here, once, for every hover
261/// label in this window, rather than at fifteen call sites of which the
262/// sixteenth would be forgotten.
263pub(crate) static OVERLAID: AtomicBool = AtomicBool::new(false);
264
265/// Whether a tip is cleared to paint: an ordinary tip stands aside whenever
266/// `OVERLAID` is set (a card/menu is up over the underlying UI it belongs
267/// to), but a tip *anchored on the overlay itself* -- the `?` glyph on a
268/// card's own head, say -- was never the case `OVERLAID` meant to catch, so
269/// it paints regardless. One predicate, so [`Tip`] and [`OverlayTip`] can't
270/// drift apart on what "overlaid" is supposed to mean.
271pub(crate) fn tip_may_paint(anchored_on_overlay: bool) -> bool {
272 anchored_on_overlay || !OVERLAID.load(Ordering::Relaxed)
273}
274
275/// DESIGN §4: "Notices, menus, chips, cues, and tooltips are all the same
276/// plate" -- canvas-on-panel, 2px radius, the room's own type
277/// (`ui::type_scale`), not a bordered box in an ad hoc size.
278fn tip_plate(text: &SharedString) -> Div {
279 let style = crate::ui::type_scale::label(
280 crate::ui::type_scale::LABEL_ROW_PX,
281 gpui::FontWeight::MEDIUM,
282 );
283 div()
284 .px(px(8.))
285 .py(px(4.))
286 .rounded(px(2.))
287 .bg(rgb(DARK_CANVAS()))
288 .font(style.font)
289 .text_size(style.size)
290 .text_color(rgb(INK1()))
291 .child(text.clone())
292}
293
294/// A tooltip is a view in gpui and nothing smaller, so this is the smallest one
295/// that carries a line of text. It paints outside the window's element tree and
296/// therefore owns its colours.
297pub(crate) struct Tip(pub(crate) SharedString);
298
299impl Render for Tip {
300 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
301 // A card or a menu is up: nothing. A line of text over the items of the
302 // menu that just opened under the pointer is the card being painted
303 // over by the window it covers. (This struct is every tooltip on the
304 // *underlying* UI -- grepped: `timeline.rs`, `library.rs`,
305 // `overlays.rs`, `spine_stance.rs`, `dock_stance.rs`,
306 // `timeband_stance.rs`, `preview.rs`, here -- so the fix belongs here
307 // once, not per call site.)
308 if !tip_may_paint(false) {
309 return div();
310 }
311 tip_plate(&self.0)
312 }
313}
314
315/// A tip anchored on the overlay itself -- a card's own `?` glyph, drawn on
316/// its own card head. `OVERLAID` exists to hide a [`Tip`] on the UI *under*
317/// a card while the card sits over it; a tip painted on the card is not
318/// that case, so it is exempt (`tip_may_paint(true)` is always `true`).
319/// Everything else about it is [`Tip`]'s own plate.
320pub(crate) struct OverlayTip(pub(crate) SharedString);
321
322impl Render for OverlayTip {
323 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
324 tip_plate(&self.0)
325 }
326}
327
328/// A number being typed into a row that has no text field of its own: the
329/// digits so far, the range and digit cap that row enforces, and once a
330/// commit has been refused, why. Text-field semantics on a card that has no
331/// text field -- typing, backspace, arrows that step, enter that commits and
332/// escape that gives up -- held as state and driven by the root's key
333/// handler, since nothing in these rows takes gpui focus. Shared by the
334/// export card's custom bitrate field and the transition duration row
335/// (DEBT #111) -- one implementation, each caller its own range and unit.
336#[derive(Clone, Debug, PartialEq, Eq)]
337pub(crate) struct NumberEdit {
338 pub(crate) text: String,
339 pub(crate) refusal: Option<String>,
340 min: u32,
341 max: u32,
342 digits: usize,
343 unit: &'static str,
344}
345
346impl NumberEdit {
347 /// Starts on the number the row already carries, so backspace edits it
348 /// rather than the field opening empty over a value that is still in
349 /// force. Zero is no number at all -- it is what the row opens at, before
350 /// anyone has typed one.
351 pub(crate) fn new(value: u32, min: u32, max: u32, digits: usize, unit: &'static str) -> Self {
352 NumberEdit {
353 text: match value {
354 0 => String::new(),
355 v => v.to_string(),
356 },
357 refusal: None,
358 min,
359 max,
360 digits,
361 unit,
362 }
363 }
364
365 /// A digit against what is there. The one past the row's digit cap is
366 /// refused *out loud*: a keystroke dropped in silence is how the old
367 /// digit capture left a row showing a number the user had already typed
368 /// past.
369 pub(crate) fn digit(&mut self, digit: u32) {
370 if self.text.chars().count() >= self.digits {
371 self.refusal = Some(format!(
372 "{} digits is already past the ceiling",
373 self.digits
374 ));
375 return;
376 }
377 match char::from_digit(digit, 10) {
378 Some(c) => {
379 self.text.push(c);
380 self.refusal = None;
381 }
382 None => self.refusal = Some("digits only".into()),
383 }
384 }
385
386 /// Erases the last digit, and the refusal with it: the number on screen has
387 /// changed, so the reason the old one was refused no longer describes it.
388 pub(crate) fn backspace(&mut self) {
389 self.text.pop();
390 self.refusal = None;
391 }
392
393 /// The arrows, which is how a number gets picked rather than typed. Steps
394 /// from what is in the field -- an empty one starts at the floor, so the
395 /// first press up is the row's minimum and not a jump to some remembered
396 /// value -- and stays inside the range, because a step is a walk through
397 /// the legal numbers rather than a way out of them.
398 #[allow(dead_code)] // the budget field is free text; the transition row still types digits
399 pub(crate) fn step(&mut self, by: i32) {
400 let at = self
401 .text
402 .parse::<i32>()
403 .unwrap_or(self.min as i32 - by.signum());
404 self.text = (at + by)
405 .clamp(self.min as i32, self.max as i32)
406 .to_string();
407 self.refusal = None;
408 }
409
410 /// The number, or `None` with the reason recorded where the row will read
411 /// it. Never clamped: a row that clamps a typed number to its ceiling
412 /// without saying so is writing a number the user never typed. For a row
413 /// whose own stepper already clamps silently, use [`Self::commit_clamped`]
414 /// instead -- refusing there would be a stricter rule than the mouse door
415 /// enforces.
416 #[allow(dead_code)] // as above: `commit_clamped` is the transition row's door
417 pub(crate) fn commit(&mut self) -> Option<u32> {
418 match self.text.parse::<u32>() {
419 Ok(v) if (self.min..=self.max).contains(&v) => {
420 self.refusal = None;
421 Some(v)
422 }
423 Ok(0) => {
424 self.refusal = Some(format!(
425 "0 is not a value — {}–{} {}",
426 self.min, self.max, self.unit
427 ));
428 None
429 }
430 Ok(v) => {
431 self.refusal = Some(format!(
432 "{v} is past the {} {} ceiling",
433 self.max, self.unit
434 ));
435 None
436 }
437 Err(_) => {
438 self.refusal = Some(format!(
439 "type a number — {}–{} {}",
440 self.min, self.max, self.unit
441 ));
442 None
443 }
444 }
445 }
446
447 /// The number, clamped into range instead of refused -- for a row whose
448 /// own stepper already clamps silently (the transition duration's setter
449 /// clamps to the clips' shared length), so a typed number lands exactly
450 /// where that same stepper would have walked it to. Always succeeds.
451 pub(crate) fn commit_clamped(&mut self) -> u32 {
452 let v = self.text.parse::<u32>().unwrap_or(self.min);
453 self.refusal = None;
454 v.clamp(self.min, self.max)
455 }
456
457 /// What the row shows while it is being typed into: the digits, the caret
458 /// that says they are landing *here*, and either the refusal or the two
459 /// keys that end the edit.
460 pub(crate) fn detail(&self) -> String {
461 format!(
462 "{}▏ {} — {}",
463 self.text,
464 self.unit,
465 match &self.refusal {
466 Some(why) => why.as_str(),
467 None => "enter commits · esc cancels",
468 }
469 )
470 }
471}
472
473/// How much text the colour field will hold: `rgba(255, 255, 255, 255)` with
474/// room to spare. Every legal colour is far inside it; the cap is there so a
475/// held key cannot grow the buffer without bound.
476const COLOR_EDIT_CHARS: usize = 32;
477
478/// A colour being typed into a row that has no text field of its own: the
479/// free-text sibling of [`NumberEdit`], for the same reason it exists -- these
480/// rows take no gpui focus, so the text is held as state and driven by the
481/// root's key handler. One caller, the Clip tab's colour field
482/// ([`Player::edit_viz_hex`]): typing, backspace, enter that commits and
483/// escape that gives up, and a refusal in words when what is there is not a
484/// colour.
485#[derive(Clone, Debug, PartialEq, Eq)]
486pub(crate) struct ColorEdit {
487 pub(crate) text: String,
488 pub(crate) refusal: Option<String>,
489}
490
491impl ColorEdit {
492 /// Starts on the colour the row already shows, so backspace edits it
493 /// rather than the field opening empty over a colour still in force
494 /// ([`NumberEdit::new`]'s own rule).
495 pub(crate) fn new(seed: &str) -> Self {
496 ColorEdit {
497 text: seed.to_string(),
498 refusal: None,
499 }
500 }
501
502 /// One printable stroke. The one past the cap is refused *out loud*: a
503 /// keystroke dropped in silence is what leaves a field showing something
504 /// the user did not type ([`NumberEdit::digit`]'s own reason).
505 pub(crate) fn typed(&mut self, c: char) {
506 if self.text.chars().count() >= COLOR_EDIT_CHARS {
507 self.refusal = Some(format!("{COLOR_EDIT_CHARS} characters is already past the field"));
508 return;
509 }
510 self.text.push(c);
511 self.refusal = None;
512 }
513
514 /// Erases the last character, and the refusal with it: the text on screen
515 /// has changed, so the reason the old one was refused no longer describes
516 /// it.
517 pub(crate) fn backspace(&mut self) {
518 self.text.pop();
519 self.refusal = None;
520 }
521
522 /// The colour, or `None` with the reason recorded where the row will read
523 /// it. Only the shapes the paint field can carry are read at all
524 /// (`engine::decode::viz_color_from_text`); anything else is refused
525 /// rather than guessed at, and the refusal says what a colour looks like
526 /// so the next try is a backspace away.
527 pub(crate) fn commit(&mut self) -> Option<(u8, u8)> {
528 match engine::decode::viz_color_from_text(&self.text) {
529 Some(hue_sat) => {
530 self.refusal = None;
531 Some(hue_sat)
532 }
533 None => {
534 self.refusal = Some("type a colour — #RRGGBB or rgb(r,g,b)".to_string());
535 None
536 }
537 }
538 }
539
540 /// What the row shows while it is being typed into: the text, the caret
541 /// that says it is landing *here*, and either the refusal or the two keys
542 /// that end the edit.
543 pub(crate) fn detail(&self) -> String {
544 format!(
545 "{}▏ {}",
546 self.text,
547 match &self.refusal {
548 Some(why) => why.as_str(),
549 None => "enter commits · esc cancels",
550 }
551 )
552 }
553}
554
555/// What a window with no file open shows: DESIGN §8 wants a noun, not a
556/// sentence -- both ways in (window drop target, Import in the media list)
557/// are taught by their own geography, not by this label.
558pub(crate) fn empty_hint() -> impl IntoElement {
559 div()
560 .flex()
561 .flex_col()
562 .items_center()
563 .gap(px(6.))
564 .text_color(rgb(FG_SECONDARY()))
565 .child("No project")
566}