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