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
//! NetworkManager connectivity source.
//!
//! Reads the primary connection from NetworkManager over the system DBus and
//! emits typed [`Msg::Network`] snapshots through the [producer
//! bridge](crate::producer), so connectivity reaches the render loop the same way
//! every other message does — the rendering code never talks to DBus directly.
//!
//! NetworkManager exposes an overall `State` plus a `PrimaryConnection` object
//! path on `org.freedesktop.NetworkManager`. The producer reads those, follows
//! the primary active connection to its `Type` (and, on Wi-Fi, traverses
//! device → access point for the `Ssid` and `Strength`), normalizes
//! the readings into a [`Network`], then re-reads and re-emits whenever the state
//! or primary connection changes, or the active access point's strength moves. Normalization lives in [`network_from_nm`], a
//! pure function the tests drive directly — the full DBus value → message →
//! widget path is covered without a live system bus.

use futures_util::future::{Either, select};
use futures_util::stream::{BoxStream, StreamExt, select_all};
use log::warn;
use zbus::zvariant::OwnedObjectPath;
use zbus::{Connection, proxy};

use crate::widget::{Msg, Network, NetworkState};

use crate::producer::{MsgSender, Producer, ProducerFuture, ProducerResult};

/// Normalize NetworkManager's overall state and the primary connection's type
/// into a [`Network`] snapshot.
///
/// `nm_state` follows NetworkManager's `NMState` enum: `10` asleep, `20`
/// disconnected, `30` disconnecting all read as offline; `40` connecting and
/// `50`/`60`/`70` connected (local/site/global) are classified by `conn_type`;
/// `0` unknown — or anything a future NetworkManager might add — is
/// [`Unknown`](NetworkState::Unknown). `conn_type` is the active connection's
/// `Type` (`"802-3-ethernet"` → wired, `"802-11-wireless"` → wireless, anything
/// else unknown). The `ssid` is passed straight to [`Network::new`], which keeps
/// it only on a wireless link. Pure over its inputs: the integration tests drive
/// the full reading → message → widget path through this without a live bus.
pub fn network_from_nm(nm_state: u32, conn_type: Option<&str>, ssid: Option<&str>) -> Network {
    let state = match nm_state {
        // Asleep, disconnected, or tearing the connection down: offline.
        10 | 20 | 30 => NetworkState::Disconnected,
        // Connecting or connected (local/site/global): classify by link type.
        40 | 50 | 60 | 70 => connection_state(conn_type),
        // Unknown (0) or any value a future NetworkManager might add.
        _ => NetworkState::Unknown,
    };
    Network::new(state, ssid)
}

/// Map an active connection's `Type` string to a connected [`NetworkState`].
///
/// Only the two link kinds the bar distinguishes are recognized; an absent or
/// unrecognized type degrades to [`Unknown`](NetworkState::Unknown) rather than
/// guessing.
fn connection_state(conn_type: Option<&str>) -> NetworkState {
    match conn_type {
        Some("802-3-ethernet") => NetworkState::Wired,
        Some("802-11-wireless") => NetworkState::Wireless,
        _ => NetworkState::Unknown,
    }
}

/// The subset of `org.freedesktop.NetworkManager` the bar reads. zbus generates
/// `NetworkManagerProxy` from this.
#[proxy(
    interface = "org.freedesktop.NetworkManager",
    default_service = "org.freedesktop.NetworkManager",
    default_path = "/org/freedesktop/NetworkManager"
)]
trait NetworkManager {
    /// Overall connectivity state; see [`network_from_nm`] for the value mapping.
    #[zbus(property)]
    fn state(&self) -> zbus::Result<u32>;

    /// Object path of the primary active connection, or `"/"` when there is none.
    #[zbus(property)]
    fn primary_connection(&self) -> zbus::Result<OwnedObjectPath>;
}

/// The subset of `org.freedesktop.NetworkManager.Connection.Active` the bar
/// reads on the primary connection. The path is dynamic, so this proxy is built
/// per-connection.
#[proxy(
    interface = "org.freedesktop.NetworkManager.Connection.Active",
    default_service = "org.freedesktop.NetworkManager"
)]
trait ActiveConnection {
    /// The connection type, e.g. `"802-3-ethernet"` or `"802-11-wireless"`.
    #[zbus(property, name = "Type")]
    fn type_(&self) -> zbus::Result<String>;

    /// Object paths of the devices carrying this connection.
    #[zbus(property)]
    fn devices(&self) -> zbus::Result<Vec<OwnedObjectPath>>;
}

/// The subset of `org.freedesktop.NetworkManager.Device.Wireless` used to reach
/// the active access point of a wireless device.
#[proxy(
    interface = "org.freedesktop.NetworkManager.Device.Wireless",
    default_service = "org.freedesktop.NetworkManager"
)]
trait WirelessDevice {
    /// Object path of the access point currently in use, or `"/"` when none.
    #[zbus(property)]
    fn active_access_point(&self) -> zbus::Result<OwnedObjectPath>;
}

/// The subset of `org.freedesktop.NetworkManager.AccessPoint` carrying the SSID
/// and signal strength.
#[proxy(
    interface = "org.freedesktop.NetworkManager.AccessPoint",
    default_service = "org.freedesktop.NetworkManager"
)]
trait AccessPoint {
    /// The network name as raw bytes (not necessarily valid UTF-8).
    #[zbus(property)]
    fn ssid(&self) -> zbus::Result<Vec<u8>>;

    /// The signal quality in percent.
    #[zbus(property)]
    fn strength(&self) -> zbus::Result<u8>;
}

/// The active access point a wireless snapshot was read from: its proxy (to
/// watch `Strength`) alongside the object path identifying it.
struct ActiveAp {
    path: OwnedObjectPath,
    proxy: AccessPointProxy<'static>,
}

/// Read NetworkManager's current connectivity and normalize it into a snapshot.
///
/// A failed read degrades to `None` (network shown unavailable) and a logged
/// warning rather than ending the stream — a transient DBus hiccup, or
/// NetworkManager not running at all, never takes the source down; the widget
/// simply stays blank.
#[hotpath::measure]
async fn read_snapshot(
    conn: &Connection,
    nm: &NetworkManagerProxy<'_>,
) -> (Option<Network>, Option<ActiveAp>) {
    match try_read(conn, nm).await {
        Ok((network, ap)) => (Some(network), ap),
        Err(e) => {
            warn!("networkmanager: reading network state failed: {e}");
            (None, None)
        }
    }
}

/// Read the overall state and primary connection, following it to a type and
/// (on Wi-Fi) an SSID and signal strength, then fold them into a normalized
/// snapshot, returning the access point it came from so its strength can be
/// watched.
#[hotpath::measure]
async fn try_read(
    conn: &Connection,
    nm: &NetworkManagerProxy<'_>,
) -> zbus::Result<(Network, Option<ActiveAp>)> {
    let state = nm.state().await?;
    let primary = nm.primary_connection().await?;
    // "/" is NetworkManager's "no primary connection": nothing to classify.
    if primary.as_str() == "/" {
        return Ok((network_from_nm(state, None, None), None));
    }

    let active = ActiveConnectionProxy::builder(conn)
        .path(primary)?
        .build()
        .await?;
    let conn_type = active.type_().await?;
    // The access point lives several hops away and only matters on Wi-Fi; a
    // missing one degrades to no name or strength rather than failing the read.
    let ap = if conn_type == "802-11-wireless" {
        read_access_point(conn, &active).await
    } else {
        None
    };
    let (ssid, signal) = match &ap {
        Some(ap) => {
            let ssid = ap
                .proxy
                .ssid()
                .await
                .ok()
                .map(|bytes| String::from_utf8_lossy(&bytes).into_owned());
            (ssid, ap.proxy.strength().await.ok())
        }
        None => (None, None),
    };

    let network = network_from_nm(state, Some(&conn_type), ssid.as_deref()).with_signal(signal);
    Ok((network, ap))
}

/// Best-effort access point lookup for a wireless connection: connection →
/// device → active access point.
///
/// Every hop can be absent (no device, no associated AP) or fail transiently;
/// any of those simply yields `None`, so the widget falls back to the bare
/// Wi-Fi icon rather than erroring. The SSID bytes are decoded lossily by the
/// caller — an SSID is not guaranteed to be valid UTF-8.
#[hotpath::measure]
async fn read_access_point(
    conn: &Connection,
    active: &ActiveConnectionProxy<'_>,
) -> Option<ActiveAp> {
    let device_path = active.devices().await.ok()?.into_iter().next()?;
    let wireless = WirelessDeviceProxy::builder(conn)
        .path(device_path)
        .ok()?
        .build()
        .await
        .ok()?;
    let ap_path = wireless.active_access_point().await.ok()?;
    if ap_path.as_str() == "/" {
        return None;
    }
    let proxy = AccessPointProxy::builder(conn)
        .path(ap_path.clone())
        .ok()?
        .build()
        .await
        .ok()?;
    Some(ActiveAp {
        path: ap_path,
        proxy,
    })
}

/// A [`Producer`] that streams NetworkManager connectivity changes into the
/// render loop.
///
/// Construct with [`new`](NetworkProducer::new) and hand it to the producer
/// bridge; it reads an initial snapshot, then re-reads and emits on every change
/// to the overall state or the primary connection until the system bus closes or
/// the render loop shuts down.
pub struct NetworkProducer;

impl NetworkProducer {
    /// Create a NetworkManager connectivity producer.
    pub fn new() -> Self {
        Self
    }
}

impl Default for NetworkProducer {
    fn default() -> Self {
        Self::new()
    }
}

impl Producer for NetworkProducer {
    fn name(&self) -> String {
        "networkmanager".to_string()
    }

    fn run(self: Box<Self>, tx: MsgSender) -> ProducerFuture {
        Box::pin(run(tx))
    }
}

/// Drive the connectivity stream: initial snapshot, then re-read on each change.
///
/// Returns `Ok(())` once the render loop has gone away (a [`send`] reports the
/// channel closed) or the property streams end. A failed system-bus connection
/// propagates as an error the bridge logs and isolates — the bar keeps running,
/// the network widget simply stays blank.
///
/// [`send`]: MsgSender::send
async fn run(tx: MsgSender) -> ProducerResult {
    let conn = Connection::system().await?;
    let nm = NetworkManagerProxy::new(&conn).await?;

    // Either the overall state or the primary connection changing warrants a
    // re-read; merge the two property streams and re-emit a fresh snapshot on
    // each tick. An unchanged snapshot is harmless — the widget reports no
    // visible change.
    let mut changes = select_all([
        nm.receive_state_changed().await.map(|_| ()).boxed(),
        nm.receive_primary_connection_changed()
            .await
            .map(|_| ())
            .boxed(),
    ]);
    // The active access point's strength is watched too, re-subscribing only
    // when the access point itself changes so a roam or reconnect follows it.
    let mut watched: Option<OwnedObjectPath> = None;
    let mut strength: Option<BoxStream<'static, ()>> = None;

    loop {
        let (snapshot, ap) = read_snapshot(&conn, &nm).await;
        if tx.send(Msg::Network(snapshot)).is_err() {
            return Ok(());
        }
        let path = ap.as_ref().map(|ap| ap.path.clone());
        if path != watched {
            strength = match ap {
                Some(ap) => Some(
                    ap.proxy
                        .receive_strength_changed()
                        .await
                        .map(|_| ())
                        .boxed(),
                ),
                None => None,
            };
            watched = path;
        }

        match strength.as_mut() {
            Some(signal) => match select(changes.next(), signal.next()).await {
                Either::Left((None, _)) => return Ok(()),
                Either::Right((None, _)) => {
                    strength = None;
                    watched = None;
                }
                _ => {}
            },
            None => {
                if changes.next().await.is_none() {
                    return Ok(());
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn offline_states_normalize_to_disconnected() {
        // 10 asleep, 20 disconnected, 30 disconnecting — all offline regardless
        // of any stale connection type.
        for state in [10, 20, 30] {
            let network = network_from_nm(state, Some("802-3-ethernet"), None);
            assert_eq!(network.state(), NetworkState::Disconnected);
        }
    }

    #[test]
    fn connected_ethernet_normalizes_to_wired() {
        // 50/60/70 are connected (local/site/global); 40 is connecting.
        for state in [40, 50, 60, 70] {
            let network = network_from_nm(state, Some("802-3-ethernet"), None);
            assert_eq!(network.state(), NetworkState::Wired);
            assert_eq!(network.label(), "wired");
        }
    }

    #[test]
    fn connected_wireless_keeps_its_ssid() {
        let network = network_from_nm(70, Some("802-11-wireless"), Some("home-net"));
        assert_eq!(network.state(), NetworkState::Wireless);
        assert_eq!(network.ssid(), Some("home-net"));
        assert_eq!(network.label(), "home-net");
    }

    #[test]
    fn connected_wireless_without_ssid_has_no_text_label() {
        let network = network_from_nm(70, Some("802-11-wireless"), None);
        assert_eq!(network.state(), NetworkState::Wireless);
        assert_eq!(network.ssid(), None);
        assert_eq!(network.label(), "");
    }

    #[test]
    fn connected_with_unknown_type_normalizes_to_unknown() {
        // Connected, but the link is neither plain ethernet nor wifi (a VPN,
        // a bridge, a missing type): shown as unknown rather than mislabeled.
        assert_eq!(
            network_from_nm(70, Some("vpn"), None).state(),
            NetworkState::Unknown
        );
        assert_eq!(
            network_from_nm(70, None, None).state(),
            NetworkState::Unknown
        );
    }

    #[test]
    fn unknown_nm_state_normalizes_to_unknown() {
        assert_eq!(
            network_from_nm(0, Some("802-3-ethernet"), None).state(),
            NetworkState::Unknown
        );
        assert_eq!(
            network_from_nm(99, Some("802-11-wireless"), Some("home-net")).state(),
            NetworkState::Unknown
        );
    }

    #[test]
    fn ssid_is_dropped_when_the_link_is_not_wireless() {
        // Even if NetworkManager hands an SSID alongside a wired link, the
        // normalized snapshot never carries it.
        let network = network_from_nm(70, Some("802-3-ethernet"), Some("home-net"));
        assert_eq!(network.ssid(), None);
        assert_eq!(network.label(), "wired");
    }
}