tablero 0.2.1

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
//! The network widget and its normalized connectivity model.
//!
//! [`Network`] is the typed, normalized snapshot a producer feeds in through
//! [`Msg::Network`]; [`NetworkWidget`] renders it compactly,
//! repainting only when the visible connection state or SSID actually changes.
//!
//! Unavailable connectivity (or an unreachable network daemon) is carried as
//! `Msg::Network(None)`: the widget then shows nothing, exactly as it does before
//! its first reading, so a machine with no network stack never paints a stale or
//! placeholder value.

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

use super::{Msg, Tooltip, Widget, WidgetStyle, draw_text_pill, glyph_label, measure_text_pill};

/// Default network glyphs (Font Awesome, via Nerd Font), chosen by connection
/// state: a wifi arc, a wired sitemap, a cross when disconnected, and a question
/// mark when the state is indeterminate.
const WIRELESS_GLYPH: &str = "\u{f1eb}"; // nf-fa-wifi
const WIRED_GLYPH: &str = "\u{f0e8}"; // nf-fa-sitemap
const DISCONNECTED_GLYPH: &str = "\u{f00d}"; // nf-fa-times
const UNKNOWN_GLYPH: &str = "\u{f128}"; // nf-fa-question

/// The kind of network connection in use, normalized from a raw daemon reading.
///
/// The many low-level NetworkManager states collapse into these four so the bar
/// can choose one unambiguous glyph: the user only needs to know whether they are
/// off the network, on a wired link, on Wi-Fi, or in an indeterminate state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkState {
    /// No active connection.
    Disconnected,
    /// Connected over a wired (Ethernet) link.
    Wired,
    /// Connected over a wireless (Wi-Fi) link.
    Wireless,
    /// Connectivity could not be determined.
    Unknown,
}

impl NetworkState {
    /// A short, human-readable label for the state.
    pub fn label(self) -> &'static str {
        match self {
            NetworkState::Disconnected => "disconnected",
            NetworkState::Wired => "wired",
            NetworkState::Wireless => "wifi",
            NetworkState::Unknown => "unknown",
        }
    }
}

/// A normalized snapshot of connectivity: the connection state plus, for a
/// wireless link, the network name (SSID).
///
/// Normalization happens once, at the producer boundary, so the widget and the
/// redraw policy compare clean, canonical values. The SSID is meaningful only on
/// a wireless link, so it is retained solely when the state is
/// [`Wireless`](NetworkState::Wireless) and the name is non-empty after trimming;
/// in every other case it is dropped to `None`. A blank or whitespace-only SSID
/// is therefore never shown — the widget falls back to the bare state label
/// rather than painting an empty `"wifi "`. Equality is a faithful "does this
/// look different on screen?" test.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Network {
    state: NetworkState,
    ssid: Option<String>,
}

impl Network {
    /// Build a normalized snapshot from a connection `state` and an optional raw
    /// `ssid`.
    ///
    /// The SSID is kept only on a wireless link and only when it has non-blank
    /// content (it is trimmed first); otherwise it is discarded. Pass the
    /// daemon's reading verbatim — the filtering here is the single place a
    /// missing or meaningless name is tamed.
    pub fn new(state: NetworkState, ssid: Option<&str>) -> Self {
        let ssid = if state == NetworkState::Wireless {
            ssid.map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_owned)
        } else {
            None
        };
        Self { state, ssid }
    }

    /// The normalized connection state.
    pub fn state(&self) -> NetworkState {
        self.state
    }

    /// The wireless network name, present only on a wireless link with a
    /// non-blank SSID.
    pub fn ssid(&self) -> Option<&str> {
        self.ssid.as_deref()
    }

    /// The compact display label, e.g. `"home-net"`, `"wired"`, or
    /// `"disconnected"`.
    ///
    /// The Wi-Fi glyph already communicates the connection type, so a wireless
    /// link shows only its SSID. Without one, the glyph stands alone. Keeping
    /// this a pure function makes the rendered text deterministic and
    /// unit-testable without painting pixels.
    pub fn label(&self) -> String {
        match (self.state, self.ssid.as_deref()) {
            (NetworkState::Wireless, Some(ssid)) => ssid.to_string(),
            (NetworkState::Wireless, None) => String::new(),
            _ => self.state.label().to_string(),
        }
    }
}

/// The default glyph for a connection state: a wifi arc on a wireless link, a
/// sitemap on a wired one, a cross when disconnected, and a question mark when
/// the state is indeterminate.
fn default_glyph(state: NetworkState) -> &'static str {
    match state {
        NetworkState::Wireless => WIRELESS_GLYPH,
        NetworkState::Wired => WIRED_GLYPH,
        NetworkState::Disconnected => DISCONNECTED_GLYPH,
        NetworkState::Unknown => UNKNOWN_GLYPH,
    }
}

/// A bar widget showing the network connection state and, on Wi-Fi, the SSID.
///
/// Holds the last snapshot it was given so [`update`](Widget::update) can report
/// a visible change only when the normalized snapshot actually differs. The
/// snapshot is an [`Option`]: `None` is "no network / unavailable", which renders
/// as empty space — identical to the pre-first-reading state, so unavailable
/// connectivity is shown the same whether it was never there or just went away.
/// Its resolved [`WidgetStyle`] decides the glyph, the optional pill, and the
/// colors it draws with.
pub struct NetworkWidget {
    bounds: Bounds,
    state: Option<Network>,
    style: WidgetStyle,
}

impl NetworkWidget {
    /// Create a network widget occupying `bounds`, empty until its first
    /// [`Msg::Network`] and carrying the default (flat,
    /// glyph-on) style.
    pub fn new(bounds: Bounds) -> Self {
        Self {
            bounds,
            state: None,
            style: WidgetStyle::default(),
        }
    }

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

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

    /// The full pill text: the state-derived glyph joined to the label, or empty
    /// while the network is unavailable (so the widget reserves no slot).
    fn display_text(&self) -> String {
        match &self.state {
            Some(network) => glyph_label(
                self.style.glyph(default_glyph(network.state())),
                &network.label(),
            ),
            None => String::new(),
        }
    }

    /// Connection details kept off the bar's compact label.
    pub fn tooltip_text(&self) -> Option<String> {
        self.state.as_ref().map(|network| match network.state() {
            NetworkState::Wireless => match network.ssid() {
                Some(ssid) => format!("Connection: Wi-Fi\nSSID: {ssid}"),
                None => "Connection: Wi-Fi".to_string(),
            },
            NetworkState::Wired => "Connection: Wired".to_string(),
            NetworkState::Disconnected => "Status: Disconnected".to_string(),
            NetworkState::Unknown => "Status: Unknown".to_string(),
        })
    }

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

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

    fn draw(&self, ctx: &mut RenderContext) {
        // An unavailable network leaves `display_text` empty, so the pill paints
        // nothing: the dashboard has already cleared the background.
        draw_text_pill(
            ctx,
            &self.style,
            self.bounds,
            &self.display_text(),
            self.style.base_colors(),
        );
    }

    fn measure(&self, ctx: &mut RenderContext, _height: u32) -> u32 {
        measure_text_pill(ctx, &self.style, &self.display_text())
    }

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

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

    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 chrono::{Local, TimeZone};

    fn network(state: NetworkState, ssid: Option<&str>) -> Msg {
        Msg::Network(Some(Network::new(state, ssid)))
    }

    #[test]
    fn state_labels_are_unambiguous_words() {
        assert_eq!(NetworkState::Disconnected.label(), "disconnected");
        assert_eq!(NetworkState::Wired.label(), "wired");
        assert_eq!(NetworkState::Wireless.label(), "wifi");
        assert_eq!(NetworkState::Unknown.label(), "unknown");
    }

    #[test]
    fn ssid_is_kept_only_on_a_wireless_link() {
        // A wired/disconnected/unknown link never carries an SSID, even if one is
        // offered by the daemon.
        assert_eq!(
            Network::new(NetworkState::Wired, Some("home-net")).ssid(),
            None
        );
        assert_eq!(
            Network::new(NetworkState::Disconnected, Some("home-net")).ssid(),
            None
        );
        assert_eq!(
            Network::new(NetworkState::Unknown, Some("home-net")).ssid(),
            None
        );
        assert_eq!(
            Network::new(NetworkState::Wireless, Some("home-net")).ssid(),
            Some("home-net")
        );
    }

    #[test]
    fn ssid_is_trimmed_and_blank_names_are_dropped() {
        assert_eq!(
            Network::new(NetworkState::Wireless, Some("  home-net  ")).ssid(),
            Some("home-net")
        );
        // Empty and whitespace-only names are meaningless: dropped to None.
        assert_eq!(Network::new(NetworkState::Wireless, Some("")).ssid(), None);
        assert_eq!(
            Network::new(NetworkState::Wireless, Some("   ")).ssid(),
            None
        );
        assert_eq!(Network::new(NetworkState::Wireless, None).ssid(), None);
    }

    #[test]
    fn label_shows_only_the_ssid_on_wifi_and_the_state_otherwise() {
        assert_eq!(
            Network::new(NetworkState::Wireless, Some("home-net")).label(),
            "home-net"
        );
        // With no usable SSID, the state glyph stands alone.
        assert_eq!(Network::new(NetworkState::Wireless, None).label(), "");
        assert_eq!(Network::new(NetworkState::Wired, None).label(), "wired");
        assert_eq!(
            Network::new(NetworkState::Disconnected, None).label(),
            "disconnected"
        );
        assert_eq!(Network::new(NetworkState::Unknown, None).label(), "unknown");
    }

    #[test]
    fn first_reading_changes_state_and_sets_label() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        assert_eq!(widget.label(), "");
        assert!(widget.update(&network(NetworkState::Wireless, Some("home-net"))));
        assert_eq!(widget.label(), "home-net");
    }

    #[test]
    fn identical_reading_is_not_a_visible_change() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&network(NetworkState::Wireless, Some("home-net"))));
        // The same normalized snapshot again (untrimmed name normalizes equal):
        // nothing to repaint.
        assert!(!widget.update(&network(NetworkState::Wireless, Some("  home-net  "))));
        assert_eq!(widget.label(), "home-net");
    }

    #[test]
    fn a_new_ssid_is_a_visible_change() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&network(NetworkState::Wireless, Some("home-net"))));
        assert!(widget.update(&network(NetworkState::Wireless, Some("cafe-net"))));
        assert_eq!(widget.label(), "cafe-net");
    }

    #[test]
    fn a_new_state_is_a_visible_change() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&network(NetworkState::Wireless, Some("home-net"))));
        assert!(widget.update(&network(NetworkState::Wired, None)));
        assert_eq!(widget.label(), "wired");
    }

    #[test]
    fn network_going_absent_is_a_visible_change_then_blank() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        assert!(widget.update(&network(NetworkState::Wireless, Some("home-net"))));
        // Daemon gone / network stack unavailable: the snapshot is now absent.
        assert!(widget.update(&Msg::Network(None)));
        assert_eq!(widget.label(), "");
    }

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

    #[test]
    fn unrelated_message_is_ignored() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        widget.update(&network(NetworkState::Wired, None));
        let tick = Msg::Tick(Local.with_ymd_and_hms(2026, 6, 27, 8, 0, 0).unwrap());
        assert!(!widget.update(&tick));
        assert_eq!(widget.label(), "wired");
    }

    #[test]
    fn set_bounds_repositions_the_widget() {
        let mut widget = NetworkWidget::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 display_text_uses_a_state_driven_glyph() {
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        // Nothing to show before the first reading: no glyph, no slot.
        assert_eq!(widget.display_text(), "");
        // Each connection state picks its own glyph ahead of the label.
        widget.update(&network(NetworkState::Wireless, Some("home-net")));
        assert_eq!(widget.display_text(), format!("{WIRELESS_GLYPH} home-net"));
        widget.update(&network(NetworkState::Wireless, None));
        assert_eq!(widget.display_text(), WIRELESS_GLYPH);
        widget.update(&network(NetworkState::Wired, None));
        assert_eq!(widget.display_text(), format!("{WIRED_GLYPH} wired"));
        widget.update(&network(NetworkState::Disconnected, None));
        assert_eq!(
            widget.display_text(),
            format!("{DISCONNECTED_GLYPH} disconnected")
        );
    }

    #[test]
    fn an_absent_network_measures_zero_a_present_one_reserves_a_slot() {
        let mut ctx = RenderContext::new(320, 32);
        let mut widget = NetworkWidget::new(Bounds::new(0, 0, 320, 32));
        assert_eq!(widget.measure(&mut ctx, 32), 0);
        widget.update(&network(NetworkState::Wired, None));
        assert!(widget.measure(&mut ctx, 32) > 0);
    }

    #[test]
    fn tooltip_keeps_connection_details_off_the_compact_label() {
        let mut widget = NetworkWidget::new(Bounds::new(10, 0, 100, 32));
        widget.update(&network(NetworkState::Wireless, Some("home-net")));

        assert_eq!(widget.label(), "home-net");
        assert_eq!(
            widget.tooltip_at(20, 16).map(|tooltip| tooltip.text),
            Some("Connection: Wi-Fi\nSSID: home-net".to_string())
        );
        assert_eq!(widget.tooltip_at(200, 16), None);
    }
}