1use 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
103pub const CAP: u64 = 99;
105
106pub const MIN_TARGET: f32 = 24.0;
109
110#[derive(Clone, Debug, PartialEq)]
114struct Looks {
115 dot: f32,
117 ring: f32,
119 flag: f32,
121 swatch: f32,
123 badge_height: f32,
125 badge_padding: f32,
126 badge_font: f32,
128 pip: f32,
130 icon: f32,
132 target: Vec2,
135 offset: f32,
137 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
196#[serde(rename_all = "snake_case")]
197pub enum Led {
198 Off,
200 On,
202 Busy,
204 Warning,
206 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 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#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
257#[serde(rename_all = "snake_case")]
258pub enum Pip {
259 Busy,
261 Progress(f32),
263 Done,
265 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
290#[serde(rename_all = "snake_case")]
291pub enum FlagShape {
292 Corner,
294 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
315#[serde(rename_all = "snake_case")]
316pub enum Flag {
317 Modified,
319 Pinned,
321 Required,
323 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
391#[serde(rename_all = "snake_case")]
392pub enum ValueMark {
393 Changed,
394 Held(String),
396 Moved(String),
398}
399
400impl ValueMark {
401 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 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#[derive(Clone, Copy, Debug, PartialEq)]
441pub enum Swatch {
442 Color(Color32),
444 None,
446 Mixed,
448}
449
450#[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 Start,
460 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 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 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#[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
542pub fn set_direction(ctx: &Context, direction: Direction) {
544 lock(&drawn_state(ctx)).direction = direction;
545}
546
547pub fn direction(ctx: &Context) -> Direction {
549 lock(&drawn_state(ctx)).direction
550}
551
552pub fn badge_text(count: u64, cap: u64) -> String {
554 if count > cap {
555 format!("{cap}+")
556 } else {
557 count.to_string()
558 }
559}
560
561pub 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 toggle: Option<(bool, Icon)>,
598 },
599}
600
601#[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 pub fn dot(tone: Tone) -> Indicator {
646 Indicator::new(Kind::Dot(None)).tone(tone)
647 }
648
649 pub fn led(state: Led) -> Indicator {
651 Indicator::new(Kind::Dot(Some(state)))
652 }
653
654 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 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 pub fn pip(state: Pip) -> Indicator {
678 Indicator::new(Kind::Pip(state))
679 }
680
681 pub fn flag(flag: Flag) -> Indicator {
683 Indicator::new(Kind::Flag(flag.shape(), Some(flag)))
684 }
685
686 pub fn flag_shape(shape: FlagShape) -> Indicator {
688 Indicator::new(Kind::Flag(shape, None))
689 }
690
691 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 pub fn swatch(color: Color32) -> Indicator {
700 Indicator::new(Kind::Swatch(Swatch::Color(color)))
701 }
702
703 pub fn swatch_of(swatch: Swatch) -> Indicator {
705 Indicator::new(Kind::Swatch(swatch))
706 }
707
708 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 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 pub fn id(mut self, id: impl Into<String>) -> Self {
733 self.key = Some(id.into());
734 self
735 }
736
737 pub fn name(mut self, name: impl Into<String>) -> Self {
741 self.name = Some(name.into());
742 self
743 }
744
745 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 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 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 pub fn interactive(mut self, action: impl Into<String>) -> Self {
781 self.action = Some(action.into());
782 self
783 }
784
785 pub fn command(mut self, command: CommandId) -> Self {
788 self.command = Some(command);
789 self
790 }
791
792 pub fn disabled(mut self, reason: impl Into<String>) -> Self {
794 self.disabled = Some(reason.into());
795 self
796 }
797
798 pub fn attention(mut self, since: f64) -> Self {
802 self.attention = Some(since);
803 self
804 }
805
806 pub fn delayed(mut self, id: Id, since: f64, busy: bool) -> Self {
810 self.delayed = Some((id, since, busy));
811 self
812 }
813
814 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 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 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 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 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 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 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 pub fn measure(&self, ui: &Ui) -> Vec2 {
1033 self.mark_size(ui.painter(), &Looks::of(ui.ctx()))
1034 }
1035
1036 pub fn show(self, ui: &mut Ui) -> Response {
1039 self.ui(ui)
1040 }
1041
1042 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 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 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 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 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 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 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 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 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 match swatch {
1378 Swatch::Color(col) if col.is_opaque() => {
1379 p.rect_filled(rect, radius, *col);
1380 }
1381 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 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
1464pub trait IndicatorExt {
1466 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#[derive(Clone, Debug, PartialEq, Serialize)]
1480pub struct Record {
1481 pub id: String,
1483 pub kind: &'static str,
1486 pub state: String,
1491 pub value: Option<f64>,
1493 pub text: Option<String>,
1495 pub tone: Tone,
1496 pub name: Option<String>,
1498 pub action: Option<String>,
1500 pub host: Option<String>,
1503 pub interactive: bool,
1504 pub enabled: bool,
1505 pub shown: bool,
1507 pub pulsing: bool,
1508 pub command: Option<String>,
1509 pub rect: [f32; 4],
1511}
1512
1513pub 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 s.last.clone()
1522 } else if s.pass + 1 == now {
1523 s.building.clone()
1525 } else {
1526 Vec::new()
1527 }
1528}
1529
1530pub fn find(ctx: &Context, id: &str) -> Option<Record> {
1532 drawn(ctx).into_iter().find(|r| r.id == id)
1533}
1534
1535pub 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 pass: u64,
1545 building: Vec<Record>,
1546 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
1567fn 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
1597fn 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 Moving(f32),
1615 Still,
1617}
1618
1619struct Look {
1620 color: Color32,
1621 on_host: bool,
1622 corner: (bool, bool),
1624 pulse: Pulse,
1625 ring: f32,
1627 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
1658fn 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 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 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 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 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}