tablero 0.6.0

A fast, native Wayland status bar for Hyprland
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! The volume widget and its normalized audio-output model.
//!
//! [`Volume`] is the typed, normalized snapshot a producer feeds in through
//! [`Msg::Volume`]; [`VolumeWidget`] renders it, repainting
//! only when the visible state (level, mute, or device kind) actually changes.
//!
//! The widget reserves a slot only when the source has something to show — a
//! fresh bar with no PipeWire yet (or a system running PipeWire but with no
//! output) measures zero, exactly as the `network` and `system` widgets do.
//! That keeps the right zone clean when audio is not in play; the bluetooth
//! "always show `unavailable`" pattern does not apply here because an absent
//! audio server usually means the user has none, not that the user is interested
//! in seeing a placeholder.
//!
//! The level bucket drives the icon, and the label is the bare `N%` the user
//! reads at a glance (the `format` key can reshape it). A muted sink shows the
//! muted icon alone; the level, device, and mute state live in the hover
//! tooltip. Keeping the pill short is what keeps the widget narrow enough to
//! live in the right cluster next to the other status pills.

use crate::icon::BuiltinIcon;
use crate::render::{Bounds, RenderContext};

use super::{
    IconSetting, LaunchSpec, Msg, ResolvedIcon, Tooltip, Widget, WidgetStyle, draw_icon_content,
    expand, measure_icon_content,
};

/// The default label: the level icon followed by the bare percentage.
const DEFAULT_FORMAT: &str = "{icon}{percent}%";

/// Placeholders accepted by the volume `format` and `tooltip-format`.
pub const VOLUME_PLACEHOLDERS: &[&str] = &["icon", "percent", "device"];

/// Validate a volume `format` or `tooltip-format`.
pub fn validate_volume_format(format: &str) -> Result<(), String> {
    super::validate_placeholders(format, VOLUME_PLACEHOLDERS)
}

/// The kind of audio output the active sink represents, derived from the
/// PipeWire `device.icon-name` (preferred) or `device.form-factor` (fallback).
///
/// The variant is retained on the snapshot so a sink switch counts as a visible
/// change worth repainting, even though the rendered icon now follows the
/// level bucket rather than the device. It is not surfaced in the default
/// label; the tooltip and the `{device}` placeholder name it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceKind {
    /// Headphones (`device.icon-name` in `audio-headphones*` or
    /// `device.form-factor` in `headphone`).
    Headphones,
    /// A headset (headphones with a microphone, `audio-headset*` / `headset`).
    Headset,
    /// Speakers (any of the `audio-speakers*` icons or `speaker` form factor).
    Speakers,
    /// A monitor / TV output (HDMI, DisplayPort) — `device.icon-name` matches
    /// `video-display*` or `device.form-factor` is `monitor` or `tv`.
    Monitor,
    /// A phone (e.g. a paired handset) — `phone` / `audio-handsfree*`.
    Phone,
    /// A television output (form factor `tv` when the icon name did not match
    /// the `Monitor` branch).
    Tv,
    /// Anything the heuristics could not classify (no icon, unknown form
    /// factor, or a custom value).
    Other,
}

impl DeviceKind {
    /// A short human-readable name, used by the tooltip and `{device}`.
    pub fn label(self) -> &'static str {
        match self {
            DeviceKind::Headphones => "Headphones",
            DeviceKind::Headset => "Headset",
            DeviceKind::Speakers => "Speakers",
            DeviceKind::Monitor => "Monitor",
            DeviceKind::Phone => "Phone",
            DeviceKind::Tv => "TV",
            DeviceKind::Other => "Other",
        }
    }
}

/// A normalized snapshot of the active output sink: the playback level (whole
/// percent) and the current mute state, plus the device kind retained for
/// change detection.
///
/// Normalization happens once, at the producer boundary, so the widget and the
/// redraw policy compare clean, canonical values: `level` is clamped to
/// `0..=100` and rounded to a whole percent, `NaN`/negative inputs become zero,
/// and the mute flag is honored verbatim. Equality is therefore a faithful
/// "does this look different on screen?" test — sub-percent jitter from
/// sampling never forces a repaint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Volume {
    level: u8,
    muted: bool,
    device: DeviceKind,
}

impl Volume {
    /// Build a normalized snapshot from a raw linear `level` in `0.0..=1.0`
    /// (the unit PipeWire returns), a `muted` flag, and a `device` kind.
    ///
    /// The level is clamped to `0.0..=1.0` and multiplied by 100, rounding to
    /// the nearest whole percent; a `NaN`/negative input becomes `0`, a value
    /// above `1.0` becomes `100`. Pass the producer's readings verbatim; the
    /// clamping here is the single place out-of-range values are tamed.
    pub fn new(level: f32, muted: bool, device: DeviceKind) -> Self {
        Self {
            level: normalize_level(level),
            muted,
            device,
        }
    }

    /// The normalized level, `0..=100`.
    pub fn level(self) -> u8 {
        self.level
    }

    /// Whether the active sink is muted.
    pub fn muted(self) -> bool {
        self.muted
    }

    /// The device kind the snapshot was taken from — retained so a sink switch
    /// registers as a visible change.
    pub fn device(self) -> DeviceKind {
        self.device
    }

    /// A short plain-text summary, e.g. `"42%"` or `"Muted"`.
    ///
    /// The summary is intentionally device-blind so it stays short. Keeping
    /// this a pure function makes the reading deterministic and unit-testable
    /// without painting pixels.
    pub fn label(self) -> String {
        if self.muted {
            "Muted".to_string()
        } else {
            format!("{}%", self.level)
        }
    }
}

/// Clamp a raw linear level to `0.0..=1.0`, multiply by 100, round to a whole
/// percent, and map `NaN`/negative to `0`.
fn normalize_level(value: f32) -> u8 {
    if value.is_nan() || value <= 0.0 {
        0
    } else if value >= 1.0 {
        100
    } else {
        (value * 100.0).round() as u8
    }
}

/// A bar widget showing the active output sink's volume or mute state.
///
/// Holds the last snapshot it was given so [`update`](Widget::update) can
/// report a visible change only when the normalized snapshot actually differs
/// — a repeated identical reading keeps the loop idle. The snapshot is an
/// [`Option`]: `None` is the pre-first-reading state, which renders as empty
/// space (the widget measures zero and reserves no slot) — so a system
/// without PipeWire, or a PipeWire install with no audio sinks, is shown the
/// same whether the source is absent or just hasn't reported yet. Its resolved
/// [`WidgetStyle`] decides the glyph, the optional pill, and the colors it
/// draws with. An optional `on_click` path turns clicks into a
/// [`Command::RunProgram`](super::Command::RunProgram) so the user can wire a
/// volume manager launcher (e.g. `pavucontrol`, `wpctl`-wrapping script)
/// without writing Rust.
pub struct VolumeWidget {
    bounds: Bounds,
    state: Option<Volume>,
    style: WidgetStyle,
    on_click: Option<LaunchSpec>,
    format: String,
    /// A user-supplied low-to-high `{icon}` ramp; `None` keeps the built-in
    /// speaker art.
    format_icons: Option<Vec<String>>,
    /// A user-supplied muted glyph; `None` keeps the built-in muted art.
    muted_icon: Option<String>,
    tooltip: bool,
    /// A custom tooltip template; `None` uses the built-in summary.
    tooltip_format: Option<String>,
}

impl VolumeWidget {
    /// Create a volume widget occupying `bounds`, empty until its first
    /// [`Msg::Volume`] and carrying the default (flat,
    /// glyph-on) style.
    pub fn new(bounds: Bounds) -> Self {
        Self {
            bounds,
            state: None,
            style: WidgetStyle::default(),
            on_click: None,
            format: DEFAULT_FORMAT.to_string(),
            format_icons: None,
            muted_icon: None,
            tooltip: true,
            tooltip_format: None,
        }
    }

    /// Set the label format (`{icon}`, `{percent}`, `{device}`).
    pub fn with_format(mut self, format: Option<String>) -> Self {
        if let Some(format) = format {
            self.format = format;
        }
        self
    }

    /// Set a low-to-high text icon ramp for the unmuted levels.
    pub fn with_format_icons(mut self, icons: Option<Vec<String>>) -> Self {
        self.format_icons = icons.filter(|icons| !icons.is_empty());
        self
    }

    /// Set the text glyph shown while muted.
    pub fn with_muted_icon(mut self, icon: Option<String>) -> Self {
        self.muted_icon = icon;
        self
    }

    /// Enable or disable the hover tooltip.
    pub fn with_tooltip(mut self, tooltip: Option<bool>) -> Self {
        if let Some(tooltip) = tooltip {
            self.tooltip = tooltip;
        }
        self
    }

    /// Set a custom tooltip format (same placeholders as `format`).
    pub fn with_tooltip_format(mut self, format: Option<String>) -> Self {
        if format.is_some() {
            self.tooltip_format = format;
        }
        self
    }

    /// Set the resolved visual style, consuming and returning `self` so it
    /// chains off [`new`](VolumeWidget::new) at build time.
    pub fn with_style(mut self, style: WidgetStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the executable path run when the widget is clicked.
    ///
    /// When `None`, the widget is display-only and clicks yield nothing; when
    /// `Some(path)`, a left-click anywhere inside the widget's bounds produces
    /// a [`Command::RunProgram`](super::Command::RunProgram) the host executor
    /// spawns directly (no shell). Consuming and returning `self` chains off
    /// [`new`](VolumeWidget::new) at build time.
    pub fn with_on_click(mut self, path: Option<LaunchSpec>) -> Self {
        self.on_click = path;
        self
    }

    /// The currently displayed label (empty before the first reading, or while
    /// the source is unavailable).
    pub fn label(&self) -> String {
        self.state.map(Volume::label).unwrap_or_default()
    }

    /// The pill template: the configured format with `{percent}`/`{device}`
    /// filled in, or the bare `{icon}` while muted. Empty before the first
    /// reading, so the widget reserves no slot.
    fn template(&self) -> String {
        match &self.state {
            Some(volume) if volume.muted() => "{icon}".to_string(),
            Some(volume) => self.expand(&self.format, *volume),
            None => String::new(),
        }
    }

    fn expand(&self, format: &str, volume: Volume) -> String {
        expand(
            format,
            &[
                ("percent", &volume.level().to_string()),
                ("device", volume.device().label()),
            ],
        )
    }

    /// The expanded hover tooltip, when enabled and a reading exists.
    pub fn tooltip_text(&self) -> Option<String> {
        if !self.tooltip {
            return None;
        }
        let volume = self.state?;
        Some(match &self.tooltip_format {
            Some(format) => {
                let icon = match self.icon() {
                    ResolvedIcon::Text(icon) => icon,
                    _ => String::new(),
                };
                self.expand(format, volume).replace("{icon}", &icon)
            }
            None => {
                let mut text = format!(
                    "Volume: {}%\nDevice: {}",
                    volume.level(),
                    volume.device().label()
                );
                if volume.muted() {
                    text.push_str("\nMuted");
                }
                text
            }
        })
    }

    fn contains(&self, px: u32, py: u32) -> bool {
        let b = self.bounds;
        px >= b.x && px < b.x + b.width && py >= b.y && py < b.y + b.height
    }

    /// The speaker icon for the current level bucket — muted, then low/medium/high
    /// by percent — resolved against the style so a custom `icon`/`icon = "none"`
    /// still overrides it, and against any `format-icons` text ramp or muted
    /// glyph. `None` before the first reading (nothing to show).
    fn icon(&self) -> ResolvedIcon {
        if let (IconSetting::Default, Some(volume)) = (&self.style.icon, &self.state) {
            if volume.muted() {
                if let Some(icon) = &self.muted_icon {
                    return ResolvedIcon::Text(icon.clone());
                }
            } else if let Some(icons) = &self.format_icons {
                let index = (usize::from(volume.level()) * icons.len()) / 101;
                return ResolvedIcon::Text(icons[index].clone());
            }
        }
        let default = match &self.state {
            // 0% is silent whether or not the mute flag is set, so it reads as
            // muted rather than as the quietest audible step.
            Some(volume) if volume.muted() || volume.level() == 0 => BuiltinIcon::VolumeMuted,
            Some(volume) => match volume.level() {
                1..=33 => BuiltinIcon::VolumeLow,
                34..=66 => BuiltinIcon::VolumeMedium,
                _ => BuiltinIcon::VolumeHigh,
            },
            None => return ResolvedIcon::None,
        };
        self.style.resolve_icon(default)
    }
}

impl Widget for VolumeWidget {
    fn update(&mut self, msg: &Msg) -> bool {
        match msg {
            Msg::Volume(next) => {
                if self.state == *next {
                    return false;
                }
                self.state = *next;
                true
            }
            _ => false,
        }
    }

    #[hotpath::measure(impl_type = "VolumeWidget")]
    fn draw(&self, ctx: &mut RenderContext) {
        // An absent volume leaves the template empty, so the pill paints
        // nothing: the dashboard has already cleared the background.
        draw_icon_content(
            ctx,
            &self.style,
            self.bounds,
            &self.icon(),
            &self.template(),
            self.style.base_colors(),
        );
    }

    #[hotpath::measure(impl_type = "VolumeWidget")]
    fn measure(&self, ctx: &mut RenderContext, _height: u32) -> u32 {
        measure_icon_content(ctx, &self.style, &self.icon(), &self.template())
    }

    fn bounds(&self) -> Bounds {
        self.bounds
    }

    fn set_bounds(&mut self, bounds: Bounds) {
        self.bounds = bounds;
    }

    fn on_click(&self, px: u32, py: u32, button: super::ClickButton) -> Option<super::Command> {
        // Single-action widget: only the primary button launches the mixer.
        if button != super::ClickButton::Left {
            return None;
        }
        // Only interactive when an on-click path was configured at build time;
        // otherwise the default (None) is correct.
        let path = self.on_click.as_ref()?;
        if !self.contains(px, py) {
            return None;
        }
        Some(super::Command::RunProgram(path.clone()))
    }

    fn tooltip_at(&self, px: u32, py: u32) -> Option<Tooltip> {
        if !self.contains(px, py) {
            return None;
        }
        Some(Tooltip {
            text: self.tooltip_text()?,
            bounds: self.bounds,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::ClickButton;
    use chrono::{Local, TimeZone};

    fn vol(level: f32, muted: bool, device: DeviceKind) -> Msg {
        Msg::Volume(Some(Volume::new(level, muted, device)))
    }

    #[test]
    fn new_clamps_a_negative_level_to_zero() {
        let v = Volume::new(-0.5, false, DeviceKind::Speakers);
        assert_eq!(v.level(), 0);
    }

    #[test]
    fn new_clamps_an_above_one_level_to_one_hundred() {
        let v = Volume::new(2.5, false, DeviceKind::Speakers);
        assert_eq!(v.level(), 100);
    }

    #[test]
    fn new_rounds_a_sub_percent_level_to_the_nearest_whole_percent() {
        let v = Volume::new(0.424, false, DeviceKind::Speakers);
        assert_eq!(v.level(), 42);
        let v = Volume::new(0.426, false, DeviceKind::Speakers);
        assert_eq!(v.level(), 43);
    }

    #[test]
    fn new_treats_nan_and_zero_levels_as_zero() {
        assert_eq!(Volume::new(f32::NAN, false, DeviceKind::Other).level(), 0);
        assert_eq!(Volume::new(0.0, false, DeviceKind::Other).level(), 0);
    }

    #[test]
    fn label_shows_the_bare_percent_when_unmuted() {
        assert_eq!(
            Volume::new(0.42, false, DeviceKind::Speakers).label(),
            "42%"
        );
    }

    #[test]
    fn label_shows_mute_when_muted() {
        // Mute always reads "Muted" — the level is irrelevant.
        assert_eq!(
            Volume::new(0.42, true, DeviceKind::Speakers).label(),
            "Muted"
        );
        assert_eq!(Volume::new(0.0, true, DeviceKind::Other).label(), "Muted");
    }

    #[test]
    fn label_does_not_include_the_device_name() {
        // The label stays short regardless of the device kind — the glyph is
        // the device hint, the label is the level.
        for device in [
            DeviceKind::Headphones,
            DeviceKind::Headset,
            DeviceKind::Speakers,
            DeviceKind::Monitor,
            DeviceKind::Phone,
            DeviceKind::Tv,
            DeviceKind::Other,
        ] {
            assert_eq!(Volume::new(0.5, false, device).label(), "50%");
        }
    }

    #[test]
    fn first_reading_changes_state_and_sets_label() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert_eq!(widget.label(), "");
        assert!(widget.update(&vol(0.42, false, DeviceKind::Speakers)));
        assert_eq!(widget.label(), "42%");
    }

    #[test]
    fn identical_reading_is_not_a_visible_change() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&vol(0.42, false, DeviceKind::Speakers)));
        // Sub-percent jitter normalizes to the same whole percent: no repaint.
        assert!(!widget.update(&vol(0.424, false, DeviceKind::Speakers)));
        assert_eq!(widget.label(), "42%");
    }

    #[test]
    fn a_new_level_is_a_visible_change() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&vol(0.42, false, DeviceKind::Speakers)));
        assert!(widget.update(&vol(0.65, false, DeviceKind::Speakers)));
        assert_eq!(widget.label(), "65%");
    }

    #[test]
    fn a_toggle_to_mute_is_a_visible_change() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&vol(0.42, false, DeviceKind::Speakers)));
        assert!(widget.update(&vol(0.42, true, DeviceKind::Speakers)));
        assert_eq!(widget.label(), "Muted");
    }

    #[test]
    fn a_toggle_back_from_mute_is_a_visible_change() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&vol(0.42, true, DeviceKind::Speakers)));
        assert!(widget.update(&vol(0.42, false, DeviceKind::Speakers)));
        assert_eq!(widget.label(), "42%");
    }

    #[test]
    fn a_new_device_kind_is_a_visible_change() {
        // Even at the same level and mute state, switching from speakers to
        // headphones changes the rendered glyph — the user needs to see the
        // difference, so the snapshot carries the device and equality says
        // they are not the same.
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&vol(0.5, false, DeviceKind::Speakers)));
        assert!(widget.update(&vol(0.5, false, DeviceKind::Headphones)));
    }

    #[test]
    fn a_volume_going_absent_is_a_visible_change_then_blank() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&vol(0.42, false, DeviceKind::Speakers)));
        // PipeWire gone or no sinks: the snapshot is now None.
        assert!(widget.update(&Msg::Volume(None)));
        assert_eq!(widget.label(), "");
    }

    #[test]
    fn absent_reading_before_any_volume_is_not_a_change() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        // "Unavailable" matches the empty initial state, so nothing to repaint.
        assert!(!widget.update(&Msg::Volume(None)));
        assert_eq!(widget.label(), "");
    }

    #[test]
    fn unrelated_message_is_ignored() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        widget.update(&vol(0.42, false, DeviceKind::Speakers));
        let tick = Msg::Tick(Local.with_ymd_and_hms(2026, 6, 27, 8, 0, 0).unwrap());
        assert!(!widget.update(&tick));
        assert_eq!(widget.label(), "42%");
    }

    #[test]
    fn set_bounds_repositions_the_widget() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 1, 1));
        widget.set_bounds(Bounds::new(10, 0, 200, 32));
        assert_eq!(widget.bounds(), Bounds::new(10, 0, 200, 32));
    }

    #[test]
    fn icon_reflects_the_level_bucket_and_mute() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        // Nothing to show before the first reading: no icon, no slot.
        assert_eq!(widget.icon(), ResolvedIcon::None);
        assert_eq!(widget.template(), "");
        // Low / medium / high buckets by level.
        widget.update(&vol(0.10, false, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::Builtin(BuiltinIcon::VolumeLow));
        widget.update(&vol(0.50, false, DeviceKind::Speakers));
        assert_eq!(
            widget.icon(),
            ResolvedIcon::Builtin(BuiltinIcon::VolumeMedium)
        );
        widget.update(&vol(0.90, false, DeviceKind::Speakers));
        assert_eq!(
            widget.icon(),
            ResolvedIcon::Builtin(BuiltinIcon::VolumeHigh)
        );
        // Muted always wins over the level.
        widget.update(&vol(0.90, true, DeviceKind::Speakers));
        assert_eq!(
            widget.icon(),
            ResolvedIcon::Builtin(BuiltinIcon::VolumeMuted)
        );
        // 0% is silent, so it takes the muted icon even with the flag clear.
        widget.update(&vol(0.0, false, DeviceKind::Speakers));
        assert_eq!(
            widget.icon(),
            ResolvedIcon::Builtin(BuiltinIcon::VolumeMuted)
        );
    }

    #[test]
    fn template_pairs_the_icon_slot_with_the_label() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        widget.update(&vol(0.42, false, DeviceKind::Speakers));
        assert_eq!(widget.template(), "{icon}42%");
        // Muted shows the muted icon alone; the level moves to the tooltip.
        widget.update(&vol(0.42, true, DeviceKind::Speakers));
        assert_eq!(widget.template(), "{icon}");
    }

    #[test]
    fn a_custom_icon_setting_overrides_the_built_in() {
        // The widget's resolved WidgetStyle can override the built-in icon with
        // a text glyph of the user's choosing.
        let style = WidgetStyle {
            icon: crate::widget::IconSetting::Custom("\u{f013}".to_string()),
            ..WidgetStyle::default()
        };
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32)).with_style(style);
        widget.update(&vol(0.5, false, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::Text("\u{f013}".into()));
    }

    #[test]
    fn icon_none_setting_opts_out_but_keeps_the_label() {
        let style = WidgetStyle {
            icon: crate::widget::IconSetting::None,
            ..WidgetStyle::default()
        };
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32)).with_style(style);
        widget.update(&vol(0.5, false, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::None);
        // The level label still shows even with the icon opted out.
        assert_eq!(widget.template(), "{icon}50%");
    }

    #[test]
    fn no_volume_measures_zero_a_sampled_one_reserves_a_slot() {
        let mut ctx = RenderContext::new(320, 32);
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert_eq!(widget.measure(&mut ctx, 32), 0);
        widget.update(&vol(0.5, false, DeviceKind::Speakers));
        assert!(widget.measure(&mut ctx, 32) > 0);
    }

    #[test]
    fn custom_format_expands_percent_and_device() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32))
            .with_format(Some("{icon} {percent}% {device}".into()));
        widget.update(&vol(0.42, false, DeviceKind::Headphones));
        assert_eq!(widget.template(), "{icon} 42% Headphones");
    }

    #[test]
    fn format_icons_ramp_picks_by_level_and_muted_icon_wins() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32))
            .with_format_icons(Some(vec!["a".into(), "b".into(), "c".into()]))
            .with_muted_icon(Some("m".into()));
        widget.update(&vol(0.10, false, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::Text("a".into()));
        widget.update(&vol(0.50, false, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::Text("b".into()));
        widget.update(&vol(1.0, false, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::Text("c".into()));
        widget.update(&vol(1.0, true, DeviceKind::Speakers));
        assert_eq!(widget.icon(), ResolvedIcon::Text("m".into()));
    }

    #[test]
    fn a_ramp_without_a_muted_icon_keeps_the_built_in_muted_art() {
        let mut widget =
            VolumeWidget::new(Bounds::new(0, 0, 320, 32)).with_format_icons(Some(vec!["a".into()]));
        widget.update(&vol(0.5, true, DeviceKind::Speakers));
        assert_eq!(
            widget.icon(),
            ResolvedIcon::Builtin(BuiltinIcon::VolumeMuted)
        );
    }

    #[test]
    fn default_tooltip_lists_level_device_and_mute() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32));
        assert_eq!(widget.tooltip_text(), None);
        widget.update(&vol(0.42, false, DeviceKind::Speakers));
        assert_eq!(
            widget.tooltip_text().as_deref(),
            Some("Volume: 42%\nDevice: Speakers")
        );
        widget.update(&vol(0.42, true, DeviceKind::Headset));
        assert_eq!(
            widget.tooltip_text().as_deref(),
            Some("Volume: 42%\nDevice: Headset\nMuted")
        );
    }

    #[test]
    fn tooltip_format_and_opt_out() {
        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32))
            .with_tooltip_format(Some("{device} at {percent}%".into()));
        widget.update(&vol(0.42, false, DeviceKind::Tv));
        assert_eq!(widget.tooltip_text().as_deref(), Some("TV at 42%"));
        assert_eq!(
            widget.tooltip_at(10, 10).map(|tip| tip.text),
            Some("TV at 42%".to_string())
        );
        assert_eq!(widget.tooltip_at(400, 10), None);

        let mut widget = VolumeWidget::new(Bounds::new(0, 0, 320, 32)).with_tooltip(Some(false));
        widget.update(&vol(0.42, false, DeviceKind::Tv));
        assert_eq!(widget.tooltip_at(10, 10), None);
    }

    #[test]
    fn without_on_click_a_click_is_a_no_op() {
        let widget = VolumeWidget::new(Bounds::new(0, 0, 200, 32));
        assert_eq!(widget.on_click(10, 10, ClickButton::Left), None);
    }

    #[test]
    fn with_on_click_a_click_inside_bounds_runs_the_program() {
        let widget = VolumeWidget::new(Bounds::new(0, 0, 200, 32))
            .with_on_click(Some(LaunchSpec::program_only("/usr/bin/pavucontrol")));
        assert_eq!(
            widget.on_click(10, 10, ClickButton::Left),
            Some(super::super::Command::RunProgram(LaunchSpec::program_only(
                "/usr/bin/pavucontrol"
            )))
        );
    }

    #[test]
    fn on_click_outside_bounds_is_ignored_even_when_configured() {
        let widget = VolumeWidget::new(Bounds::new(10, 0, 200, 32))
            .with_on_click(Some(LaunchSpec::program_only("/usr/bin/pavucontrol")));
        // x=0 is left of bounds.x=10; click is outside the pill.
        assert_eq!(widget.on_click(0, 10, ClickButton::Left), None);
        // x=210 is at/past the right edge (x + width = 210), outside.
        assert_eq!(widget.on_click(210, 10, ClickButton::Left), None);
        // y=32 is at the bottom edge (height = 32 → y range [0, 32)), outside.
        assert_eq!(widget.on_click(50, 32, ClickButton::Left), None);
    }
}