Skip to main content

makeover_immediate/
piece.rs

1//! The described things that are not fields, tables or frames, and carry no
2//! vocabulary member: a token and a wait.
3//!
4//! The vocabulary members (a meter, a control, facts, a figure, a chart) are
5//! drawn by `quasi-immediate` with the [`PieceStyle`] held here.
6//! `makeover-tui`'s `piece` module is the same split for a terminal.
7//!
8//! A wait draws a bar only when something is counting it. Every function here
9//! draws into the `Ui` it is given and hands back a [`Response`]. Nothing here
10//! takes a `focused` flag: egui owns focus.
11
12use egui::{Response, RichText, Sense, Ui, Vec2};
13use makeover_layout::{Awaiting, Token, Tone, progress_reading};
14use makeover_timing::{MotionPreference, blink};
15use std::time::Duration;
16
17use crate::Palette;
18
19/// The sizes a widget cannot derive from the description.
20///
21/// Every size arrives from the caller, as in
22/// [`FrameStyle`](crate::FrameStyle) and [`FieldStyle`](crate::FieldStyle).
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct PieceStyle {
25    /// How tall a meter's bar is drawn.
26    pub meter_height: f32,
27    /// How wide a meter's bar runs, or `None` (the default) to take the width
28    /// on offer.
29    pub meter_width: Option<f32>,
30    /// How tall a chart stands, in points.
31    ///
32    /// Separate from [`meter_height`](Self::meter_height). 200 by default,
33    /// `makeover-webview`'s `--chart-height` default.
34    pub chart_height: f32,
35    /// The corner radius on a meter's trough and on a token.
36    pub radius: u8,
37    /// Inside a token, around its label.
38    pub token_padding: Vec2,
39    /// Between a figure's value and its caption.
40    pub figure_gap: f32,
41    /// How much larger a figure's value is drawn than the body text.
42    ///
43    /// A multiplier on the app's text style, not a size.
44    pub figure_scale: f32,
45    /// The side of the activity mark, square.
46    pub mark_size: f32,
47}
48
49impl Default for PieceStyle {
50    /// Bars at 6pt taking the width on offer, a figure at double text size, and
51    /// the activity mark a square a little larger than a bar is tall.
52    fn default() -> Self {
53        Self {
54            meter_height: 6.0,
55            meter_width: None,
56            chart_height: 200.0,
57            radius: 3,
58            token_padding: Vec2::new(6.0, 2.0),
59            figure_gap: 2.0,
60            figure_scale: 2.0,
61            mark_size: 8.0,
62        }
63    }
64}
65
66/// A badge or a chip.
67///
68/// A badge is the table model's (wiki `table-model`), as `makeover-webview`
69/// draws it: a fill of its tone surface inside a one-point edge in its tone,
70/// the label in content ink. A neutral badge fills with the raised surface and
71/// takes the border for its edge. The tone is never the ink.
72///
73/// A chip is outlined in its tone, and filled while latched.
74///
75/// A chip senses clicks and a badge senses hover only
76/// ([`Token::interactive`]); the `Response` comes back either way.
77///
78/// `latched` is a chip that is switched on, and it fills rather than outlines.
79/// Both kinds are drawn with [`PieceStyle::radius`], so a badge and a chip
80/// have the same corners. A chip's removable half is not drawn.
81pub fn token(
82    ui: &mut Ui,
83    label: &str,
84    kind: Token,
85    tone: Tone,
86    latched: bool,
87    palette: &Palette,
88    style: &PieceStyle,
89) -> Response {
90    let painted = palette.tone(tone);
91    let radius = style.radius;
92    let sense = if kind.interactive() {
93        Sense::click()
94    } else {
95        Sense::hover()
96    };
97
98    // Laid out before the rect is allocated, because a token is exactly as wide
99    // as what it says plus its padding: there is no box to fit text into here,
100    // the way a table cell has one.
101    // A token's words are content ink. A status colour is a fill, an edge or
102    // a glyph, never the colour of words (wiki `quasi-vocabulary-findings`,
103    // toned text), so the tone stays on the outline and a latched toned chip
104    // fills from the tone's surface the way a badge does. A latched neutral
105    // chip keeps its inverted fill: it carries no status, and the inversion is
106    // what tells it from one at rest.
107    let neutral = tone == Tone::Neutral;
108    let ink = match kind {
109        Token::Chip { .. } if latched && neutral => palette.page,
110        _ => palette.content,
111    };
112    let galley = ui.painter().layout_no_wrap(
113        label.to_owned(),
114        egui::TextStyle::Body.resolve(ui.style()),
115        ink,
116    );
117    let size = galley.size() + style.token_padding * 2.0;
118    let (rect, response) = ui.allocate_exact_size(size, sense);
119
120    if kind == Token::Badge {
121        ui.painter().rect(
122            rect,
123            radius,
124            palette.tone_surface(tone),
125            egui::Stroke::new(1.0, palette.tone_edge(tone)),
126            egui::StrokeKind::Inside,
127        );
128    } else if latched && neutral {
129        ui.painter().rect_filled(rect, radius, painted);
130    } else if latched {
131        ui.painter().rect(
132            rect,
133            radius,
134            palette.tone_surface(tone),
135            egui::Stroke::new(1.0, painted),
136            egui::StrokeKind::Inside,
137        );
138    } else {
139        ui.painter().rect_stroke(
140            rect,
141            radius,
142            egui::Stroke::new(1.0, painted),
143            egui::StrokeKind::Inside,
144        );
145    }
146    ui.painter()
147        .galley(rect.center() - galley.size() / 2.0, galley, ink);
148
149    // Say what was drawn, because painting it says nothing.
150    //
151    // A token allocates its rect and paints the text straight onto it, so
152    // nothing reaches the accessibility tree unless it is said here: an
153    // interactive chip would be a control a mouse can press and a screen reader
154    // cannot find, and a badge text nobody can read out.
155    //
156    // A chip that latches says so through `selected`, which is what a screen
157    // reader announces as pressed. That is `latched`'s whole meaning: the key
158    // is held down.
159    let role = if kind.interactive() {
160        egui::WidgetType::Button
161    } else {
162        egui::WidgetType::Label
163    };
164    response.widget_info(|| {
165        let mut info = egui::WidgetInfo::labeled(role, ui.is_enabled(), label);
166        if kind.interactive() {
167            info.selected = Some(latched);
168        }
169        info
170    });
171    response
172}
173
174/// What a host can see about a wait that is running.
175pub use makeover_layout::Progress;
176
177/// The activity mark: one small square, blinking.
178///
179/// Rule 2 of wiki `loading-and-progress-standard`. Lit, it is the action
180/// colour; dark, the sunken surface, in the same square.
181///
182/// [`MotionPreference::Reduced`] stills the mark lit; egui has no
183/// `prefers-reduced-motion`, so the host passes what its platform reports.
184/// The phase is `makeover_timing::blink`'s, and a repaint is requested for
185/// the next flip rather than every frame.
186pub fn activity(
187    ui: &mut Ui,
188    motion: MotionPreference,
189    palette: &Palette,
190    style: &PieceStyle,
191) -> Response {
192    let (rect, response) = ui.allocate_exact_size(Vec2::splat(style.mark_size), Sense::hover());
193    let elapsed = Duration::try_from_secs_f64(ui.input(|input| input.time)).unwrap_or_default();
194    let (lit, until) = blink(elapsed, motion);
195    if let Some(until) = until {
196        ui.ctx().request_repaint_after(until);
197    }
198    // Lit is the accent, dark is the trough it sits in. Not "drawn and not
199    // drawn": a mark that vanishes half the time is a hole in the layout, and
200    // the reader loses where to look between blinks.
201    let colour = if lit { palette.action } else { palette.sunken };
202    ui.painter().rect_filled(rect, style.radius, colour);
203    response
204}
205
206/// A wait, drawn from what is actually known about it.
207///
208/// No amount: the activity mark. An amount with no [`Progress::delivered`]:
209/// the mark and the total. Both: a bar and its reading, what is done over
210/// what there is plus the time it has taken (rule 1 of wiki
211/// `loading-and-progress-standard`), with no remaining time, arrival time or
212/// rate. The numbers are raw, with no unit.
213///
214/// With no [`PieceStyle::meter_width`] the bar takes the width left after the
215/// reading.
216pub fn awaiting(
217    ui: &mut Ui,
218    awaiting: Awaiting,
219    progress: Progress,
220    motion: MotionPreference,
221    palette: &Palette,
222    style: &PieceStyle,
223) -> Response {
224    let Some(total) = awaiting.amount else {
225        return activity(ui, motion, palette, style);
226    };
227    let Some(done) = progress.delivered else {
228        // Known size, nothing counting it: the mark, and the total beside it
229        // in the reading's ink, so the reader learns how much is coming.
230        return ui
231            .horizontal(|ui| {
232                let mark = activity(ui, motion, palette, style);
233                ui.label(RichText::new(total.to_string()).color(palette.content_muted));
234                mark
235            })
236            .inner;
237    };
238    let reading = progress_reading(done, total, progress.elapsed);
239    // With no width asked for, the bar takes what is left after the reading and
240    // the gap before it, so the reading stays on screen. Taking all of the
241    // available width pushed it past the edge.
242    let width = style.meter_width.unwrap_or_else(|| {
243        let text = RichText::new(&reading).color(palette.content_muted);
244        let galley = egui::WidgetText::from(text).into_galley(
245            ui,
246            Some(egui::TextWrapMode::Extend),
247            f32::INFINITY,
248            egui::TextStyle::Body,
249        );
250        (ui.available_width() - galley.size().x - ui.spacing().item_spacing.x).max(1.0)
251    });
252    ui.horizontal(|ui| {
253        let (rect, response) =
254            ui.allocate_exact_size(Vec2::new(width, style.meter_height), Sense::hover());
255        ui.painter().rect_filled(rect, style.radius, palette.sunken);
256        // A total of zero is no payload rather than a finished one, which is a
257        // meter's reading of the same case. Over-delivery clamps because a rect
258        // cannot be longer than itself.
259        let share = if total == 0 {
260            0.0
261        } else {
262            #[expect(
263                clippy::cast_precision_loss,
264                reason = "a byte count past 2^53 is not a wait anyone is watching a bar for"
265            )]
266            let share = (done as f64 / total as f64).min(1.0);
267            share
268        };
269        #[expect(
270            clippy::cast_possible_truncation,
271            reason = "a share is 0..=1 and the product is a width in points"
272        )]
273        let filled = (f64::from(rect.width()) * share) as f32;
274        if filled > 0.0 {
275            let mut fill = rect;
276            fill.set_width(filled);
277            ui.painter().rect_filled(fill, style.radius, palette.action);
278        }
279        ui.label(RichText::new(reading).color(palette.content_muted));
280        response
281    })
282    .inner
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use crate::tests::palette;
289
290    /// What the accessibility tree says a widget drew.
291    fn announced(
292        draw: impl FnMut(&mut Ui),
293    ) -> Vec<(
294        egui::accesskit::Role,
295        String,
296        Option<egui::accesskit::Toggled>,
297    )> {
298        let ctx = egui::Context::default();
299        ctx.enable_accesskit();
300        let mut draw = draw;
301        let input = || egui::RawInput {
302            screen_rect: Some(egui::Rect::from_min_size(
303                egui::Pos2::ZERO,
304                egui::vec2(600.0, 400.0),
305            )),
306            ..Default::default()
307        };
308        // A frame's texture changes are the host's to upload, and egui 0.36
309        // refuses to have them dropped unread. No host here, so they are
310        // cleared by hand.
311        ctx.run_ui(input(), &mut draw).textures_delta.clear();
312        let mut out = ctx.run_ui(input(), &mut draw);
313        out.textures_delta.clear();
314        out.platform_output
315            .accesskit_update
316            .expect("accesskit is on")
317            .nodes
318            .iter()
319            .map(|(_, node)| {
320                (
321                    node.role(),
322                    node.label()
323                        .or_else(|| node.value())
324                        .unwrap_or_default()
325                        .to_owned(),
326                    node.toggled(),
327                )
328            })
329            .collect()
330    }
331
332    /// The colour each run of words was painted in, by its text.
333    fn inked(draw: impl FnMut(&mut Ui)) -> Vec<(String, egui::Color32)> {
334        fn walk(shape: &egui::Shape, out: &mut Vec<(String, egui::Color32)>) {
335            match shape {
336                egui::Shape::Text(t) => {
337                    let format = t.galley.job.sections.first().map(|s| s.format.color);
338                    let colour = format
339                        .filter(|c| *c != egui::Color32::PLACEHOLDER)
340                        .unwrap_or(t.fallback_color);
341                    out.push((t.galley.job.text.clone(), colour));
342                }
343                egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)),
344                _ => {}
345            }
346        }
347        let ctx = egui::Context::default();
348        let mut draw = draw;
349        let input = egui::RawInput {
350            screen_rect: Some(egui::Rect::from_min_size(
351                egui::Pos2::ZERO,
352                egui::vec2(600.0, 400.0),
353            )),
354            ..Default::default()
355        };
356        let mut output = ctx.run_ui(input, &mut draw);
357        output.textures_delta.clear();
358        let mut out = Vec::new();
359        for clipped in &output.shapes {
360            walk(&clipped.shape, &mut out);
361        }
362        out
363    }
364
365    #[test]
366    fn a_toned_tokens_words_are_content_whether_or_not_it_is_latched() {
367        // Toned text ruling: a status colour is a fill or an edge, never words.
368        let p = palette();
369        let style = PieceStyle::default();
370        for kind in [Token::Badge, Token::Chip { removable: false }] {
371            for latched in [false, true] {
372                let drawn = inked(|ui| {
373                    token(ui, "overdue", kind, Tone::Danger, latched, &p, &style);
374                });
375                let (_, colour) = drawn
376                    .iter()
377                    .find(|(text, _)| text == "overdue")
378                    .unwrap_or_else(|| panic!("nothing painted: {drawn:?}"));
379                assert_eq!(*colour, p.content, "{kind:?} latched {latched}");
380            }
381        }
382    }
383
384    #[test]
385    fn a_chip_is_announced_as_a_control_and_says_whether_it_is_held() {
386        // A token paints its own text onto its own rect, so without saying what
387        // it drew it reaches the tree as nothing: pressable by a mouse and
388        // invisible to everything else.
389        let p = palette();
390        let style = PieceStyle::default();
391        let drawn = announced(|ui| {
392            token(
393                ui,
394                "C#",
395                Token::Chip { removable: false },
396                Tone::Neutral,
397                true,
398                &p,
399                &style,
400            );
401        });
402
403        let chip = drawn
404            .iter()
405            .find(|(role, name, _)| *role == egui::accesskit::Role::Button && name == "C#")
406            .unwrap_or_else(|| panic!("the chip is not in the tree: {drawn:?}"));
407        assert_eq!(
408            chip.2,
409            Some(egui::accesskit::Toggled::True),
410            "a latched chip is held down and says so: {drawn:?}"
411        );
412    }
413
414    #[test]
415    fn a_badge_is_announced_as_the_text_it_is() {
416        // Not a control, and not nothing either: a badge is a word on the
417        // screen and painting it is not the same as saying it.
418        let p = palette();
419        let style = PieceStyle::default();
420        let drawn = announced(|ui| {
421            token(ui, "wav", Token::Badge, Tone::Neutral, false, &p, &style);
422        });
423
424        assert!(
425            drawn
426                .iter()
427                .any(|(role, name, _)| *role == egui::accesskit::Role::Label && name == "wav"),
428            "{drawn:?}"
429        );
430        assert!(
431            !drawn
432                .iter()
433                .any(|(role, _, _)| *role == egui::accesskit::Role::Button),
434            "a badge answers nothing and must not claim to: {drawn:?}"
435        );
436    }
437
438    #[test]
439    fn every_tone_resolves_and_no_two_share_a_colour() {
440        // The reason the three status intents arrived together: a resolver
441        // missing one has to invent a colour for it.
442        let p = palette();
443        let all = [
444            p.tone(Tone::Neutral),
445            p.tone(Tone::Info),
446            p.tone(Tone::Success),
447            p.tone(Tone::Warning),
448            p.tone(Tone::Danger),
449        ];
450        for (i, a) in all.iter().enumerate() {
451            for b in &all[i + 1..] {
452                assert_ne!(a, b, "two tones resolved to one colour");
453            }
454        }
455        assert_eq!(p.tone(Tone::Neutral), p.content, "neutral is ordinary text");
456    }
457
458    #[test]
459    fn a_wait_draws_a_bar_only_when_something_is_counting_it() {
460        // The described total is half of what a bar needs. Without a numerator
461        // the honest drawing is the mark, not an empty trough implying that
462        // someone is watching bytes land.
463        let p = palette();
464        let style = PieceStyle::default();
465        egui::__run_test_ui(|ui| {
466            awaiting(
467                ui,
468                Awaiting::unmeasured(),
469                Progress::default(),
470                MotionPreference::Full,
471                &p,
472                &style,
473            );
474            awaiting(
475                ui,
476                Awaiting::of(41_943_040),
477                Progress::default(),
478                MotionPreference::Full,
479                &p,
480                &style,
481            );
482            awaiting(
483                ui,
484                Awaiting::of(41_943_040),
485                Progress {
486                    delivered: Some(10_485_760),
487                    elapsed: Some(Duration::from_secs(3)),
488                },
489                MotionPreference::Full,
490                &p,
491                &style,
492            );
493            // A zero payload is no payload, and over-delivery clamps.
494            awaiting(
495                ui,
496                Awaiting::of(0),
497                Progress {
498                    delivered: Some(9),
499                    elapsed: None,
500                },
501                MotionPreference::Full,
502                &p,
503                &style,
504            );
505            awaiting(
506                ui,
507                Awaiting::of(4),
508                Progress {
509                    delivered: Some(9),
510                    elapsed: None,
511                },
512                MotionPreference::Full,
513                &p,
514                &style,
515            );
516        });
517    }
518
519    #[test]
520    fn reduced_motion_stills_the_mark_and_does_not_remove_it() {
521        // `activity_blink(Reduced)` is None, which means lit and still. A renderer
522        // that drew nothing would have answered a request nobody made.
523        let p = palette();
524        let style = PieceStyle::default();
525        egui::__run_test_ui(|ui| {
526            let still = activity(ui, MotionPreference::Reduced, &p, &style);
527            let blinking = activity(ui, MotionPreference::Full, &p, &style);
528            assert_eq!(
529                still.rect.size(),
530                blinking.rect.size(),
531                "the mark occupies the same space either way"
532            );
533        });
534    }
535
536    #[test]
537    fn a_chip_answers_a_click_and_a_badge_does_not() {
538        // `Token::interactive` is the whole difference between the members, and
539        // the sense is what makes egui agree with it.
540        let p = palette();
541        let style = PieceStyle::default();
542        egui::__run_test_ui(|ui| {
543            let badge = token(ui, "beta", Token::Badge, Tone::Info, false, &p, &style);
544            assert!(!badge.sense.senses_click(), "a badge answers no click");
545
546            let chip = token(
547                ui,
548                "drums",
549                Token::Chip { removable: false },
550                Tone::Neutral,
551                false,
552                &p,
553                &style,
554            );
555            assert!(chip.sense.senses_click(), "a chip answers a click");
556        });
557    }
558
559    #[test]
560    fn an_unwatched_measured_wait_draws_the_mark_and_the_total() {
561        // A described amount with nothing delivered yet: the mark, then the
562        // total in the reading's ink. No bar, since nothing is counting.
563        let ctx = egui::Context::default();
564        ctx.set_fonts(egui::FontDefinitions::default());
565        let p = palette();
566        let style = PieceStyle::default();
567        let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
568            awaiting(
569                ui,
570                Awaiting::of(41_943_040),
571                Progress::default(),
572                MotionPreference::Reduced,
573                &p,
574                &style,
575            );
576        });
577        let shapes = std::mem::take(&mut output.shapes);
578        output.drop_without_applying_deltas();
579        let texts: Vec<(String, egui::Color32)> = shapes
580            .iter()
581            .filter_map(|clipped| match &clipped.shape {
582                egui::Shape::Text(text) => Some((
583                    text.galley.text().to_owned(),
584                    text.galley.job.sections.first()?.format.color,
585                )),
586                _ => None,
587            })
588            .collect();
589        let rects = shapes
590            .iter()
591            .filter(|clipped| matches!(clipped.shape, egui::Shape::Rect(_)))
592            .count();
593        assert_eq!(texts.len(), 1, "{texts:?}");
594        assert_eq!(texts[0].0, "41943040");
595        assert_eq!(texts[0].1, p.content_muted, "the reading's ink");
596        assert_eq!(rects, 1, "the mark alone, no trough");
597    }
598
599    #[test]
600    fn a_wait_keeps_its_reading_inside_the_panel() {
601        // A bar that takes all of the available width leaves the reading nowhere
602        // to go, so it lands past the panel edge. Real fonts, because the
603        // reading's width is what the bar has to make room for, and the test
604        // harness otherwise loads none. One pass, because egui grows a viewport
605        // to fit its content and would otherwise hide the overflow.
606        let ctx = egui::Context::default();
607        ctx.set_fonts(egui::FontDefinitions::default());
608        ctx.memory_mut(|m| m.options.max_passes = std::num::NonZeroUsize::new(1).unwrap());
609        let p = palette();
610        let style = PieceStyle::default();
611        let mut used = 0.0f32;
612        let mut budget = 0.0f32;
613        let input = egui::RawInput {
614            screen_rect: Some(egui::Rect::from_min_size(
615                egui::Pos2::ZERO,
616                egui::Vec2::new(300.0, 400.0),
617            )),
618            ..Default::default()
619        };
620        let output = ctx.run_ui(input, |ui| {
621            let left = ui.min_rect().left();
622            budget = ui.available_width();
623            awaiting(
624                ui,
625                Awaiting::of(41_943_040),
626                Progress {
627                    delivered: Some(10_485_760),
628                    elapsed: Some(Duration::from_secs(3)),
629                },
630                MotionPreference::Full,
631                &p,
632                &style,
633            );
634            used = ui.min_rect().right() - left;
635        });
636        output.drop_without_applying_deltas();
637        assert!(
638            used <= budget + 0.5,
639            "the bar and its reading drew to {used}, past the {budget}pt on offer"
640        );
641    }
642}