Skip to main content

egui_pop_core/
indicator.rs

1//! Micro-indicators: the small marks that say a state in very little
2//! space, beside or on another widget. Six kinds need nothing but the
3//! theme, plus icons that follow a state:
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! - a **dot** or an **LED** ([`Led`]: off, on, busy, warning, error),
9//!   each state with a shape of its own (hollow, filled, pulsing, a
10//!   triangle, a square);
11//! - a **badge**: a count capped at `99+` (zero hidden unless asked),
12//!   or a short text;
13//! - an **activity pip** ([`Pip`]): a spinner, a ring, done, failed;
14//! - a **flag** ([`Flag`]: modified, pinned, required, invalid, or a
15//!   [`FlagShape`] of the application's): a corner triangle, a stripe,
16//!   a diamond, a triangle, a square, an asterisk;
17//! - a **swatch** ([`Swatch`]): a colour over egui's alpha checkerboard,
18//!   no colour (a slash), or mixed (a dash);
19//! - a **dynamic icon**: a built-in [`Icon`], or one of two by a state;
20//! - a **value's mark** ([`ValueMark`]): changed from its default (a
21//!   dot), held by another party (a square), moved by another party (a
22//!   diamond), drawn as the dot and the flags are.
23//!
24//! They are drawn by the kit (`docs/kit.md`) like every other
25//! component: `indicator-dot`, `indicator-badge`, `indicator-flag`,
26//! `indicator-swatch`, `indicator-outline` and `indicator-button` (the
27//! target of an interactive mark), with pips on `spinner` and
28//! `progress-ring`. Colours follow the kit's one [`Tone`]. The shapes of
29//! the LEDs and of the named flags are the kit's glyph roles
30//! (`glyph.led-*`, `glyph.flag-*`), which a kit remaps to any icon; the
31//! kit refuses two states that would share a shape
32//! (`egui_pop_tokens::kit::DISTINCT_GLYPHS`). A state is never said by
33//! colour alone: each has a shape, a glyph or a text, and a name.
34//!
35//! **Passive by default.** A passive mark takes no click and no focus.
36//! On a widget ([`Indicator::on`], [`IndicatorExt::with_indicator`]) its
37//! meaning joins that widget's accessible name ("Notifications, 3");
38//! inline ([`Ui::add`]) it is read as an image with its meaning for a
39//! name. Its tooltip says the meaning too.
40//!
41//! **Interactive** ([`Indicator::interactive`]): the button rules of
42//! egui-pop, a target of at least `indicator.target` (24 points) around
43//! the mark, the focus ring, Space and Enter, a tooltip, an AccessKit
44//! node of its own (a button, or a check box for an icon that toggles)
45//! whose description is the mark's meaning, a reason when disabled, and
46//! a command ([`Indicator::command`]) that the application runs.
47//!
48//! **Anchoring.** Inline with `ui.add`, or on any rectangle with
49//! [`Indicator::paint_at`]: a corner, the start or end edge (centred
50//! vertically) or the centre ([`Anchor`]). Start and end follow the
51//! [`Direction`] (left to right unless set). Badges and dots overhang a
52//! corner by half their height and are drawn on a layer of their own
53//! just above the host's, never clipped; the others sit inside.
54//!
55//! **Motion.** A busy LED pulses; any mark can call attention after a
56//! change ([`Indicator::attention`]) for `indicator.pulse.count` pulses.
57//! The pulse runs on the motion clock (a frozen clock gives the same
58//! frame), and under reduced motion it is a still ring instead.
59//!
60//! **Agents.** Marks with an id ([`Indicator::id`]) are recorded each
61//! pass: [`drawn`] lists them, and the debug bridge's `indicators`
62//! collector shows them as JSON ([`Record`]), so an agent reads states
63//! instead of pixels.
64//!
65//! ```
66//! use egui_pop_core::icon::Icon;
67//! use egui_pop_core::indicator::{Anchor, Indicator, IndicatorExt as _, Led, Pip, Tone};
68//!
69//! fn status(ui: &mut egui::Ui, unread: u64, rendering: bool) {
70//!     // Passive, inline: read as "On".
71//!     ui.add(Indicator::led(Led::On).id("node").tooltip("Node connected"));
72//!     if rendering {
73//!         ui.add(Indicator::pip(Pip::Busy).name("Rendering"));
74//!     }
75//!     // On a button's corner: the button reads "Notifications, 3".
76//!     ui.add(Icon::Notification.label("Notifications").sense_click())
77//!         .with_indicator(ui, Indicator::count(unread).tone(Tone::Danger), Anchor::TopEnd);
78//!     // Interactive: a button of its own.
79//!     if ui
80//!         .add(Indicator::dot(Tone::Accent).name("Changed").interactive("Reset exposure"))
81//!         .clicked()
82//!     { /* reset */ }
83//! }
84//! ```
85
86use std::sync::{Arc, Mutex};
87
88use egui::{
89    Color32, Context, CornerRadius, FontId, Id, LayerId, Painter, Pos2, Rect, Response, Role,
90    Sense, Shape, Stroke, Ui, Vec2, Widget, WidgetInfo, pos2, vec2,
91};
92use egui_pop_model::ids::CommandId;
93use serde::Serialize;
94
95use crate::icon::{Icon, IconRef};
96pub use crate::kit::Tone;
97use crate::kit::{BoxStyle, Corners, Glyph, Kit, KitCx, Part, State, paint_ring};
98use crate::motion;
99use crate::state::{lock, pass, shared};
100use crate::strings::{self, StrKey};
101use crate::theme::Tokens;
102
103/// A badge's cap by default: `99+` past it.
104pub const CAP: u64 = 99;
105
106/// The smallest target of an interactive mark, whatever the kit says
107/// (WCAG 2.5.8).
108pub const MIN_TARGET: f32 = 24.0;
109
110/// The sizes and times a mark is laid out with, read from the installed
111/// kit (`indicator-*`, `progress-ring`) and the system tokens: fields,
112/// no lookup by name.
113#[derive(Clone, Debug, PartialEq)]
114struct Looks {
115    /// `indicator-dot.width`.
116    dot: f32,
117    /// `indicator-dot.rest.border-width`: an LED that is off, a pulse.
118    ring: f32,
119    /// `indicator-flag.width`.
120    flag: f32,
121    /// `indicator-swatch.width`.
122    swatch: f32,
123    /// `indicator-badge.height` and `padding-x`.
124    badge_height: f32,
125    badge_padding: f32,
126    /// `indicator-badge.font-size` (egui's small text when not given).
127    badge_font: f32,
128    /// `progress-ring.width`.
129    pip: f32,
130    /// `size.icon.inline`.
131    icon: f32,
132    /// `indicator-button.width` and `height`, never under
133    /// [`MIN_TARGET`].
134    target: Vec2,
135    /// `space.xs`: how far a mark inside a corner sits from it.
136    offset: f32,
137    /// `motion.pulse.period` (seconds) and `motion.pulse.count`.
138    pulse_period: f32,
139    pulse_count: u32,
140}
141
142impl Looks {
143    fn of(ctx: &Context) -> Looks {
144        let kit = Kit::of(ctx);
145        let t = Tokens::of(ctx);
146        Looks {
147            dot: kit.indicator_dot.data.width.max(4.0),
148            ring: kit.indicator_dot.style(State::REST).border_width.max(1.0),
149            flag: kit.indicator_flag.data.width.max(4.0),
150            swatch: kit.indicator_swatch.data.width.max(6.0),
151            badge_height: kit.indicator_badge.data.height.max(10.0),
152            badge_padding: kit.indicator_badge.data.padding_x.max(0.0),
153            badge_font: if kit.indicator_badge.data.font_size > 0.0 {
154                kit.indicator_badge.data.font_size
155            } else {
156                t.font.small
157            }
158            .max(6.0),
159            pip: kit.progress_ring.data.width.max(8.0),
160            icon: t.size.icon_inline,
161            target: vec2(
162                kit.indicator_button.data.width.max(MIN_TARGET),
163                kit.indicator_button.data.height.max(MIN_TARGET),
164            ),
165            offset: t.space.xs.max(0.0),
166            pulse_period: t.motion.pulse_period.max(0.0),
167            pulse_count: t.motion.pulse_count,
168        }
169    }
170}
171
172/// A size step (never points): the tokens' sizes scaled.
173#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
174#[serde(rename_all = "snake_case")]
175pub enum Size {
176    Small,
177    #[default]
178    Regular,
179    Large,
180}
181
182impl Size {
183    pub const ALL: [Size; 3] = [Size::Small, Size::Regular, Size::Large];
184
185    pub fn factor(self) -> f32 {
186        match self {
187            Size::Small => 0.75,
188            Size::Regular => 1.0,
189            Size::Large => 1.5,
190        }
191    }
192}
193
194/// An LED's state; each has its own shape and default tone.
195#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
196#[serde(rename_all = "snake_case")]
197pub enum Led {
198    /// A hollow ring (`indicator.led.off`).
199    Off,
200    /// Filled (success).
201    On,
202    /// Filled and pulsing (accent); a still ring under reduced motion.
203    Busy,
204    /// A triangle (warning).
205    Warning,
206    /// A square (danger).
207    Error,
208}
209
210impl Led {
211    pub const ALL: [Led; 5] = [Led::Off, Led::On, Led::Busy, Led::Warning, Led::Error];
212
213    pub fn tone(self) -> Tone {
214        match self {
215            Led::Off => Tone::Muted,
216            Led::On => Tone::Success,
217            Led::Busy => Tone::Accent,
218            Led::Warning => Tone::Warning,
219            Led::Error => Tone::Danger,
220        }
221    }
222
223    pub fn name(self) -> &'static str {
224        match self {
225            Led::Off => "off",
226            Led::On => "on",
227            Led::Busy => "busy",
228            Led::Warning => "warning",
229            Led::Error => "error",
230        }
231    }
232
233    /// The kit's glyph role for its shape (`glyph.led-*`).
234    pub fn glyph(self) -> Glyph {
235        match self {
236            Led::Off => Glyph::LedOff,
237            Led::On => Glyph::LedOn,
238            Led::Busy => Glyph::LedBusy,
239            Led::Warning => Glyph::LedWarning,
240            Led::Error => Glyph::LedError,
241        }
242    }
243
244    fn key(self) -> StrKey {
245        match self {
246            Led::Off => strings::INDICATOR_OFF,
247            Led::On => strings::INDICATOR_ON,
248            Led::Busy => strings::BUSY,
249            Led::Warning => strings::INDICATOR_WARNING,
250            Led::Error => strings::INDICATOR_ERROR,
251        }
252    }
253}
254
255/// An activity pip's state.
256#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
257#[serde(rename_all = "snake_case")]
258pub enum Pip {
259    /// A turning arc (still under reduced motion).
260    Busy,
261    /// A ring filled from the top, 0 to 1.
262    Progress(f32),
263    /// A tick (success).
264    Done,
265    /// A cross in a circle (danger).
266    Failed,
267}
268
269impl Pip {
270    pub fn tone(self) -> Tone {
271        match self {
272            Pip::Busy | Pip::Progress(_) => Tone::Accent,
273            Pip::Done => Tone::Success,
274            Pip::Failed => Tone::Danger,
275        }
276    }
277
278    pub fn name(self) -> &'static str {
279        match self {
280            Pip::Busy => "busy",
281            Pip::Progress(_) => "progress",
282            Pip::Done => "done",
283            Pip::Failed => "failed",
284        }
285    }
286}
287
288/// A flag's shape.
289#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
290#[serde(rename_all = "snake_case")]
291pub enum FlagShape {
292    /// A triangle filling a corner (on a corner anchor, that corner).
293    Corner,
294    /// A thin bar (on a start or end anchor, the host's height).
295    Stripe,
296    Diamond,
297    Triangle,
298    Square,
299    Asterisk,
300}
301
302impl FlagShape {
303    pub const ALL: [FlagShape; 6] = [
304        FlagShape::Corner,
305        FlagShape::Stripe,
306        FlagShape::Diamond,
307        FlagShape::Triangle,
308        FlagShape::Square,
309        FlagShape::Asterisk,
310    ];
311}
312
313/// The flags egui-pop names, each with its shape and tone.
314#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
315#[serde(rename_all = "snake_case")]
316pub enum Flag {
317    /// A corner triangle (accent).
318    Modified,
319    /// A diamond (info).
320    Pinned,
321    /// An asterisk (warning).
322    Required,
323    /// A triangle (danger).
324    Invalid,
325}
326
327impl Flag {
328    pub const ALL: [Flag; 4] = [Flag::Modified, Flag::Pinned, Flag::Required, Flag::Invalid];
329
330    pub fn shape(self) -> FlagShape {
331        match self {
332            Flag::Modified => FlagShape::Corner,
333            Flag::Pinned => FlagShape::Diamond,
334            Flag::Required => FlagShape::Asterisk,
335            Flag::Invalid => FlagShape::Triangle,
336        }
337    }
338
339    pub fn tone(self) -> Tone {
340        match self {
341            Flag::Modified => Tone::Accent,
342            Flag::Pinned => Tone::Info,
343            Flag::Required => Tone::Warning,
344            Flag::Invalid => Tone::Danger,
345        }
346    }
347
348    pub fn name(self) -> &'static str {
349        match self {
350            Flag::Modified => "modified",
351            Flag::Pinned => "pinned",
352            Flag::Required => "required",
353            Flag::Invalid => "invalid",
354        }
355    }
356
357    /// The kit's glyph role for its shape (`glyph.flag-*`); its
358    /// [`shape`](Flag::shape) is the default kit's.
359    pub fn glyph(self) -> Glyph {
360        match self {
361            Flag::Modified => Glyph::FlagModified,
362            Flag::Pinned => Glyph::FlagPinned,
363            Flag::Required => Glyph::FlagRequired,
364            Flag::Invalid => Glyph::FlagInvalid,
365        }
366    }
367
368    fn key(self) -> StrKey {
369        match self {
370            Flag::Modified => strings::INDICATOR_MODIFIED,
371            Flag::Pinned => strings::INDICATOR_PINNED,
372            Flag::Required => strings::INDICATOR_REQUIRED,
373            Flag::Invalid => strings::INDICATOR_INVALID,
374        }
375    }
376}
377
378/// A value's marks, beside the control showing it: it is not at its
379/// default, another party holds it, another party just moved it. Each
380/// has its shape and its meaning (in the current language), so none
381/// rests on colour alone:
382///
383/// - [`Changed`](ValueMark::Changed): a dot in the `accent` tone, "Changed
384///   from its default"; made [`interactive`](Indicator::interactive) it
385///   is the value's reset button;
386/// - [`Held`](ValueMark::Held): a square in the `warning` tone, "Held by
387///   …" (a binding, an automation, another module owns the value);
388/// - [`Moved`](ValueMark::Moved): a diamond in the `accent` tone, "Moved
389///   by …" (a gesture elsewhere, a script, a link changed it).
390#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
391#[serde(rename_all = "snake_case")]
392pub enum ValueMark {
393    Changed,
394    /// Held by whom (a name the user knows).
395    Held(String),
396    /// Moved by whom.
397    Moved(String),
398}
399
400impl ValueMark {
401    /// Its name for agents (`changed`, `held`, `moved`).
402    pub fn name(&self) -> &'static str {
403        match self {
404            ValueMark::Changed => "changed",
405            ValueMark::Held(_) => "held",
406            ValueMark::Moved(_) => "moved",
407        }
408    }
409
410    /// What it means, in the current language.
411    pub fn meaning(&self, ctx: &Context) -> String {
412        match self {
413            ValueMark::Changed => strings::tr(ctx, &strings::INDICATOR_CHANGED),
414            ValueMark::Held(by) => {
415                strings::tr_args(ctx, &strings::INDICATOR_HELD, &[("by", by.as_str())])
416            }
417            ValueMark::Moved(by) => {
418                strings::tr_args(ctx, &strings::INDICATOR_MOVED, &[("by", by.as_str())])
419            }
420        }
421    }
422
423    fn kind(&self) -> Kind {
424        match self {
425            ValueMark::Changed => Kind::Dot(None),
426            ValueMark::Held(_) => Kind::Flag(FlagShape::Square, None),
427            ValueMark::Moved(_) => Kind::Flag(FlagShape::Diamond, None),
428        }
429    }
430
431    fn tone(&self) -> Tone {
432        match self {
433            ValueMark::Changed | ValueMark::Moved(_) => Tone::Accent,
434            ValueMark::Held(_) => Tone::Warning,
435        }
436    }
437}
438
439/// What a swatch shows.
440#[derive(Clone, Copy, Debug, PartialEq)]
441pub enum Swatch {
442    /// A colour; under alpha, egui's checkerboard shows through.
443    Color(Color32),
444    /// No colour: a slash.
445    None,
446    /// Several colours at once (a selection): a dash.
447    Mixed,
448}
449
450/// Where a mark goes on its host.
451#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
452#[serde(rename_all = "snake_case")]
453pub enum Anchor {
454    TopStart,
455    TopEnd,
456    BottomStart,
457    BottomEnd,
458    /// The start edge, centred vertically.
459    Start,
460    /// The end edge, centred vertically.
461    End,
462    Center,
463}
464
465impl Anchor {
466    pub const ALL: [Anchor; 7] = [
467        Anchor::TopStart,
468        Anchor::TopEnd,
469        Anchor::BottomStart,
470        Anchor::BottomEnd,
471        Anchor::Start,
472        Anchor::End,
473        Anchor::Center,
474    ];
475
476    pub fn is_corner(self) -> bool {
477        matches!(
478            self,
479            Anchor::TopStart | Anchor::TopEnd | Anchor::BottomStart | Anchor::BottomEnd
480        )
481    }
482
483    /// Which sides it touches: right (else left, `None` centred), bottom
484    /// (else top, `None` centred).
485    fn sides(self, direction: Direction) -> (Option<bool>, Option<bool>) {
486        let rtl = direction == Direction::RightToLeft;
487        match self {
488            Anchor::TopStart => (Some(rtl), Some(false)),
489            Anchor::TopEnd => (Some(!rtl), Some(false)),
490            Anchor::BottomStart => (Some(rtl), Some(true)),
491            Anchor::BottomEnd => (Some(!rtl), Some(true)),
492            Anchor::Start => (Some(rtl), None),
493            Anchor::End => (Some(!rtl), None),
494            Anchor::Center => (None, None),
495        }
496    }
497
498    /// The rectangle of a mark of `size` on `host`. Inside, it sits
499    /// `offset` in from the edges it touches; overhanging (corners only)
500    /// it passes them by half its height, so a dot is centred on the
501    /// corner and a badge on the top edge.
502    pub fn place(
503        self,
504        host: Rect,
505        size: Vec2,
506        direction: Direction,
507        overhang: bool,
508        offset: f32,
509    ) -> Rect {
510        let (right, bottom) = self.sides(direction);
511        let overhang = overhang && self.is_corner();
512        let out = size.y / 2.0;
513        let x = match right {
514            Some(true) if overhang => host.right() + out - size.x,
515            Some(true) => host.right() - offset - size.x,
516            Some(false) if overhang => host.left() - out,
517            Some(false) => host.left() + offset,
518            None => host.center().x - size.x / 2.0,
519        };
520        let y = match bottom {
521            Some(true) if overhang => host.bottom() + out - size.y,
522            Some(true) => host.bottom() - offset - size.y,
523            Some(false) if overhang => host.top() - out,
524            Some(false) => host.top() + offset,
525            None => host.center().y - size.y / 2.0,
526        };
527        Rect::from_min_size(pos2(x, y), size)
528    }
529}
530
531/// The interface's direction: where start and end are. egui has none
532/// of its own yet; an application in a right-to-left language sets it
533/// with [`set_direction`].
534#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
535#[serde(rename_all = "snake_case")]
536pub enum Direction {
537    #[default]
538    LeftToRight,
539    RightToLeft,
540}
541
542/// Sets where start and end are for the marks of this context.
543pub fn set_direction(ctx: &Context, direction: Direction) {
544    lock(&drawn_state(ctx)).direction = direction;
545}
546
547/// Where start and end are ([`set_direction`]).
548pub fn direction(ctx: &Context) -> Direction {
549    lock(&drawn_state(ctx)).direction
550}
551
552/// The text a badge shows for a count: `cap+` past its cap.
553pub fn badge_text(count: u64, cap: u64) -> String {
554    if count > cap {
555        format!("{cap}+")
556    } else {
557        count.to_string()
558    }
559}
560
561/// Adds a meaning to a widget's accessible name: "Masks" becomes
562/// "Masks, 3 errors". A widget named by another node (`labelled_by`)
563/// gets it as its description instead. Call it after the widget gave
564/// its own name, each pass.
565pub fn annotate(ctx: &Context, host: Id, meaning: &str) {
566    ctx.accesskit_node_builder(host, |node| {
567        let label = node.label().unwrap_or_default().to_string();
568        if label.is_empty() && !node.labelled_by().is_empty() {
569            let description = match node.description() {
570                Some(d) if !d.is_empty() => format!("{d}, {meaning}"),
571                _ => meaning.to_string(),
572            };
573            node.set_description(description);
574        } else if label.is_empty() {
575            node.set_label(meaning.to_string());
576        } else {
577            node.set_label(format!("{label}, {meaning}"));
578        }
579    });
580}
581
582#[derive(Clone, Debug, PartialEq)]
583enum Kind {
584    Dot(Option<Led>),
585    Badge {
586        count: Option<u64>,
587        text: String,
588        cap: u64,
589        show_zero: bool,
590    },
591    Pip(Pip),
592    Flag(FlagShape, Option<Flag>),
593    Swatch(Swatch),
594    Icon {
595        icon: Icon,
596        /// A toggle: whether it is on, and the icon when off.
597        toggle: Option<(bool, Icon)>,
598    },
599}
600
601/// A micro-indicator, built then added inline (`ui.add`) or painted on
602/// a widget ([`Indicator::on`], [`Indicator::paint_at`]).
603///
604/// Need (status): a status dot, a LED, a count badge or a flag.
605/// Need (status): a colour swatch.
606#[derive(Clone, Debug, PartialEq)]
607#[must_use = "add it with `ui.add`, or paint it on a widget with `on` or `paint_at`"]
608pub struct Indicator {
609    kind: Kind,
610    tone: Option<Tone>,
611    key: Option<String>,
612    name: Option<String>,
613    tooltip: Option<String>,
614    size: Size,
615    action: Option<String>,
616    command: Option<CommandId>,
617    disabled: Option<String>,
618    attention: Option<f64>,
619    delayed: Option<(Id, f64, bool)>,
620    overhang: Option<bool>,
621    mark: Option<ValueMark>,
622}
623
624impl Indicator {
625    fn new(kind: Kind) -> Indicator {
626        Indicator {
627            kind,
628            tone: None,
629            key: None,
630            name: None,
631            tooltip: None,
632            size: Size::Regular,
633            action: None,
634            command: None,
635            disabled: None,
636            attention: None,
637            delayed: None,
638            overhang: None,
639            mark: None,
640        }
641    }
642
643    /// A plain dot in a tone. Give it a [`name`](Self::name): a dot
644    /// alone says nothing but "something".
645    pub fn dot(tone: Tone) -> Indicator {
646        Indicator::new(Kind::Dot(None)).tone(tone)
647    }
648
649    /// An LED: its state's shape and tone, its state's name.
650    pub fn led(state: Led) -> Indicator {
651        Indicator::new(Kind::Dot(Some(state)))
652    }
653
654    /// A count badge: `99+` past its [`cap`](Self::cap), hidden at zero
655    /// unless [`show_zero`](Self::show_zero). Its name is the real count.
656    pub fn count(count: u64) -> Indicator {
657        Indicator::new(Kind::Badge {
658            count: Some(count),
659            text: String::new(),
660            cap: CAP,
661            show_zero: false,
662        })
663    }
664
665    /// A badge with a short text (`!`, `NEW`: three characters at most
666    /// read well).
667    pub fn text(text: impl Into<String>) -> Indicator {
668        Indicator::new(Kind::Badge {
669            count: None,
670            text: text.into(),
671            cap: CAP,
672            show_zero: false,
673        })
674    }
675
676    /// An activity pip.
677    pub fn pip(state: Pip) -> Indicator {
678        Indicator::new(Kind::Pip(state))
679    }
680
681    /// One of egui-pop's flags, with its shape, tone and name.
682    pub fn flag(flag: Flag) -> Indicator {
683        Indicator::new(Kind::Flag(flag.shape(), Some(flag)))
684    }
685
686    /// A flag of the application's: a shape, then a tone and a name.
687    pub fn flag_shape(shape: FlagShape) -> Indicator {
688        Indicator::new(Kind::Flag(shape, None))
689    }
690
691    /// A value's mark ([`ValueMark`]): its shape, tone and meaning.
692    pub fn mark(mark: ValueMark) -> Indicator {
693        let mut i = Indicator::new(mark.kind()).tone(mark.tone());
694        i.mark = Some(mark);
695        i
696    }
697
698    /// A colour swatch.
699    pub fn swatch(color: Color32) -> Indicator {
700        Indicator::new(Kind::Swatch(Swatch::Color(color)))
701    }
702
703    /// A swatch saying "no colour", or "mixed".
704    pub fn swatch_of(swatch: Swatch) -> Indicator {
705        Indicator::new(Kind::Swatch(swatch))
706    }
707
708    /// An icon as a mark, by value or by name (`"visible"`,
709    /// `"phosphor:wifi-high"`; an unknown name is reported and drawn as
710    /// the placeholder).
711    pub fn icon(icon: impl Into<IconRef>) -> Indicator {
712        Indicator::new(Kind::Icon {
713            icon: icon.into().or_placeholder("indicator"),
714            toggle: None,
715        })
716    }
717
718    /// One of two icons by a state (eye and eye-off, lock and unlock),
719    /// each by value or by name. Made interactive, it is a check box.
720    pub fn toggle(
721        on: bool,
722        when_on: impl Into<IconRef>,
723        when_off: impl Into<IconRef>,
724    ) -> Indicator {
725        Indicator::new(Kind::Icon {
726            icon: when_on.into().or_placeholder("indicator"),
727            toggle: Some((on, when_off.into().or_placeholder("indicator"))),
728        })
729    }
730
731    /// An id, for agents and tests: recorded each pass ([`drawn`]).
732    pub fn id(mut self, id: impl Into<String>) -> Self {
733        self.key = Some(id.into());
734        self
735    }
736
737    /// What the mark means, read with its host's name (passive) or as
738    /// its description (interactive). LEDs, flags, pips, swatches and
739    /// counts have one by default.
740    pub fn name(mut self, name: impl Into<String>) -> Self {
741        self.name = Some(name.into());
742        self
743    }
744
745    /// The tooltip; by default the meaning (passive) or the action
746    /// (interactive).
747    pub fn tooltip(mut self, text: impl Into<String>) -> Self {
748        self.tooltip = Some(text.into());
749        self
750    }
751
752    pub fn tone(mut self, tone: Tone) -> Self {
753        self.tone = Some(tone);
754        self
755    }
756
757    pub fn size(mut self, size: Size) -> Self {
758        self.size = size;
759        self
760    }
761
762    /// A badge's cap: `cap+` past it.
763    pub fn cap(mut self, cap: u64) -> Self {
764        if let Kind::Badge { cap: c, .. } = &mut self.kind {
765            *c = cap;
766        }
767        self
768    }
769
770    /// Shows a count of zero (hidden by default).
771    pub fn show_zero(mut self, show: bool) -> Self {
772        if let Kind::Badge { show_zero, .. } = &mut self.kind {
773            *show_zero = show;
774        }
775        self
776    }
777
778    /// Makes it a button whose accessible name is `action` ("Reset
779    /// exposure", "Visible" for a toggle).
780    pub fn interactive(mut self, action: impl Into<String>) -> Self {
781        self.action = Some(action.into());
782        self
783    }
784
785    /// The command an activation runs (an interactive mark): the
786    /// application runs it before the next frame, so it is a step.
787    pub fn command(mut self, command: CommandId) -> Self {
788        self.command = Some(command);
789        self
790    }
791
792    /// Disables an interactive mark, saying why on hover.
793    pub fn disabled(mut self, reason: impl Into<String>) -> Self {
794        self.disabled = Some(reason.into());
795        self
796    }
797
798    /// Calls attention: pulses `indicator.pulse.count` times from
799    /// `since` (motion clock seconds, [`motion::now`]), then stays
800    /// still. A still ring under reduced motion, for as long.
801    pub fn attention(mut self, since: f64) -> Self {
802        self.attention = Some(since);
803        self
804    }
805
806    /// A busy pip shown only after `motion.spinner.delay` of work, then
807    /// at least `motion.spinner.min` ([`motion::Busy`]); `id` keeps its
808    /// state, `since` is when the work started.
809    pub fn delayed(mut self, id: Id, since: f64, busy: bool) -> Self {
810        self.delayed = Some((id, since, busy));
811        self
812    }
813
814    /// Whether it overhangs a corner (badges and dots do by default).
815    pub fn overhang(mut self, overhang: bool) -> Self {
816        self.overhang = Some(overhang);
817        self
818    }
819
820    pub fn is_interactive(&self) -> bool {
821        self.action.is_some()
822    }
823
824    /// Its tone: the one given, else its kind's.
825    pub fn tone_of(&self) -> Tone {
826        self.tone.unwrap_or(match &self.kind {
827            Kind::Dot(Some(led)) => led.tone(),
828            Kind::Dot(None) | Kind::Badge { .. } => Tone::Accent,
829            Kind::Pip(p) => p.tone(),
830            Kind::Flag(_, Some(f)) => f.tone(),
831            Kind::Flag(_, None) => Tone::Accent,
832            Kind::Swatch(_) | Kind::Icon { .. } => Tone::Neutral,
833        })
834    }
835
836    /// The text a badge shows (none for other kinds).
837    pub fn label(&self) -> Option<String> {
838        match &self.kind {
839            Kind::Badge {
840                count: Some(n),
841                cap,
842                ..
843            } => Some(badge_text(*n, *cap)),
844            Kind::Badge { text, .. } => Some(text.clone()),
845            _ => None,
846        }
847    }
848
849    /// Whether it shows anything: a badge at zero does not, unless asked.
850    fn has_content(&self) -> bool {
851        match &self.kind {
852            Kind::Badge {
853                count: Some(0),
854                show_zero,
855                ..
856            } => *show_zero,
857            Kind::Badge { count: Some(_), .. } => true,
858            Kind::Badge { text, .. } => !text.is_empty(),
859            _ => true,
860        }
861    }
862
863    fn shown(&self, ctx: &Context) -> bool {
864        if !self.has_content() {
865            return false;
866        }
867        match self.delayed {
868            Some((id, since, busy)) => motion::Busy::new(id, since).visible(ctx, busy),
869            None => true,
870        }
871    }
872
873    /// What it means, in the current language: the name given, else its
874    /// kind's (an LED's state, a flag, a pip, a swatch's colour, a
875    /// count).
876    pub fn meaning(&self, ctx: &Context) -> Option<String> {
877        if let Some(n) = &self.name {
878            return Some(n.clone());
879        }
880        if let Some(m) = &self.mark {
881            return Some(m.meaning(ctx));
882        }
883        match &self.kind {
884            Kind::Dot(Some(led)) => Some(strings::tr(ctx, &led.key())),
885            Kind::Dot(None) | Kind::Icon { .. } => None,
886            Kind::Badge { count: Some(n), .. } => Some(n.to_string()),
887            Kind::Badge { text, .. } => (!text.is_empty()).then(|| text.clone()),
888            Kind::Pip(Pip::Busy) => Some(strings::tr(ctx, &strings::BUSY)),
889            Kind::Pip(Pip::Progress(f)) => {
890                let percent = format!("{:.0}", f.clamp(0.0, 1.0) * 100.0);
891                Some(strings::tr_args(
892                    ctx,
893                    &strings::INDICATOR_PERCENT,
894                    &[("percent", &percent)],
895                ))
896            }
897            Kind::Pip(Pip::Done) => Some(strings::tr(ctx, &strings::INDICATOR_DONE)),
898            Kind::Pip(Pip::Failed) => Some(strings::tr(ctx, &strings::INDICATOR_FAILED)),
899            Kind::Flag(_, Some(f)) => Some(strings::tr(ctx, &f.key())),
900            Kind::Flag(_, None) => None,
901            Kind::Swatch(Swatch::Color(c)) => Some(hex(*c)),
902            Kind::Swatch(Swatch::None) => Some(strings::tr(ctx, &strings::INDICATOR_NO_COLOR)),
903            Kind::Swatch(Swatch::Mixed) => Some(strings::tr(ctx, &strings::INDICATOR_MIXED)),
904        }
905    }
906
907    /// What agents and tests see of it (its rectangle empty: it is not
908    /// drawn).
909    pub fn describe(&self, ctx: &Context) -> Record {
910        let (kind, state, value) = match &self.kind {
911            Kind::Dot(None) => ("dot", "shown".to_string(), None),
912            Kind::Dot(Some(led)) => ("led", led.name().to_string(), None),
913            Kind::Badge { count: Some(n), .. } => ("badge", "count".to_string(), Some(*n as f64)),
914            Kind::Badge { .. } => ("badge", "text".to_string(), None),
915            Kind::Pip(p) => (
916                "pip",
917                p.name().to_string(),
918                match p {
919                    Pip::Progress(f) => Some(f64::from(f.clamp(0.0, 1.0))),
920                    _ => None,
921                },
922            ),
923            Kind::Flag(_, Some(f)) => ("flag", f.name().to_string(), None),
924            Kind::Flag(shape, None) => (
925                "flag",
926                serde_json::to_value(shape)
927                    .ok()
928                    .and_then(|v| v.as_str().map(str::to_string))
929                    .unwrap_or_default(),
930                None,
931            ),
932            Kind::Swatch(Swatch::Color(_)) => ("swatch", "color".to_string(), None),
933            Kind::Swatch(Swatch::None) => ("swatch", "none".to_string(), None),
934            Kind::Swatch(Swatch::Mixed) => ("swatch", "mixed".to_string(), None),
935            Kind::Icon {
936                toggle: Some((on, _)),
937                ..
938            } => (
939                "icon",
940                if *on { "on" } else { "off" }.to_string(),
941                Some(if *on { 1.0 } else { 0.0 }),
942            ),
943            Kind::Icon { icon, .. } => ("icon", icon.name().to_string(), None),
944        };
945        let (kind, state) = match &self.mark {
946            Some(m) => ("mark", m.name().to_string()),
947            None => (kind, state),
948        };
949        let text = match &self.kind {
950            Kind::Swatch(Swatch::Color(c)) => Some(hex(*c)),
951            _ => self.label(),
952        };
953        Record {
954            id: self.key.clone().unwrap_or_default(),
955            kind,
956            state,
957            value,
958            text,
959            tone: self.tone_of(),
960            name: self.meaning(ctx),
961            action: self.action.clone(),
962            host: None,
963            interactive: self.is_interactive(),
964            enabled: self.disabled.is_none(),
965            shown: self.has_content(),
966            pulsing: false,
967            command: self.command.as_ref().map(|c| c.as_str().to_string()),
968            rect: [0.0; 4],
969        }
970    }
971
972    /// The mark's own size, without its target.
973    fn mark_size(&self, painter: &Painter, lk: &Looks) -> Vec2 {
974        let f = self.size.factor();
975        let square = |side: f32| Vec2::splat((side * f).round());
976        match &self.kind {
977            Kind::Dot(_) => square(lk.dot),
978            Kind::Badge { .. } => {
979                let h = (lk.badge_height * f).round();
980                let text = self.label().unwrap_or_default();
981                let g = painter.layout_no_wrap(
982                    text,
983                    FontId::proportional(lk.badge_font * f),
984                    Color32::PLACEHOLDER,
985                );
986                vec2((g.size().x + 2.0 * lk.badge_padding * f).max(h).ceil(), h)
987            }
988            Kind::Pip(_) => square(lk.pip),
989            Kind::Flag(FlagShape::Stripe, _) => {
990                vec2((3.0 * f).round(), (lk.flag * 2.0 * f).round())
991            }
992            Kind::Flag(..) => square(lk.flag),
993            Kind::Swatch(_) => square(lk.swatch),
994            Kind::Icon { .. } => square(lk.icon),
995        }
996    }
997
998    fn egui_id(&self, fallback: Id) -> Id {
999        match &self.key {
1000            Some(k) => Id::unique(("egui_pop_indicator", k.as_str())),
1001            None => fallback,
1002        }
1003    }
1004
1005    fn pulse(&self, ctx: &Context, lk: &Looks) -> Pulse {
1006        let busy = matches!(self.kind, Kind::Dot(Some(Led::Busy)));
1007        let period = f64::from(lk.pulse_period);
1008        let now = motion::now(ctx);
1009        let attending = self.attention.and_then(|since| {
1010            let until = since + period * f64::from(lk.pulse_count);
1011            (since..until).contains(&now).then_some((since, until))
1012        });
1013        if !busy && attending.is_none() {
1014            return Pulse::None;
1015        }
1016        if let Some((_, until)) = attending {
1017            motion::wake_at(ctx, until);
1018        }
1019        if motion::reduced(ctx) || period <= 0.0 {
1020            return Pulse::Still;
1021        }
1022        motion::animate(ctx);
1023        let phase = match (busy, attending) {
1024            (false, Some((since, _))) => ((now - since) / period).rem_euclid(1.0) as f32,
1025            _ => motion::phase(ctx, period, 0.0),
1026        };
1027        Pulse::Moving(phase)
1028    }
1029
1030    /// How much room the mark takes, for a caller placing it with
1031    /// [`paint_at`](Self::paint_at).
1032    pub fn measure(&self, ui: &Ui) -> Vec2 {
1033        self.mark_size(ui.painter(), &Looks::of(ui.ctx()))
1034    }
1035
1036    /// Adds it inline and returns its response (its target when
1037    /// interactive): the same as `ui.add`.
1038    pub fn show(self, ui: &mut Ui) -> Response {
1039        self.ui(ui)
1040    }
1041
1042    /// Paints it on a widget's corner, edge or centre, and adds its
1043    /// meaning to that widget's accessible name when passive. Returns
1044    /// the mark's response (a button's when interactive).
1045    pub fn on(self, ui: &mut Ui, host: &Response, anchor: Anchor) -> Response {
1046        let ctx = ui.ctx().clone();
1047        let passive = !self.is_interactive();
1048        let meaning = self.meaning(&ctx);
1049        let host_name = host_label(&ctx, host.id);
1050        let shown = self.shown(&ctx);
1051        let r = self.place(ui, host.rect, anchor, host_name);
1052        if passive
1053            && shown
1054            && let Some(m) = meaning
1055        {
1056            annotate(&ctx, host.id, &m);
1057        }
1058        r
1059    }
1060
1061    /// Paints it on a rectangle (no widget's name to add to). Returns
1062    /// the mark's response (a button's when interactive).
1063    pub fn paint_at(self, ui: &mut Ui, host: Rect, anchor: Anchor) -> Response {
1064        self.place(ui, host, anchor, None)
1065    }
1066
1067    fn place(self, ui: &mut Ui, host: Rect, anchor: Anchor, host_name: Option<String>) -> Response {
1068        let ctx = ui.ctx().clone();
1069        let lk = Looks::of(&ctx);
1070        let dir = direction(&ctx);
1071        let mut size = self.mark_size(ui.painter(), &lk);
1072        let shape = match &self.kind {
1073            // A named flag sits in its corner when its glyph is `corner`.
1074            Kind::Flag(_, Some(f)) => Some(if Kit::of(&ctx).glyph(f.glyph()) == Icon::Corner {
1075                FlagShape::Corner
1076            } else {
1077                FlagShape::Square
1078            }),
1079            Kind::Flag(shape, None) => Some(*shape),
1080            _ => None,
1081        };
1082        let mut offset = lk.offset;
1083        if shape == Some(FlagShape::Stripe) && matches!(anchor, Anchor::Start | Anchor::End) {
1084            size.y = host.height();
1085            offset = 0.0;
1086        }
1087        if shape == Some(FlagShape::Corner) && anchor.is_corner() {
1088            offset = 0.0;
1089        }
1090        let overhang = self
1091            .overhang
1092            .unwrap_or(matches!(self.kind, Kind::Badge { .. } | Kind::Dot(_)))
1093            && anchor.is_corner();
1094        let mark = anchor.place(host, size, dir, overhang, offset);
1095        let fallback = ui
1096            .scope_id()
1097            .with(("egui_pop_indicator", ui.next_auto_id(), anchor));
1098        let id = self.egui_id(fallback);
1099        let target = if self.is_interactive() {
1100            Rect::from_center_size(
1101                mark.center(),
1102                vec2(
1103                    mark.width().max(lk.target.x),
1104                    mark.height().max(lk.target.y),
1105                ),
1106            )
1107        } else {
1108            mark
1109        };
1110        let response = self.interact(ui, target, id, self.shown(ui.ctx()));
1111        let painter = if overhang {
1112            overhang_painter(ui)
1113        } else {
1114            ui.painter().clone()
1115        };
1116        let corner = anchor.sides(dir);
1117        let visible = ui.is_rect_visible(host);
1118        self.finish(
1119            ui,
1120            &painter,
1121            response,
1122            mark,
1123            Placement {
1124                on_host: true,
1125                corner: (corner.0.unwrap_or(false), corner.1.unwrap_or(false)),
1126                visible,
1127                host: host_name,
1128            },
1129        )
1130    }
1131
1132    /// Whether an interactive mark takes clicks: not disabled, nor in a
1133    /// disabled `Ui`.
1134    fn active(&self, ui: &Ui) -> bool {
1135        self.is_interactive() && self.disabled.is_none() && ui.is_enabled()
1136    }
1137
1138    fn interact(&self, ui: &mut Ui, rect: Rect, id: Id, shown: bool) -> Response {
1139        let sense = if shown && self.active(ui) {
1140            Sense::click()
1141        } else {
1142            Sense::hover()
1143        };
1144        ui.interact(rect, id, sense)
1145    }
1146
1147    fn finish(
1148        self,
1149        ui: &mut Ui,
1150        painter: &Painter,
1151        response: Response,
1152        mark: Rect,
1153        placement: Placement,
1154    ) -> Response {
1155        let ctx = ui.ctx().clone();
1156        let kit = Kit::of(&ctx);
1157        let lk = Looks::of(&ctx);
1158        let shown = self.shown(&ctx);
1159        let enabled = self.active(ui);
1160        let interactive = self.is_interactive();
1161        let pulse = if shown {
1162            self.pulse(&ctx, &lk)
1163        } else {
1164            Pulse::None
1165        };
1166        if shown && placement.visible {
1167            let cx = KitCx {
1168                painter,
1169                ppp: ctx.pixels_per_point(),
1170            };
1171            // The target's state: what `indicator-button` is drawn in,
1172            // and what an icon mark takes its colour from.
1173            let mut state = State::REST.toned(self.tone_of());
1174            if interactive {
1175                state = State::from_response(&response).toned(self.tone_of());
1176                if !enabled {
1177                    state = State::REST
1178                        .toned(self.tone_of())
1179                        .with(State::DISABLED, true);
1180                }
1181                if let Kind::Icon {
1182                    toggle: Some((on, _)),
1183                    ..
1184                } = &self.kind
1185                {
1186                    state = state.with(State::SELECTED, *on);
1187                }
1188                kit.indicator_button.paint(
1189                    &cx,
1190                    &Part {
1191                        rect: response.rect,
1192                        room: response.rect,
1193                        state,
1194                        label: None,
1195                    },
1196                );
1197            }
1198            let mut color = self.color(&kit, state);
1199            if interactive && !enabled {
1200                color = kit.indicator_button.style(state).text;
1201            }
1202            self.paint(
1203                &cx,
1204                &kit,
1205                mark,
1206                &Look {
1207                    color,
1208                    on_host: placement.on_host,
1209                    corner: placement.corner,
1210                    pulse,
1211                    ring: lk.ring,
1212                    font: lk.badge_font * self.size.factor(),
1213                },
1214            );
1215        }
1216        let meaning = self.meaning(&ctx);
1217        let mut response = response;
1218        if interactive && shown {
1219            let action = self.action.clone().unwrap_or_default();
1220            let ui_enabled = enabled;
1221            match &self.kind {
1222                Kind::Icon {
1223                    toggle: Some((on, _)),
1224                    ..
1225                } => {
1226                    let on = *on;
1227                    response.widget_info(|| {
1228                        WidgetInfo::selected(Role::CheckBox, ui_enabled, on, &action)
1229                    });
1230                }
1231                _ => {
1232                    response.widget_info(|| WidgetInfo::labeled(Role::Button, ui_enabled, &action))
1233                }
1234            }
1235            if let Some(m) = &meaning {
1236                ctx.accesskit_node_builder(response.id, |node| node.set_description(m.clone()));
1237            }
1238            let tip = self.tooltip.clone().unwrap_or_else(|| action.clone());
1239            response = match &self.disabled {
1240                Some(reason) => response.on_hover_text(format!("{action}: {reason}")),
1241                None => response.on_hover_text(tip),
1242            };
1243            if enabled
1244                && response.clicked()
1245                && let Some(c) = &self.command
1246            {
1247                lock(&drawn_state(&ctx)).commands.push(c.clone());
1248                ctx.request_repaint();
1249            }
1250        } else if shown {
1251            if !placement.on_host
1252                && let Some(m) = &meaning
1253            {
1254                let enabled = ui.is_enabled();
1255                response.widget_info(|| WidgetInfo::labeled(Role::Image, enabled, m));
1256            }
1257            if let Some(tip) = self.tooltip.clone().or_else(|| meaning.clone()) {
1258                response = response.on_hover_text(tip);
1259            }
1260        }
1261        if self.key.is_some() {
1262            let mut r = self.describe(&ctx);
1263            r.shown = shown;
1264            r.pulsing = !matches!(pulse, Pulse::None);
1265            r.host = placement.host;
1266            r.rect = [mark.min.x, mark.min.y, mark.width(), mark.height()];
1267            record(&ctx, r);
1268        }
1269        response
1270    }
1271
1272    /// The mark's colour, from its kit component in its tone; `state`
1273    /// is its target's (an icon mark follows it).
1274    fn color(&self, kit: &Kit, state: State) -> Color32 {
1275        let tone = self.tone_of();
1276        let rest = State::REST.toned(tone);
1277        match &self.kind {
1278            Kind::Dot(Some(Led::Off)) if self.tone.is_none() => {
1279                kit.indicator_dot.style(State::REST).border_color
1280            }
1281            Kind::Dot(_) => kit.indicator_dot.style(rest).fill,
1282            Kind::Badge { .. } => kit.indicator_badge.style(rest).fill,
1283            Kind::Pip(Pip::Busy) => kit.spinner.style(rest).indicator_color,
1284            Kind::Pip(_) => kit.progress_ring.style(rest).indicator_color,
1285            Kind::Flag(..) => kit.indicator_flag.style(rest).fill,
1286            Kind::Swatch(_) => kit.indicator_swatch.style(rest).text,
1287            Kind::Icon { .. } => kit.indicator_button.style(state).text,
1288        }
1289    }
1290
1291    fn paint(&self, cx: &KitCx<'_>, kit: &Kit, rect: Rect, look: &Look) {
1292        let p = cx.painter;
1293        let color = look.color;
1294        let c = rect.center();
1295        let r = rect.width().min(rect.height()) / 2.0;
1296        let outline = kit.indicator_outline.style(State::REST);
1297        match &self.kind {
1298            Kind::Dot(led) => {
1299                if look.on_host && outline.ring_width > 0.0 {
1300                    p.circle_filled(c, r + outline.ring_width, outline.ring_color);
1301                }
1302                // An LED's shape is its state's glyph role: the kit's.
1303                let icon = led.map_or(Icon::Disc, |l| kit.glyph(l.glyph()));
1304                paint_glyph(p, icon, rect, color, look.ring);
1305                paint_pulse_ring(p, c, r, look);
1306            }
1307            Kind::Badge { .. } => {
1308                let state = State::REST.toned(self.tone_of());
1309                let badge = &kit.indicator_badge;
1310                if look.on_host {
1311                    // The outline is a ring around the badge's own corners.
1312                    let b = BoxStyle {
1313                        radius: badge.style(state).radius.min((rect.height() / 2.0).floor()),
1314                        ..*outline
1315                    };
1316                    paint_ring(cx, rect, &b, Corners::All);
1317                }
1318                let galley = p.layout_no_wrap(
1319                    self.label().unwrap_or_default(),
1320                    FontId::proportional(look.font),
1321                    Color32::PLACEHOLDER,
1322                );
1323                badge.paint_part(
1324                    cx,
1325                    &Part {
1326                        rect,
1327                        room: rect,
1328                        state,
1329                        label: Some(&galley),
1330                    },
1331                );
1332                let round = |grow: f32| CornerRadius::same((rect.height() / 2.0 + grow) as u8);
1333                match look.pulse {
1334                    Pulse::Moving(phase) => {
1335                        let grow = 1.0 + 4.0 * phase;
1336                        p.rect_stroke(
1337                            rect.expand(grow),
1338                            round(grow),
1339                            Stroke::new(look.ring, color.gamma_multiply(1.0 - phase)),
1340                            egui::StrokeKind::Outside,
1341                        );
1342                    }
1343                    Pulse::Still => {
1344                        p.rect_stroke(
1345                            rect.expand(2.0),
1346                            round(2.0),
1347                            Stroke::new(look.ring, color),
1348                            egui::StrokeKind::Outside,
1349                        );
1350                    }
1351                    Pulse::None => {}
1352                }
1353            }
1354            Kind::Pip(pip) => match pip {
1355                Pip::Busy => crate::progress::paint_spinner_on(p, rect, color),
1356                Pip::Progress(f) => crate::progress::paint_ring_on(p, rect, Some(*f), color),
1357                Pip::Done => Icon::Check.paint(p, rect, color),
1358                Pip::Failed => Icon::Error.paint(p, rect, color),
1359            },
1360            Kind::Flag(shape, flag) => {
1361                match flag.map(|f| kit.glyph(f.glyph())) {
1362                    // A named flag's shape is its glyph role; `corner`
1363                    // turns to the corner it sits in.
1364                    Some(Icon::Corner) => {
1365                        paint_flag(p, FlagShape::Corner, rect, look.corner, color);
1366                    }
1367                    Some(icon) => paint_glyph(p, icon, rect, color, look.ring),
1368                    None => paint_flag(p, *shape, rect, look.corner, color),
1369                }
1370                paint_pulse_ring(p, c, r, look);
1371            }
1372            Kind::Swatch(swatch) => {
1373                let swatch_kit = &kit.indicator_swatch;
1374                let b = swatch_kit.style(State::REST);
1375                let radius = CornerRadius::same(b.radius.round().clamp(0.0, 255.0) as u8);
1376                // The colour is content, under the kit's box.
1377                match swatch {
1378                    Swatch::Color(col) if col.is_opaque() => {
1379                        p.rect_filled(rect, radius, *col);
1380                    }
1381                    // The checkerboard under alpha is egui's.
1382                    Swatch::Color(col) => egui::widgets::color_picker::show_color_at(p, *col, rect),
1383                    Swatch::None => {
1384                        let inset = rect.shrink(rect.width() * 0.15);
1385                        p.line_segment(
1386                            [inset.left_bottom(), inset.right_top()],
1387                            Stroke::new((rect.width() / 10.0).max(1.0), color),
1388                        );
1389                    }
1390                    Swatch::Mixed => {
1391                        let half = rect.width() * 0.25;
1392                        p.line_segment(
1393                            [c - vec2(half, 0.0), c + vec2(half, 0.0)],
1394                            Stroke::new((rect.width() / 8.0).max(1.5), color),
1395                        );
1396                    }
1397                }
1398                swatch_kit.paint(
1399                    cx,
1400                    &Part {
1401                        rect,
1402                        room: rect,
1403                        state: State::REST,
1404                        label: None,
1405                    },
1406                );
1407                paint_pulse_ring(p, c, r, look);
1408            }
1409            Kind::Icon { icon, toggle } => {
1410                let icon = match toggle {
1411                    Some((false, off)) => *off,
1412                    _ => *icon,
1413                };
1414                icon.paint(p, rect, color);
1415            }
1416        }
1417    }
1418}
1419
1420impl Widget for Indicator {
1421    fn ui(self, ui: &mut Ui) -> Response {
1422        let ctx = ui.ctx().clone();
1423        let lk = Looks::of(&ctx);
1424        let shown = self.shown(&ctx);
1425        let mark = if shown {
1426            self.mark_size(ui.painter(), &lk)
1427        } else {
1428            Vec2::ZERO
1429        };
1430        let outer = if self.is_interactive() && shown {
1431            vec2(mark.x.max(lk.target.x), mark.y.max(lk.target.y))
1432        } else {
1433            mark
1434        };
1435        // Nothing to show (a badge at zero, a pip not yet due): no room
1436        // taken, no node.
1437        let (auto, rect) = if shown {
1438            ui.allocate_space(outer)
1439        } else {
1440            (
1441                ui.next_auto_id(),
1442                Rect::from_min_size(ui.cursor().min, Vec2::ZERO),
1443            )
1444        };
1445        let id = self.egui_id(auto);
1446        let response = self.interact(ui, rect, id, shown);
1447        let visible = ui.is_rect_visible(rect);
1448        let painter = ui.painter().clone();
1449        self.finish(
1450            ui,
1451            &painter,
1452            response,
1453            Rect::from_center_size(rect.center(), mark),
1454            Placement {
1455                on_host: false,
1456                corner: (direction(&ctx) == Direction::RightToLeft, false),
1457                visible,
1458                host: None,
1459            },
1460        )
1461    }
1462}
1463
1464/// Indicators on a widget's response.
1465pub trait IndicatorExt {
1466    /// Paints an indicator on this widget ([`Indicator::on`]) and
1467    /// returns the widget's response.
1468    fn with_indicator(self, ui: &mut Ui, indicator: Indicator, anchor: Anchor) -> Response;
1469}
1470
1471impl IndicatorExt for Response {
1472    fn with_indicator(self, ui: &mut Ui, indicator: Indicator, anchor: Anchor) -> Response {
1473        indicator.on(ui, &self, anchor);
1474        self
1475    }
1476}
1477
1478/// What agents and tests see of a drawn indicator.
1479#[derive(Clone, Debug, PartialEq, Serialize)]
1480pub struct Record {
1481    /// Its id ([`Indicator::id`]).
1482    pub id: String,
1483    /// `dot`, `led`, `badge`, `pip`, `flag`, `swatch`, `icon` or `mark`
1484    /// (a [`ValueMark`]).
1485    pub kind: &'static str,
1486    /// The LED's, pip's or flag's state, `count` or `text` for a badge,
1487    /// `color`, `none` or `mixed` for a swatch, `on` or `off` for a
1488    /// toggle, the icon's name, `shown` for a dot, `changed`, `held` or
1489    /// `moved` for a mark.
1490    pub state: String,
1491    /// A badge's count, a pip's fraction, a toggle's 1 or 0.
1492    pub value: Option<f64>,
1493    /// What it shows: a badge's text (`99+`), a swatch's colour.
1494    pub text: Option<String>,
1495    pub tone: Tone,
1496    /// Its meaning, as read by screen readers.
1497    pub name: Option<String>,
1498    /// An interactive one's action.
1499    pub action: Option<String>,
1500    /// The accessible name of the widget it sits on, before its meaning
1501    /// joined it.
1502    pub host: Option<String>,
1503    pub interactive: bool,
1504    pub enabled: bool,
1505    /// Whether it shows (a badge at zero, a delayed pip do not).
1506    pub shown: bool,
1507    pub pulsing: bool,
1508    pub command: Option<String>,
1509    /// Its mark's rectangle in points: x, y, width, height.
1510    pub rect: [f32; 4],
1511}
1512
1513/// The indicators with an id drawn in the last complete pass: empty
1514/// when that pass drew none (a frame hiding every bar).
1515pub fn drawn(ctx: &Context) -> Vec<Record> {
1516    let st = drawn_state(ctx);
1517    let s = lock(&st);
1518    let now = pass(ctx);
1519    if s.pass == now {
1520        // Read while the pass draws: the one before.
1521        s.last.clone()
1522    } else if s.pass + 1 == now {
1523        // The pass just ended.
1524        s.building.clone()
1525    } else {
1526        Vec::new()
1527    }
1528}
1529
1530/// One drawn indicator by id.
1531pub fn find(ctx: &Context, id: &str) -> Option<Record> {
1532    drawn(ctx).into_iter().find(|r| r.id == id)
1533}
1534
1535/// The commands interactive indicators asked for since the last call;
1536/// the application runs them (an egui-pop `App` does, each frame).
1537pub fn take_commands(ctx: &Context) -> Vec<CommandId> {
1538    std::mem::take(&mut lock(&drawn_state(ctx)).commands)
1539}
1540
1541#[derive(Default)]
1542struct Drawn {
1543    /// The pass `building` was recorded in.
1544    pass: u64,
1545    building: Vec<Record>,
1546    /// The pass before `pass`, when it recorded marks.
1547    last: Vec<Record>,
1548    commands: Vec<CommandId>,
1549    direction: Direction,
1550}
1551
1552impl std::fmt::Debug for Drawn {
1553    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1554        f.debug_struct("Drawn")
1555            .field("pass", &self.pass)
1556            .field("building", &self.building.len())
1557            .field("last", &self.last.len())
1558            .field("commands", &self.commands.len())
1559            .finish()
1560    }
1561}
1562
1563fn drawn_state(ctx: &Context) -> Arc<Mutex<Drawn>> {
1564    shared::<Drawn>(ctx, "core.indicators")
1565}
1566
1567/// The first record of a pass starts its list; the one before becomes
1568/// `last` only when it is the pass just before (a pass that drew no mark
1569/// leaves nothing behind).
1570fn rotate(ctx: &Context, s: &mut Drawn) {
1571    let now = pass(ctx);
1572    if s.pass != now {
1573        s.last = if s.pass + 1 == now {
1574            std::mem::take(&mut s.building)
1575        } else {
1576            s.building.clear();
1577            Vec::new()
1578        };
1579        s.pass = now;
1580    }
1581}
1582
1583fn record(ctx: &Context, r: Record) {
1584    let st = drawn_state(ctx);
1585    let mut s = lock(&st);
1586    rotate(ctx, &mut s);
1587    s.building.retain(|x| x.id != r.id);
1588    s.building.push(r);
1589}
1590
1591fn host_label(ctx: &Context, id: Id) -> Option<String> {
1592    ctx.accesskit_node_builder(id, |node| node.label().map(str::to_string))
1593        .flatten()
1594        .filter(|l| !l.is_empty())
1595}
1596
1597/// A painter on a layer of its own just above the host's, unclipped,
1598/// with the host layer's transform (a pan and zoom).
1599fn overhang_painter(ui: &Ui) -> Painter {
1600    let ctx = ui.ctx();
1601    let parent = ui.layer_id();
1602    let layer = LayerId::new(parent.order, parent.id.with("egui_pop_indicator"));
1603    ctx.set_sublayer(parent, layer);
1604    if let Some(transform) = ctx.layer_transform_to_global(parent) {
1605        ctx.set_transform_layer(layer, transform);
1606    }
1607    Painter::new(ctx.clone(), layer, Rect::EVERYTHING)
1608}
1609
1610#[derive(Clone, Copy, Debug, PartialEq)]
1611enum Pulse {
1612    None,
1613    /// 0 to 1 through one pulse.
1614    Moving(f32),
1615    /// Reduced motion: a still ring.
1616    Still,
1617}
1618
1619struct Look {
1620    color: Color32,
1621    on_host: bool,
1622    /// The corner it sits in: right, bottom.
1623    corner: (bool, bool),
1624    pulse: Pulse,
1625    /// A pulse's ring width (`indicator-dot.rest.border-width`).
1626    ring: f32,
1627    /// A badge's text size.
1628    font: f32,
1629}
1630
1631struct Placement {
1632    on_host: bool,
1633    corner: (bool, bool),
1634    visible: bool,
1635    host: Option<String>,
1636}
1637
1638fn paint_pulse_ring(p: &Painter, c: Pos2, r: f32, look: &Look) {
1639    match look.pulse {
1640        Pulse::Moving(phase) => {
1641            p.circle_stroke(
1642                c,
1643                r + look.ring + r * 1.2 * phase,
1644                Stroke::new(look.ring, look.color.gamma_multiply(1.0 - phase)),
1645            );
1646        }
1647        Pulse::Still => {
1648            p.circle_stroke(
1649                c,
1650                r + look.ring * 1.5 + 1.0,
1651                Stroke::new(look.ring, look.color),
1652            );
1653        }
1654        Pulse::None => {}
1655    }
1656}
1657
1658/// Paints a glyph as a mark: egui-pop's own marks at the full size of
1659/// `rect` (a ring `ring` thick), any other icon as it is drawn anywhere.
1660fn paint_glyph(p: &Painter, icon: Icon, rect: Rect, color: Color32, ring: f32) {
1661    if !crate::icon::paint_mark(p, icon, rect, color, ring) {
1662        icon.paint(p, rect, color);
1663    }
1664}
1665
1666fn paint_flag(p: &Painter, shape: FlagShape, rect: Rect, corner: (bool, bool), color: Color32) {
1667    let c = rect.center();
1668    let s = rect.width().min(rect.height());
1669    let h = s / 2.0;
1670    match shape {
1671        FlagShape::Corner => {
1672            let (right, bottom) = corner;
1673            let x = if right { rect.right() } else { rect.left() };
1674            let y = if bottom { rect.bottom() } else { rect.top() };
1675            let dx = if right { -rect.width() } else { rect.width() };
1676            let dy = if bottom {
1677                -rect.height()
1678            } else {
1679                rect.height()
1680            };
1681            p.add(Shape::convex_polygon(
1682                vec![pos2(x, y), pos2(x + dx, y), pos2(x, y + dy)],
1683                color,
1684                Stroke::NONE,
1685            ));
1686        }
1687        FlagShape::Stripe => {
1688            p.rect_filled(rect, CornerRadius::same(1), color);
1689        }
1690        FlagShape::Diamond => {
1691            p.add(Shape::convex_polygon(
1692                vec![
1693                    pos2(c.x, c.y - h),
1694                    pos2(c.x + h, c.y),
1695                    pos2(c.x, c.y + h),
1696                    pos2(c.x - h, c.y),
1697                ],
1698                color,
1699                Stroke::NONE,
1700            ));
1701        }
1702        FlagShape::Triangle => {
1703            p.add(Shape::convex_polygon(
1704                vec![
1705                    pos2(c.x, c.y - h),
1706                    pos2(c.x + h, c.y + h * 0.8),
1707                    pos2(c.x - h, c.y + h * 0.8),
1708                ],
1709                color,
1710                Stroke::NONE,
1711            ));
1712        }
1713        FlagShape::Square => {
1714            p.rect_filled(
1715                Rect::from_center_size(c, Vec2::splat(s * 0.8)),
1716                CornerRadius::same(1),
1717                color,
1718            );
1719        }
1720        FlagShape::Asterisk => {
1721            let stroke = Stroke::new((s / 5.0).max(1.0), color);
1722            for k in 0..3 {
1723                let a = std::f32::consts::FRAC_PI_2 + k as f32 * std::f32::consts::PI / 3.0;
1724                let d = vec2(a.cos(), a.sin()) * h;
1725                p.line_segment([c - d, c + d], stroke);
1726            }
1727        }
1728    }
1729}
1730
1731fn hex(c: Color32) -> String {
1732    if c.a() == 255 {
1733        format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())
1734    } else {
1735        let [r, g, b, a] = c.to_srgba_unmultiplied();
1736        format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
1737    }
1738}
1739
1740#[cfg(test)]
1741mod tests {
1742    use super::*;
1743
1744    #[test]
1745    fn a_badge_caps_its_count_and_hides_zero() {
1746        assert_eq!(badge_text(0, CAP), "0");
1747        assert_eq!(badge_text(9, CAP), "9");
1748        assert_eq!(badge_text(99, CAP), "99");
1749        assert_eq!(badge_text(100, CAP), "99+");
1750        assert_eq!(badge_text(1000, 999), "999+");
1751        assert!(!Indicator::count(0).has_content());
1752        assert!(Indicator::count(0).show_zero(true).has_content());
1753        assert_eq!(Indicator::count(250).label().as_deref(), Some("99+"));
1754        assert_eq!(
1755            Indicator::count(250).cap(999).label().as_deref(),
1756            Some("250")
1757        );
1758        assert!(!Indicator::text("").has_content());
1759        assert!(Indicator::text("NEW").has_content());
1760    }
1761
1762    #[test]
1763    fn a_capped_badge_still_says_its_real_count() {
1764        let ctx = Context::default();
1765        let r = Indicator::count(1234).id("unread").describe(&ctx);
1766        assert_eq!(r.text.as_deref(), Some("99+"));
1767        assert_eq!(r.name.as_deref(), Some("1234"));
1768        assert_eq!(r.value, Some(1234.0));
1769        let json = serde_json::to_value(&r).unwrap();
1770        assert_eq!(json["kind"], "badge");
1771        assert_eq!(json["state"], "count");
1772        assert_eq!(json["tone"], "accent");
1773        assert_eq!(json["interactive"], false);
1774    }
1775
1776    #[test]
1777    fn anchors_follow_the_direction() {
1778        let host = Rect::from_min_size(pos2(100.0, 100.0), vec2(40.0, 20.0));
1779        let size = vec2(8.0, 8.0);
1780        let ltr = Anchor::TopEnd.place(host, size, Direction::LeftToRight, false, 2.0);
1781        assert_eq!(ltr.right_top(), pos2(138.0, 102.0));
1782        let rtl = Anchor::TopEnd.place(host, size, Direction::RightToLeft, false, 2.0);
1783        assert_eq!(rtl.left_top(), pos2(102.0, 102.0));
1784        let start = Anchor::Start.place(host, size, Direction::LeftToRight, false, 0.0);
1785        assert_eq!(start.left_center(), pos2(100.0, 110.0));
1786        let end = Anchor::End.place(host, size, Direction::RightToLeft, false, 0.0);
1787        assert_eq!(end.left_center(), pos2(100.0, 110.0));
1788        let center = Anchor::Center.place(host, size, Direction::LeftToRight, true, 2.0);
1789        assert_eq!(center.center(), host.center());
1790    }
1791
1792    #[test]
1793    fn an_overhanging_mark_passes_the_corner_by_half_its_height() {
1794        let host = Rect::from_min_size(pos2(0.0, 0.0), vec2(24.0, 24.0));
1795        // A dot is centred on the corner.
1796        let dot = Anchor::TopEnd.place(host, vec2(8.0, 8.0), Direction::LeftToRight, true, 2.0);
1797        assert_eq!(dot.center(), pos2(24.0, 0.0));
1798        // A wider badge has its end cap on the corner, its middle on the edge.
1799        let badge =
1800            Anchor::BottomStart.place(host, vec2(28.0, 16.0), Direction::LeftToRight, true, 2.0);
1801        assert_eq!(badge.left(), -8.0);
1802        assert_eq!(badge.center().y, 24.0);
1803        // Edges never overhang.
1804        let end = Anchor::End.place(host, vec2(8.0, 8.0), Direction::LeftToRight, true, 2.0);
1805        assert!(host.contains_rect(end));
1806    }
1807
1808    #[test]
1809    fn defaults_name_every_state_without_colour() {
1810        let ctx = Context::default();
1811        for led in Led::ALL {
1812            assert!(Indicator::led(led).meaning(&ctx).is_some(), "{led:?}");
1813        }
1814        for flag in Flag::ALL {
1815            assert!(Indicator::flag(flag).meaning(&ctx).is_some(), "{flag:?}");
1816        }
1817        for pip in [Pip::Busy, Pip::Progress(0.42), Pip::Done, Pip::Failed] {
1818            assert!(Indicator::pip(pip).meaning(&ctx).is_some(), "{pip:?}");
1819        }
1820        assert_eq!(
1821            Indicator::pip(Pip::Progress(0.42)).meaning(&ctx).as_deref(),
1822            Some("42%")
1823        );
1824        assert_eq!(
1825            Indicator::swatch(Color32::from_rgb(255, 0, 16))
1826                .meaning(&ctx)
1827                .as_deref(),
1828            Some("#ff0010")
1829        );
1830        // A plain dot has no meaning until it is given one.
1831        assert_eq!(Indicator::dot(Tone::Accent).meaning(&ctx), None);
1832        assert_eq!(
1833            Indicator::dot(Tone::Accent)
1834                .name("Changed")
1835                .meaning(&ctx)
1836                .as_deref(),
1837            Some("Changed")
1838        );
1839    }
1840
1841    #[test]
1842    fn the_pulse_is_still_under_reduced_motion_and_ends() {
1843        let ctx = Context::default();
1844        crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
1845        let clock = motion::freeze(&ctx, 10.0);
1846        let lk = Looks::of(&ctx);
1847        let busy = Indicator::led(Led::Busy);
1848        let Pulse::Moving(a) = busy.pulse(&ctx, &lk) else {
1849            panic!("a busy LED pulses");
1850        };
1851        assert_eq!(
1852            busy.pulse(&ctx, &lk),
1853            Pulse::Moving(a),
1854            "a frozen clock, a frozen pulse"
1855        );
1856        let called = Indicator::count(3).attention(10.0);
1857        assert!(matches!(called.pulse(&ctx, &lk), Pulse::Moving(_)));
1858        clock.set(10.0 + f64::from(lk.pulse_period) * f64::from(lk.pulse_count) + 0.01);
1859        assert_eq!(called.pulse(&ctx, &lk), Pulse::None, "attention ends");
1860        assert_eq!(Indicator::led(Led::On).pulse(&ctx, &lk), Pulse::None);
1861        crate::theme::install(
1862            &ctx,
1863            &crate::theme::ThemeSpec::new("pop-dark").reduced_motion(true),
1864        );
1865        assert_eq!(busy.pulse(&ctx, &lk), Pulse::Still);
1866    }
1867
1868    #[test]
1869    fn the_interactive_target_is_never_under_24_points() {
1870        let ctx = Context::default();
1871        crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
1872        let target = Looks::of(&ctx).target;
1873        assert!(target.x >= MIN_TARGET && target.y >= MIN_TARGET);
1874    }
1875}