forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

networks.rs1399 lines, 52.5 KiBHistoryRawDownload
1//! Networks page: sortable AP table, clients table, row-click target
2//! selection.
3
4use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px};
5use gpuikit::elements::badge::badge;
6use gpuikit::elements::button::button;
7use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table};
8use gpuikit::elements::text_field::text_field;
9use gpuikit::elements::typography::{h3, small, text};
10use gpuikit::layout::{h_stack, v_stack};
11use gpuikit::theme::{ActiveTheme, Themeable};
12
13use crate::common::{AccessPoint, ClientInfo, MacAddr, ProbeInfo, Security};
14use crate::ui::app::AppRoot;
15
16use std::collections::VecDeque;
17
18const COL_BSSID: usize = 0;
19const COL_SSID: usize = 1;
20/// Risk tags (`rogue?` / `weak`) that used to be stacked under the SSID.
21const COL_FLAGS: usize = 2;
22// Column-order documentation; vendor columns are not sortable, so nothing
23// references these by value (sort arms only name the sortable consts).
24#[allow(dead_code)]
25const COL_VENDOR: usize = 3;
26const COL_LABEL: usize = 4;
27const COL_CH: usize = 5;
28const COL_BAND: usize = 6;
29const COL_SEC: usize = 7;
30const COL_RSSI: usize = 8;
31const COL_BEACONS: usize = 9;
32const COL_AGE: usize = 10;
33
34const CCOL_MAC: usize = 0;
35#[allow(dead_code)]
36const CCOL_VENDOR: usize = 1;
37const CCOL_STATE: usize = 2;
38const CCOL_LABEL: usize = 3;
39const CCOL_AP: usize = 4;
40const CCOL_RSSI: usize = 5;
41const CCOL_FRAMES: usize = 6;
42const CCOL_AGE: usize = 7;
43// Device-group id (MAC-randomization pairing); not sortable.
44#[allow(dead_code)]
45const CCOL_ID: usize = 8;
46
47/// Human "last seen" age, e.g. `2s`, `5m`, `1h`. `last_seen_ms` comes from
48/// the UI/service-side process-local clock ([`crate::common::now_ms`]).
49pub fn age(last_seen_ms: u64) -> String {
50 let s = crate::common::now_ms().saturating_sub(last_seen_ms) / 1000;
51 if s < 60 {
52 format!("{s}s")
53 } else if s < 3600 {
54 format!("{}m", s / 60)
55 } else {
56 format!("{}h", s / 3600)
57 }
58}
59
60/// Band label for display: 2.4 GHz when the channel maps below 3 GHz,
61/// else 5 GHz. (6 GHz channel numbers collide with 2.4 GHz in this app —
62/// the scanner treats them as cosmetic, so 6 GHz APs may read "2.4".)
63pub(crate) fn band(ch: u8) -> &'static str {
64 match crate::common::freq_of_channel(ch) {
65 Some(f) if f < 3000 => "2.4",
66 Some(_) => "5",
67 None => "?",
68 }
69}
70
71pub(crate) fn sec_badge_label(label: &str, sec: Security) -> gpuikit::elements::badge::Badge {
72 match sec {
73 Security::Open => badge(label).outline(),
74 Security::Wep => badge(label).destructive(),
75 Security::Wpa | Security::Wpa2 => badge(label),
76 Security::Wpa3 => badge(label).secondary(),
77 }
78}
79
80/// Refined security label for the badge. The AKM suites of the RSN IE know
81/// more than the broad `Security` buckets: a transition AP (PSK+SAE) reads
82/// `WPA2/3`, an SAE-only AP reads `WPA3`, an OWE-only AP `OWE`.
83pub(crate) fn sec_label(ap: &AccessPoint) -> String {
84 let has = |k: crate::common::Akm| ap.akms.contains(&k);
85 if ap.security == Security::Wpa3 && has(crate::common::Akm::Sae) {
86 let pskish = has(crate::common::Akm::Psk)
87 || has(crate::common::Akm::PskSha256)
88 || has(crate::common::Akm::FtPsk);
89 if !pskish {
90 return "WPA3".to_string();
91 }
92 }
93 // OWE ("enhanced open") still carries an RSN IE, so it lands in the
94 // Wpa2 bucket — only the AKM list reveals it.
95 if has(crate::common::Akm::Owe) && ap.akms.len() == 1 {
96 return "OWE".to_string();
97 }
98 ap.security.label().to_string()
99}
100
101/// Station liveness badge: `up` while frames are flowing, `down` once the
102/// scanner observed a deauth/disassoc hitting this client.
103fn conn_badge(cl: &ClientInfo) -> gpuikit::elements::badge::Badge {
104 if cl.connected {
105 badge("up").secondary()
106 } else {
107 badge("down").destructive()
108 }
109}
110
111/// Client-table text cell. Disconnected rows are dimmed so the flagged
112/// stations visually recede from the live ones.
113fn client_cell(cl: &ClientInfo, body: String, cx: &mut gpui::App) -> gpui::AnyElement {
114 let mut cell = div().child(body);
115 if !cl.connected {
116 cell = cell.text_color(cx.theme().fg_muted());
117 }
118 cell.into_any_element()
119}
120
121/// Clients-section subtitle: `N stations`, `N stations (M down)` when the
122/// scanner flagged disconnects.
123fn client_counts(app: &AppRoot) -> String {
124 let total = app.state.clients.len();
125 let down = app.state.clients.values().filter(|c| !c.connected).count();
126 if down == 0 {
127 format!("{total} stations")
128 } else {
129 format!("{total} stations ({down} down)")
130 }
131}
132
133/// OUI vendor for a MAC; `random` for locally-administered MACs (modern
134/// phones/laptops rotate these — look at the ID column for the pairing),
135/// `—` for unknown prefixes.
136pub(crate) fn vendor_of(mac: &MacAddr) -> &'static str {
137 if crate::oui::is_locally_administered(mac) {
138 "random"
139 } else {
140 crate::oui::lookup(mac).unwrap_or("—")
141 }
142}
143
144/// Normalized (trim + lowercase) form matching `state.rogue_ssids` keys.
145fn norm_ssid(s: &str) -> String {
146 s.trim().to_lowercase()
147}
148
149/// Sparkline cell: up to 20 bars from the recent RSSI history of `mac`,
150/// right-aligned in recency order (last 20 values), padded to a stable
151/// 20-slot width with transparent placeholders. Height maps rssi -95..-30
152/// dBm onto 2..10 px.
153pub(crate) fn sparkline(hist: Option<&VecDeque<i8>>, accent: gpui::Hsla) -> gpui::AnyElement {
154 let mut bars: Vec<gpui::Div> = Vec::with_capacity(20);
155 if let Some(hist) = hist {
156 for &r in hist.iter().rev().take(20) {
157 let r = r as f32;
158 let h = ((r + 95.0) / 65.0 * 8.0 + 2.0).clamp(2.0, 10.0);
159 bars.push(div().w(px(3.)).h(px(h)).bg(accent));
160 }
161 bars.reverse();
162 }
163 while bars.len() < 20 {
164 bars.insert(0, div().w(px(3.)).h(px(1.)));
165 }
166 h_stack()
167 .items_end()
168 .gap(px(1.))
169 .h(px(10.))
170 .children(bars)
171 .into_any_element()
172}
173
174/// MAC of the row the label editor targets: a selected client wins over
175/// the selected AP.
176fn label_target(app: &AppRoot) -> Option<MacAddr> {
177 app.selected_client.or(app.selected)
178}
179
180/// Prefill the label input with the current label of `mac` (empty when
181/// none) — called whenever a row becomes the label target.
182fn prefill_label(app: &AppRoot, mac: MacAddr, cx: &mut Context<AppRoot>) {
183 let cur = app.state.labels.get(&mac).cloned().unwrap_or_default();
184 app.label_input
185 .update(cx, |input, cx| input.set_content(cur, cx));
186}
187
188/// Save button: write the input as the label of the current target (empty
189/// input = clear), then persist the whole map to `~/wifi_lab/labels.json`.
190fn save_label(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
191 view.update(cx, |app, cx| {
192 let Some(mac) = label_target(app) else {
193 app.state
194 .push_log("label: select an AP or client row first");
195 cx.notify();
196 return;
197 };
198 let raw = app.label_input.read(cx).content().trim().to_string();
199 if raw.is_empty() {
200 if app.state.labels.remove(&mac).is_some() {
201 app.state.push_log(format!("label cleared: {mac}"));
202 }
203 } else {
204 app.state.labels.insert(mac, raw.clone());
205 app.state.push_log(format!("label set: {mac} = \"{raw}\""));
206 }
207 if let Err(e) = crate::store::save(&app.state.labels) {
208 app.state.push_log(format!("label save FAILED: {e:#}"));
209 }
210 cx.notify();
211 });
212}
213
214/// One risk tag of an AP. `severity` orders the FLAGS column and the
215/// briefing list (higher = worse). [`risk_tags`] is the single source of
216/// truth: the column, its sorting and the Attacks briefing all read it, so
217/// a new tag is one line there.
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub(crate) struct RiskTag {
220 pub(crate) label: &'static str,
221 pub(crate) severity: u8,
222}
223
224/// Every risk tag of `ap`, worst first. Today: `rogue?` (same SSID on a
225/// different BSSID with different security) and `weak` (Open/WEP).
226pub(crate) fn risk_tags(
227 ap: &AccessPoint,
228 rogues: &std::collections::HashSet<String>,
229) -> Vec<RiskTag> {
230 let mut tags = Vec::new();
231 if !ap.ssid.is_empty() && rogues.contains(&norm_ssid(&ap.ssid)) {
232 tags.push(RiskTag {
233 label: "rogue?",
234 severity: 2,
235 });
236 }
237 if matches!(ap.security, Security::Open | Security::Wep) {
238 tags.push(RiskTag {
239 label: "weak",
240 severity: 1,
241 });
242 }
243 tags.sort_by_key(|t| std::cmp::Reverse(t.severity));
244 tags
245}
246
247/// Risk rank for sorting the FLAGS column: severity of the worst tag (0 =
248/// no tags). Higher = worse.
249pub(crate) fn risk_rank(ap: &AccessPoint, rogues: &std::collections::HashSet<String>) -> u8 {
250 risk_tags(ap, rogues).first().map_or(0, |t| t.severity)
251}
252
253/// Width budget of the FLAGS column — fixed, so badges can never push the
254/// neighbouring columns around.
255const FLAGS_W: f32 = 150.;
256/// Gap between badges (mirrors the cell's `gap_2`).
257const FLAGS_GAP: f32 = 8.;
258/// Width of the `+N` overflow marker (`text_xs` text).
259const FLAGS_MORE_W: f32 = 26.;
260
261/// Estimated width of one badge: Small control metrics are 16 px tall with
262/// 6 px horizontal padding, a 1 px border per side and 11 px semibold text
263/// (≈ 7 px per character at this scale). The estimate only decides how many
264/// badges to draw — the cell also clips, so an under-estimate can never
265/// bleed into the next column.
266fn badge_width(label: &str) -> f32 {
267 label.chars().count() as f32 * 7.0 + 14.0
268}
269
270/// How many of `tags` fit the FLAGS column: `(shown, hidden)`. Whatever does
271/// not fit collapses into one `+N` marker, so ten tags still occupy a single
272/// constant-width cell; the full list stays readable on the Attacks
273/// briefing card.
274fn fit_tags(tags: &[RiskTag], width: f32) -> (usize, usize) {
275 if tags.is_empty() {
276 return (0, 0);
277 }
278 // Width of the first `n` badges, gaps included.
279 let drawn = |n: usize| -> f32 {
280 if n == 0 {
281 0.0
282 } else {
283 tags[..n].iter().map(|t| badge_width(t.label)).sum::<f32>() + FLAGS_GAP * (n - 1) as f32
284 }
285 };
286 if drawn(tags.len()) <= width {
287 return (tags.len(), 0);
288 }
289 // Drop tags from the tail until the survivors plus the marker fit.
290 for shown in (0..tags.len()).rev() {
291 let marker = if shown > 0 { FLAGS_GAP } else { 0.0 } + FLAGS_MORE_W;
292 if drawn(shown) + marker <= width {
293 return (shown, tags.len() - shown);
294 }
295 }
296 (0, tags.len())
297}
298
299fn sorted_aps(app: &AppRoot) -> Vec<AccessPoint> {
300 let mut rows: Vec<AccessPoint> = app.state.aps.values().cloned().collect();
301 if let Some(sort) = app.ap_sort {
302 let labels = &app.state.labels;
303 let rogues = &app.state.rogue_ssids;
304 let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column {
305 COL_BSSID => l.bssid.cmp(&r.bssid),
306 COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)),
307 COL_FLAGS => risk_rank(l, rogues)
308 .cmp(&risk_rank(r, rogues))
309 .then_with(|| l.bssid.cmp(&r.bssid)),
310 COL_LABEL => labels
311 .get(&l.bssid)
312 .cmp(&labels.get(&r.bssid))
313 .then_with(|| l.bssid.cmp(&r.bssid)),
314 COL_CH => l.channel.cmp(&r.channel),
315 COL_BAND => band(l.channel).cmp(band(r.channel)),
316 COL_SEC => l.security.label().cmp(r.security.label()),
317 COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),
318 COL_BEACONS => l.beacons.cmp(&r.beacons),
319 COL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), // newest = 0s first
320 _ => std::cmp::Ordering::Equal,
321 };
322 rows.sort_by(|l, r| match sort.direction {
323 SortDirection::Ascending => ord(l, r),
324 SortDirection::Descending => ord(l, r).reverse(),
325 });
326 }
327 rows
328}
329
330fn sorted_clients(app: &AppRoot) -> Vec<ClientInfo> {
331 let mut rows: Vec<ClientInfo> = app.state.clients.values().cloned().collect();
332 if let Some(sort) = app.client_sort {
333 let labels = &app.state.labels;
334 let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column {
335 CCOL_MAC => l.mac.cmp(&r.mac),
336 CCOL_STATE => l.connected.cmp(&r.connected),
337 CCOL_LABEL => labels
338 .get(&l.mac)
339 .cmp(&labels.get(&r.mac))
340 .then_with(|| l.mac.cmp(&r.mac)),
341 CCOL_AP => {
342 // Sort by what the column shows: the AP's SSID (bssid falls
343 // back behind named entries, ties on raw MAC).
344 let key = |c: &ClientInfo| {
345 c.ap.and_then(|b| app.state.aps.get(&b))
346 .filter(|a| !a.ssid.is_empty())
347 .map(|a| a.ssid.to_lowercase())
348 .unwrap_or_else(|| "\u{10ffff}".into())
349 };
350 key(l).cmp(&key(r)).then_with(|| l.ap.cmp(&r.ap))
351 }
352 CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),
353 CCOL_FRAMES => l.frames.cmp(&r.frames),
354 CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(),
355 _ => std::cmp::Ordering::Equal,
356 };
357 rows.sort_by(|l, r| match sort.direction {
358 SortDirection::Ascending => ord(l, r),
359 SortDirection::Descending => ord(l, r).reverse(),
360 });
361 }
362 // Disconnected (deauth-flagged) stations sink below every connected
363 // row regardless of the active sort — the state column answers "what
364 // is still here", the partition is the answer at a glance. Stable
365 // sort keeps the user-chosen order within each group.
366 rows.sort_by_key(|c| !c.connected);
367 rows
368}
369
370fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> {
371 let selected = app.selected;
372 let rows = sorted_aps(app)
373 .into_iter()
374 .map(|ap| {
375 let bssid = ap.bssid;
376 let view = view.clone();
377 Row::new(ap)
378 .selected(selected == Some(bssid))
379 .on_click(move |_window, cx| {
380 view.update(cx, |app, cx| {
381 app.selected = Some(bssid);
382 // Keep the target's AP row for the Attacks card —
383 // the live record can vanish (host-capture mode
384 // never re-scans), the snapshot holds.
385 if let Some(row) = app.state.aps.get(&bssid) {
386 app.selected_ap = Some(row.clone());
387 }
388 app.selected_client = None;
389 prefill_label(app, bssid, cx);
390 app.state.push_log(format!("target selected: {bssid}"));
391 cx.notify();
392 });
393 })
394 })
395 .collect::<Vec<_>>();
396
397 let rogues = app.state.rogue_ssids.clone();
398 let rssi_hist = app.state.rssi_hist.clone();
399
400 table("networks-aps")
401 .column(
402 Column::new("BSSID", |ap: &AccessPoint, _w, _cx| {
403 div().child(ap.bssid.to_string()).into_any_element()
404 })
405 .sortable()
406 .min_width(px(150.)),
407 )
408 .column({
409 Column::new("SSID", |ap: &AccessPoint, _w, _cx| {
410 // SSID text only — risk tags live in the FLAGS column (they
411 // used to be stacked under the SSID, which made the column
412 // two lines tall and squeezed the text).
413 div()
414 .w_full()
415 .overflow_hidden()
416 .text_ellipsis()
417 .whitespace_nowrap()
418 .child(if ap.ssid.is_empty() {
419 "<hidden>".to_string()
420 } else {
421 ap.ssid.clone()
422 })
423 .into_any_element()
424 })
425 .sortable()
426 .flex(2.0)
427 .min_width(px(120.))
428 })
429 .column({
430 let rogues = rogues.clone();
431 Column::new("FLAGS", move |ap: &AccessPoint, _w, _cx| {
432 let tags = risk_tags(ap, &rogues);
433 // Constant-width cell: badges that do not fit collapse into
434 // `+N` (full list on the Attacks briefing), and the cell
435 // clips as a hard backstop — gpuikit cells do not clip by
436 // themselves, so no badge can paint over VENDOR.
437 let (shown, hidden) = fit_tags(&tags, FLAGS_W);
438 let mut row = h_stack().gap_2().items_center();
439 for tag in tags.iter().take(shown) {
440 row = row.child(badge(tag.label).destructive());
441 }
442 if hidden > 0 {
443 row = row.child(small(format!("+{hidden}")).muted());
444 }
445 div()
446 .w(px(FLAGS_W))
447 .flex_none()
448 .overflow_hidden()
449 .child(row)
450 .into_any_element()
451 })
452 .sortable()
453 .fixed(px(FLAGS_W))
454 })
455 .column(
456 Column::new("VENDOR", |ap: &AccessPoint, _w, _cx| {
457 div().child(vendor_of(&ap.bssid)).into_any_element()
458 })
459 .flex(1.0)
460 .min_width(px(90.)),
461 )
462 .column({
463 // Snapshot per render pass (the table is rebuilt with fresh
464 // state each time anyway).
465 let labels = app.state.labels.clone();
466 Column::new("LABEL", move |ap: &AccessPoint, _w, _cx| {
467 div()
468 .child(labels.get(&ap.bssid).cloned().unwrap_or_default())
469 .into_any_element()
470 })
471 .sortable()
472 .flex(1.0)
473 .min_width(px(100.))
474 })
475 .column(
476 Column::new("CH", |ap: &AccessPoint, _w, _cx| {
477 div().child(ap.channel.to_string()).into_any_element()
478 })
479 .sortable()
480 .fixed(px(60.))
481 .end(),
482 )
483 .column(
484 Column::new("BAND", |ap: &AccessPoint, _w, _cx| {
485 div()
486 .child(format!("{} GHz", band(ap.channel)))
487 .into_any_element()
488 })
489 .sortable()
490 .fixed(px(80.))
491 .end(),
492 )
493 .column(
494 Column::new("SEC", |ap: &AccessPoint, _w, _cx| {
495 // Fixed-width badge slot: the AKM text starts at the same x in
496 // every row regardless of badge-label width. 64 px fits the
497 // longest badge ("WPA2/3"); 52 clipped it mid-glyph over the
498 // AKM text. The cell itself is bounded so an over-long AKM join
499 // ellipsizes instead of painting into SIGNAL.
500 let badge_slot = div()
501 .w(px(64.))
502 .flex_none()
503 .child(sec_badge_label(&sec_label(ap), ap.security));
504 let joined = ap
505 .akms
506 .iter()
507 .map(|a| a.label())
508 .collect::<Vec<_>>()
509 .join("+");
510 let mut cell = h_stack()
511 .gap_1()
512 .items_center()
513 .w_full()
514 .overflow_hidden()
515 .child(badge_slot);
516 if !joined.is_empty() {
517 cell = cell
518 .child(
519 div()
520 .flex_1()
521 .min_w_0()
522 .overflow_hidden()
523 .text_ellipsis()
524 .whitespace_nowrap()
525 .child(small(joined)),
526 )
527 .justify_start();
528 }
529 cell.into_any_element()
530 })
531 .sortable()
532 .fixed(px(170.))
533 .align(CellAlign::Center),
534 )
535 .column({
536 let rssi_hist = rssi_hist.clone();
537 Column::new("SIGNAL", move |ap: &AccessPoint, _w, cx| {
538 sparkline(rssi_hist.get(&ap.bssid), cx.theme().accent())
539 })
540 .sortable()
541 .fixed(px(90.))
542 .align(CellAlign::Center)
543 })
544 .column(
545 Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| {
546 div().child(ap.beacons.to_string()).into_any_element()
547 })
548 .sortable()
549 .fixed(px(100.))
550 .end(),
551 )
552 .column(
553 Column::new("AGE", |ap: &AccessPoint, _w, _cx| {
554 div().child(age(ap.last_seen_ms)).into_any_element()
555 })
556 .sortable()
557 .fixed(px(70.))
558 .end(),
559 )
560 .rows(rows)
561 .sorted_by(app.ap_sort)
562 .on_sort({
563 let view = view.clone();
564 move |request, _window, cx| {
565 view.update(cx, |app, cx| {
566 app.ap_sort = Some(request.suggested());
567 cx.notify();
568 });
569 }
570 })
571 .max_h(px(340.))
572 .empty("No access points heard yet — is capture running?")
573}
574
575fn client_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<ClientInfo> {
576 let rows = sorted_clients(app)
577 .into_iter()
578 .map(|cl| {
579 // Clicking a client selects the (AP, client) pair: its AP
580 // becomes the target and the client is remembered for deauth.
581 let ap = cl.ap;
582 let mac = cl.mac;
583 let view = view.clone();
584 Row::new(cl)
585 .selected(app.selected_client == Some(mac))
586 .on_click(move |_window, cx| {
587 view.update(cx, |app, cx| {
588 match ap {
589 // Mapped client: its AP becomes the target.
590 Some(ap) => {
591 app.selected = Some(ap);
592 if let Some(row) = app.state.aps.get(&ap) {
593 app.selected_ap = Some(row.clone());
594 }
595 app.selected_client = Some(mac);
596 prefill_label(app, mac, cx);
597 app.state
598 .push_log(format!("target selected: {ap} (client {mac})"));
599 cx.notify();
600 }
601 // Unmapped client (scanner never resolved the
602 // association): keep the current target, target
603 // the client at it for deauth.
604 None if app.selected.is_some() => {
605 let target = app.selected.expect("checked above");
606 app.selected_client = Some(mac);
607 prefill_label(app, mac, cx);
608 app.state.push_log(format!(
609 "client selected: {mac} (AP unmapped — deauth targets {target})"
610 ));
611 cx.notify();
612 }
613 None => {
614 app.state.push_log(format!(
615 "client {mac}: AP unknown — pick a target AP row first"
616 ));
617 cx.notify();
618 }
619 }
620 });
621 })
622 })
623 .collect::<Vec<_>>();
624
625 table("networks-clients")
626 .column(
627 Column::new("MAC", |cl: &ClientInfo, _w, cx| {
628 client_cell(cl, cl.mac.to_string(), cx)
629 })
630 .sortable()
631 .min_width(px(150.)),
632 )
633 .column(
634 Column::new("VENDOR", |cl: &ClientInfo, _w, cx| {
635 client_cell(cl, vendor_of(&cl.mac).to_string(), cx)
636 })
637 .flex(1.0)
638 .min_width(px(90.)),
639 )
640 .column(
641 Column::new("STATE", |cl: &ClientInfo, _w, _cx| {
642 conn_badge(cl).into_any_element()
643 })
644 .sortable()
645 .fixed(px(90.))
646 .align(CellAlign::Center),
647 )
648 .column({
649 let labels = app.state.labels.clone();
650 Column::new("LABEL", move |cl: &ClientInfo, _w, cx| {
651 client_cell(cl, labels.get(&cl.mac).cloned().unwrap_or_default(), cx)
652 })
653 .sortable()
654 .flex(1.0)
655 .min_width(px(100.))
656 })
657 .column({
658 // BSSID → SSID resolution: "which network does this client
659 // belong to" reads as a name, not a MAC.
660 let ap_names: std::collections::BTreeMap<MacAddr, String> = app
661 .state
662 .aps
663 .iter()
664 .filter(|(_, a)| !a.ssid.is_empty())
665 .map(|(b, a)| (*b, a.ssid.clone()))
666 .collect();
667 Column::new("AP", move |cl: &ClientInfo, _w, cx| {
668 let Some(bssid) = cl.ap else {
669 return client_cell(cl, "—".into(), cx);
670 };
671 match ap_names.get(&bssid) {
672 None => client_cell(cl, bssid.to_string(), cx),
673 Some(name) => {
674 let mut cell = div().child(name.clone());
675 if !cl.connected {
676 cell = cell.text_color(cx.theme().fg_muted());
677 }
678 let sub = div()
679 .text_color(cx.theme().fg_muted())
680 .child(small(bssid.to_string()));
681 v_stack().child(cell).child(sub).into_any_element()
682 }
683 }
684 })
685 .sortable()
686 .min_width(px(150.))
687 })
688 .column(
689 Column::new("RSSI", |cl: &ClientInfo, _w, cx| {
690 client_cell(cl, format!("{} dBm", cl.rssi_dbm), cx)
691 })
692 .sortable()
693 .fixed(px(90.))
694 .end(),
695 )
696 .column(
697 Column::new("FRAMES", |cl: &ClientInfo, _w, cx| {
698 client_cell(cl, cl.frames.to_string(), cx)
699 })
700 .sortable()
701 .fixed(px(90.))
702 .end(),
703 )
704 .column(
705 Column::new("AGE", |cl: &ClientInfo, _w, cx| {
706 client_cell(cl, age(cl.last_seen_ms), cx)
707 })
708 .sortable()
709 .fixed(px(70.))
710 .end(),
711 )
712 .column({
713 // Device-group id + member count (`#1~ (2)`: group 1, "~" =
714 // strong witness, two known MACs — the MAC-randomization
715 // pairing). Confidence labels per `IdentConfidence::label`.
716 let counts: std::collections::BTreeMap<u64, usize> = app
717 .state
718 .ident_groups
719 .iter()
720 .map(|(g, ms)| (*g, ms.len()))
721 .collect();
722 Column::new("ID", move |cl: &ClientInfo, _w, cx| {
723 let Some(gid) = cl.ident_group else {
724 return client_cell(cl, String::new(), cx);
725 };
726 let conf = cl.ident_conf.map(|c| c.label()).unwrap_or("");
727 let n = counts.get(&gid).copied().unwrap_or(1);
728 let body = if n > 1 {
729 format!("#{gid}{conf} ({n})")
730 } else {
731 format!("#{gid}{conf}")
732 };
733 let mut cell = div().child(body);
734 if n > 1 {
735 cell = cell.text_color(cx.theme().accent());
736 }
737 cell.into_any_element()
738 })
739 .fixed(px(90.))
740 .align(CellAlign::Center)
741 })
742 .rows(rows)
743 .sorted_by(app.client_sort)
744 .on_sort({
745 let view = view.clone();
746 move |request, _window, cx| {
747 view.update(cx, |app, cx| {
748 app.client_sort = Some(request.suggested());
749 cx.notify();
750 });
751 }
752 })
753 .max_h(px(220.))
754 .empty("No client stations observed")
755}
756
757/// Recently observed probe requests, newest first, capped at 300 rows.
758fn probe_table(app: &AppRoot) -> Table<ProbeInfo> {
759 let rows: Vec<ProbeInfo> = app.state.probes.iter().rev().take(300).cloned().collect();
760 let rogues = app.state.rogue_ssids.clone();
761
762 table("networks-probes")
763 .column(
764 Column::new("CLIENT", |p: &ProbeInfo, _w, _cx| {
765 div()
766 .child(format!("{} ({})", p.client, vendor_of(&p.client)))
767 .into_any_element()
768 })
769 .min_width(px(190.)),
770 )
771 .column({
772 let rogues = rogues.clone();
773 Column::new("SSID", move |p: &ProbeInfo, _w, cx| match &p.ssid {
774 Some(s) => {
775 let mut cell = div().child(s.clone());
776 if !s.is_empty() && rogues.contains(&norm_ssid(s)) {
777 cell = cell.text_color(cx.theme().warning());
778 }
779 cell.into_any_element()
780 }
781 None => div().child("<any>").into_any_element(),
782 })
783 .flex(2.0)
784 .min_width(px(120.))
785 })
786 .column(
787 Column::new("RSSI", |p: &ProbeInfo, _w, _cx| {
788 div()
789 .child(format!("{} dBm", p.rssi_dbm))
790 .into_any_element()
791 })
792 .fixed(px(90.))
793 .end(),
794 )
795 .column(
796 Column::new("AGE", |p: &ProbeInfo, _w, _cx| {
797 div().child(age(p.at_ms)).into_any_element()
798 })
799 .fixed(px(70.))
800 .end(),
801 )
802 .rows(rows.into_iter().map(Row::new).collect::<Vec<_>>())
803 .max_h(px(220.))
804 .empty("No probe requests observed")
805}
806
807/// Fixed row count per activity column. Constant by design: the block must
808/// not resize when channels appear or disappear.
809const TL_ROWS: usize = 8;
810/// Per-snapshot columns drawn per row (older samples scroll off the left).
811const TL_COLUMNS: usize = 45;
812/// AP count on one channel that triggers the crowded warning.
813const TL_CROWD_WARN: usize = 4;
814/// Width one column block needs: channel label + [`TL_COLUMNS`] cells + the
815/// trailing frame counter, plus stack gaps. Blocks are laid out side by
816/// side, so extra channels cost WIDTH, never height.
817const TL_BLOCK_WIDTH: f32 = 360.;
818/// Hard cap on side-by-side blocks (4 × 8 = 32 channels on screen).
819const TL_MAX_BLOCKS: usize = 4;
820/// Horizontal space that is not the timeline (page nav, paddings) — ignored
821/// when deciding how many blocks fit.
822const TL_RESERVED_WIDTH: f32 = 220.;
823
824/// One timeline row. A blank slot (`channel: None`) exists purely to keep
825/// the block's height constant.
826#[derive(Clone, Debug, PartialEq)]
827struct TimelineRow {
828 channel: Option<u8>,
829 /// Frame deltas per snapshot, oldest→newest (may exceed [`TL_COLUMNS`];
830 /// the renderer shows the newest columns).
831 deltas: Vec<u64>,
832 /// Cumulative frames seen for the channel — shown before a second
833 /// snapshot makes a delta meaningful.
834 total: u64,
835 /// APs currently on the channel.
836 aps: usize,
837}
838
839/// The rendered timeline: `blocks` side-by-side column stacks of exactly
840/// [`TL_ROWS`] rows each, plus how many channels the newest snapshot
841/// reported and how many of them made it on screen.
842#[derive(Clone, Debug, Default, PartialEq)]
843struct TimelineView {
844 blocks: Vec<Vec<TimelineRow>>,
845 shown: usize,
846 active: usize,
847}
848
849/// Lay the timeline out for `available_width` px of horizontal space: the
850/// busiest channels of the newest snapshot — ordered by channel number and
851/// split into side-by-side column blocks of [`TL_ROWS`] rows — padded to
852/// whole blocks with blank rows. The row count per block (and therefore the
853/// block height) is constant whatever the channel set does; channels beyond
854/// the width's capacity are dropped by frame count, and the caller reports
855/// them via [`TimelineView::active`] vs [`TimelineView::shown`].
856fn timeline_view(
857 tl: &VecDeque<Vec<crate::common::ChannelStat>>,
858 crowd: &std::collections::HashMap<u8, usize>,
859 available_width: f32,
860) -> TimelineView {
861 let Some(latest) = tl.back() else {
862 return TimelineView::default();
863 };
864 let mut busy = latest.clone();
865 busy.sort_by_key(|s| std::cmp::Reverse(s.frames));
866 let active = busy.len();
867 let blocks = (((available_width.max(0.) / TL_BLOCK_WIDTH) as usize).clamp(1, TL_MAX_BLOCKS))
868 .min(active.div_ceil(TL_ROWS).max(1));
869 let capacity = blocks * TL_ROWS;
870 busy.truncate(capacity);
871 busy.sort_by_key(|s| s.channel);
872
873 let mut rows: Vec<TimelineRow> = busy
874 .into_iter()
875 .map(|b| {
876 // Frame series across the snapshots that reported this channel
877 // (missed snapshots are skipped, minor skew).
878 let series: Vec<u64> = tl
879 .iter()
880 .filter_map(|snap| {
881 snap.iter()
882 .find(|s| s.channel == b.channel)
883 .map(|s| s.frames)
884 })
885 .collect();
886 TimelineRow {
887 channel: Some(b.channel),
888 deltas: series
889 .windows(2)
890 .map(|w| w[1].saturating_sub(w[0]))
891 .collect(),
892 total: series.last().copied().unwrap_or(b.frames),
893 aps: *crowd.get(&b.channel).unwrap_or(&0),
894 }
895 })
896 .collect();
897 let shown = rows.len();
898 while rows.len() < capacity {
899 rows.push(TimelineRow {
900 channel: None,
901 deltas: Vec::new(),
902 total: 0,
903 aps: 0,
904 });
905 }
906 TimelineView {
907 blocks: rows.chunks(TL_ROWS).map(|c| c.to_vec()).collect(),
908 shown,
909 active,
910 }
911}
912
913/// Timeline of per-channel activity: one row per busiest channel, each row
914/// a right-aligned run of per-snapshot frame-delta columns (opacity =
915/// relative intensity). A channel hosting ≥4 APs gets a crowded warning —
916/// overlapping BSSs eat each other's airtime.
917///
918/// Rows are laid out in side-by-side column blocks sized to the available
919/// width, so a wide window shows more channels instead of wasting the space
920/// to the right. Every block always renders exactly [`TL_ROWS`] rows —
921/// unused slots are blank placeholders, same geometry — so channels entering
922/// or leaving the scan never resize the block: the tables below stay put.
923fn channel_timeline(
924 app: &AppRoot,
925 theme: &gpuikit::theme::Theme,
926 available_width: f32,
927) -> Option<gpui::AnyElement> {
928 let tl = &app.state.chan_timeline;
929 if tl.is_empty() {
930 return None;
931 }
932
933 // AP count per channel → crowded-channel warning.
934 let mut crowd: std::collections::HashMap<u8, usize> = std::collections::HashMap::new();
935 for ap in app.state.aps.values() {
936 if ap.channel > 0 {
937 *crowd.entry(ap.channel).or_default() += 1;
938 }
939 }
940
941 let accent = theme.accent();
942 // One row builder for data AND placeholder rows: identical geometry is
943 // what keeps the block height constant.
944 let build_row = |label_text: String, warn: bool, cols: Vec<gpui::Div>, trailer: String| {
945 let mut label = div().w(px(80.)).flex_none().text_xs();
946 label = if warn {
947 label.text_color(theme.warning())
948 } else {
949 label.text_color(theme.fg_muted())
950 };
951 h_stack()
952 .gap_2()
953 .items_center()
954 .child(label.child(label_text))
955 .child(h_stack().items_end().children(cols))
956 .child(
957 div()
958 .w(px(70.))
959 .flex_none()
960 .text_xs()
961 .text_color(theme.fg_muted())
962 .child(trailer),
963 )
964 .into_any_element()
965 };
966 let blank_cols = || (0..TL_COLUMNS).map(|_| div().w(px(4.)).h(px(12.)));
967
968 let view = timeline_view(tl, &crowd, available_width);
969 let render_row = |r: &TimelineRow| -> gpui::AnyElement {
970 let Some(ch) = r.channel else {
971 // Unused slot: invisible, but occupying its row. The NBSP
972 // keeps the label/trailer line boxes at full text height so
973 // blank rows match data rows exactly.
974 return build_row(
975 "\u{00a0}".to_string(),
976 false,
977 blank_cols().collect(),
978 "\u{00a0}".to_string(),
979 );
980 };
981 let max = r.deltas.iter().copied().max().unwrap_or(0).max(1) as f32;
982 let shown: &[u64] = &r.deltas[r.deltas.len().saturating_sub(TL_COLUMNS)..];
983 let mut cols: Vec<gpui::Div> = Vec::with_capacity(TL_COLUMNS);
984 // Left-pad quiet history so rows align at the newest edge.
985 cols.extend(blank_cols().take(TL_COLUMNS.saturating_sub(shown.len())));
986 for &d in shown {
987 let a = 0.15 + 0.85 * (d as f32 / max);
988 cols.push(div().w(px(4.)).h(px(12.)).bg(accent.opacity(a)));
989 }
990 let warn = r.aps >= TL_CROWD_WARN;
991 let label_text = if warn {
992 format!("ch{ch} ⚠{} APs", r.aps)
993 } else {
994 format!("ch{ch}")
995 };
996 // Before a second snapshot there is no delta to show — the row
997 // carries the cumulative count instead of a misleading `0 fr`.
998 let last = r.deltas.last().copied().unwrap_or(r.total);
999 build_row(label_text, warn, cols, format!("{last} fr"))
1000 };
1001 // Side by side: extra channels widen the block, they never make it
1002 // taller.
1003 let blocks: Vec<gpui::AnyElement> = view
1004 .blocks
1005 .iter()
1006 .map(|block| {
1007 v_stack()
1008 .gap_1()
1009 .flex_none()
1010 .children(block.iter().map(&render_row).collect::<Vec<_>>())
1011 .into_any_element()
1012 })
1013 .collect();
1014 let header = if tl.len() < 2 {
1015 "channel activity — first snapshot, waiting for deltas".to_string()
1016 } else {
1017 let mut h = format!(
1018 "channel activity — last {} snapshots (one column each), brightest = busiest",
1019 tl.len()
1020 );
1021 if view.active > view.shown {
1022 h.push_str(&format!(
1023 " · {} busiest of {} active channels shown",
1024 view.shown, view.active
1025 ));
1026 }
1027 h
1028 };
1029 Some(
1030 v_stack()
1031 .gap_1()
1032 .child(small(header))
1033 .child(h_stack().gap_6().items_start().children(blocks))
1034 .into_any_element(),
1035 )
1036}
1037
1038/// Channel activity visualization: the fixed-height per-channel timeline,
1039/// hidden only until the first snapshot arrives. `available_width` is the
1040/// window width the timeline may occupy.
1041fn channel_activity(
1042 app: &AppRoot,
1043 theme: &gpuikit::theme::Theme,
1044 available_width: f32,
1045) -> Option<gpui::AnyElement> {
1046 channel_timeline(app, theme, available_width)
1047}
1048
1049pub fn render(
1050 app: &mut AppRoot,
1051 view: &Entity<AppRoot>,
1052 window: &mut Window,
1053 cx: &mut Context<AppRoot>,
1054) -> gpui::Div {
1055 // Persistent label editor: applies to the selected row (a selected
1056 // client wins over the selected AP — see [`label_target`]).
1057 let label_bar = label_target(app).map(|mac| {
1058 h_stack()
1059 .items_center()
1060 .gap_2()
1061 .child(small("label for"))
1062 .child(text(mac.to_string()).code().small().into_any_element())
1063 .child(
1064 div()
1065 .w(px(240.))
1066 .child(text_field(&app.label_input, cx).placeholder("name this device…")),
1067 )
1068 .child(button("btn-label-save", "Save").on_click({
1069 let view = view.clone();
1070 move |_, window, cx| save_label(&view, window, cx)
1071 }))
1072 .child(small("(empty saves as no label)"))
1073 .into_any_element()
1074 });
1075
1076 v_stack()
1077 .size_full()
1078 .gap_3()
1079 .p_4()
1080 .child(
1081 gpuikit::layout::h_stack()
1082 .items_center()
1083 .gap_3()
1084 .child(h3("Access Points"))
1085 .child(small(format!(
1086 "{} networks — click a row to pick a target",
1087 app.state.aps.len()
1088 ))),
1089 )
1090 .children(label_bar)
1091 .children(channel_activity(
1092 app,
1093 cx.theme(),
1094 f32::from(window.viewport_size().width) - TL_RESERVED_WIDTH,
1095 ))
1096 .child(ap_table(app, view))
1097 .child(
1098 gpuikit::layout::h_stack()
1099 .items_center()
1100 .gap_3()
1101 .child(h3("Clients"))
1102 .child(small(client_counts(app))),
1103 )
1104 .child(client_table(app, view))
1105 .child(
1106 gpuikit::layout::h_stack()
1107 .items_center()
1108 .gap_3()
1109 .child(h3("Probes"))
1110 .child(small(format!("{} observed", app.state.probes.len()))),
1111 )
1112 .child(probe_table(app))
1113}
1114#[cfg(test)]
1115mod tests {
1116 use super::*;
1117 use crate::common::ChannelStat;
1118 use std::collections::HashMap;
1119
1120 fn snap(pairs: &[(u8, u64)]) -> Vec<ChannelStat> {
1121 pairs
1122 .iter()
1123 .map(|&(channel, frames)| ChannelStat {
1124 channel,
1125 frames,
1126 beacons: 0,
1127 })
1128 .collect()
1129 }
1130
1131 fn timeline(snaps: Vec<Vec<ChannelStat>>) -> VecDeque<Vec<ChannelStat>> {
1132 snaps.into()
1133 }
1134
1135 /// Window width that fits every block (tests use it to isolate the
1136 /// channel-count behaviour from the width behaviour).
1137 const WIDE: f32 = TL_BLOCK_WIDTH * TL_MAX_BLOCKS as f32;
1138
1139 fn rows_of(view: &TimelineView) -> Vec<TimelineRow> {
1140 view.blocks.iter().flatten().cloned().collect()
1141 }
1142
1143 /// The reported bug: the activity block resized (pushing everything
1144 /// below it) when channels were added to or removed from the scan.
1145 /// Height is now `TL_ROWS` rows per block whatever the channel set does
1146 /// — 4 channels and 20 channels produce the same block height.
1147 #[test]
1148 fn timeline_height_is_constant_across_channel_sets() {
1149 let cases: Vec<Vec<(u8, u64)>> = vec![
1150 vec![],
1151 vec![(1, 10)],
1152 vec![(1, 10), (6, 200), (11, 30), (36, 5)],
1153 (1..=12).map(|c| (c, c as u64 * 7)).collect(),
1154 (1..=20).map(|c| (c, c as u64 * 7)).collect(),
1155 (1..=40).map(|c| (c, c as u64 * 7)).collect(),
1156 ];
1157 for set in cases {
1158 let view = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), WIDE);
1159 for (i, block) in view.blocks.iter().enumerate() {
1160 assert_eq!(
1161 block.len(),
1162 TL_ROWS,
1163 "channel set {set:?} block {i} must hold exactly TL_ROWS rows"
1164 );
1165 }
1166 let rows = rows_of(&view);
1167 // Blank slots only ever trail the data rows.
1168 let first_blank = rows.iter().position(|r| r.channel.is_none());
1169 if let Some(i) = first_blank {
1170 assert!(
1171 rows[i..].iter().all(|r| r.channel.is_none()),
1172 "blank slots must be trailing: {rows:?}"
1173 );
1174 }
1175 }
1176 // An empty timeline yields no blocks at all (block hidden).
1177 assert!(
1178 timeline_view(&timeline(vec![]), &HashMap::new(), WIDE)
1179 .blocks
1180 .is_empty()
1181 );
1182 }
1183
1184 /// 20 channels: as many column blocks as the width allows, and every
1185 /// one of them exactly TL_ROWS rows tall.
1186 #[test]
1187 fn timeline_uses_horizontal_space_for_many_channels() {
1188 let set: Vec<(u8, u64)> = (1..=20).map(|c| (c, 1000 - c as u64)).collect();
1189 let view = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), WIDE);
1190 assert_eq!(view.active, 20);
1191 assert_eq!(view.shown, 20, "wide window must show all 20 channels");
1192 assert_eq!(view.blocks.len(), 20usize.div_ceil(TL_ROWS));
1193 assert!(view.blocks.iter().all(|b| b.len() == TL_ROWS));
1194
1195 // Narrow window: fewer blocks, extras dropped by frame count (the
1196 // busiest survive), height unchanged.
1197 let narrow = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), TL_BLOCK_WIDTH);
1198 assert_eq!(narrow.blocks.len(), 1);
1199 assert_eq!(narrow.shown, TL_ROWS);
1200 assert_eq!(narrow.active, 20);
1201 let kept: Vec<u8> = rows_of(&narrow).iter().filter_map(|r| r.channel).collect();
1202 assert_eq!(
1203 kept,
1204 vec![1, 2, 3, 4, 5, 6, 7, 8],
1205 "busiest kept, ascending"
1206 );
1207
1208 // No more blocks than the cap, however wide the window gets. The
1209 // block count is also bounded by how many channels exist — a 40
1210 // channel set is what can actually reach the cap.
1211 let many: Vec<(u8, u64)> = (1..=40).map(|c| (c, 1000 - c as u64)).collect();
1212 let huge = timeline_view(&timeline(vec![snap(&many)]), &HashMap::new(), 100_000.);
1213 assert_eq!(huge.blocks.len(), TL_MAX_BLOCKS);
1214 assert_eq!(huge.shown, TL_MAX_BLOCKS * TL_ROWS, "capacity is the cap");
1215 assert_eq!(huge.active, 40);
1216 assert!(
1217 huge.shown < huge.active,
1218 "the header must be able to report dropped channels"
1219 );
1220 }
1221
1222 /// Surviving channels keep their relative order whatever else joins or
1223 /// leaves the busiest set, so rows don't shuffle between scans.
1224 #[test]
1225 fn timeline_order_is_by_channel() {
1226 let sets = [
1227 vec![(1, 10), (6, 200), (36, 5)],
1228 vec![(3, 900), (1, 10), (36, 5), (11, 40)],
1229 vec![(11, 40), (36, 5)],
1230 ];
1231 for set in sets {
1232 let view = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), WIDE);
1233 let channels: Vec<u8> = rows_of(&view).iter().filter_map(|r| r.channel).collect();
1234 let mut sorted = channels.clone();
1235 sorted.sort_unstable();
1236 assert_eq!(channels, sorted, "rows must ascend by channel: {set:?}");
1237 }
1238 }
1239
1240 #[test]
1241 fn timeline_deltas_and_totals() {
1242 let mut crowd = HashMap::new();
1243 crowd.insert(6, 5);
1244 // ch6 reported in every snapshot, ch11 missing from the middle one.
1245 let tl = timeline(vec![
1246 snap(&[(6, 100), (11, 10)]),
1247 snap(&[(6, 160)]),
1248 snap(&[(6, 200), (11, 50)]),
1249 ]);
1250 let view = timeline_view(&tl, &crowd, WIDE);
1251 let rows = rows_of(&view);
1252 let ch6 = rows.iter().find(|r| r.channel == Some(6)).expect("ch6 row");
1253 assert_eq!(ch6.deltas, vec![60, 40], "consecutive deltas");
1254 assert_eq!(ch6.total, 200);
1255 assert_eq!(ch6.aps, 5);
1256 let ch11 = rows
1257 .iter()
1258 .find(|r| r.channel == Some(11))
1259 .expect("ch11 row");
1260 // Missed snapshot skipped: the delta spans the gap.
1261 assert_eq!(ch11.deltas, vec![40]);
1262 assert_eq!(ch11.total, 50);
1263
1264 // A single snapshot has no delta yet — the row shows the total.
1265 let view = timeline_view(&timeline(vec![snap(&[(1, 42)])]), &HashMap::new(), WIDE);
1266 let ch1 = rows_of(&view)
1267 .into_iter()
1268 .find(|r| r.channel == Some(1))
1269 .expect("ch1 row");
1270 assert!(ch1.deltas.is_empty());
1271 assert_eq!(ch1.total, 42);
1272 }
1273
1274 #[test]
1275 fn risk_rank_orders_rogue_over_weak_over_none() {
1276 let mut rogues = std::collections::HashSet::new();
1277 rogues.insert(norm_ssid("evil-twin"));
1278 let ap = |ssid: &str, sec: Security| AccessPoint {
1279 bssid: MacAddr([1, 2, 3, 4, 5, 6]),
1280 ssid: ssid.to_string(),
1281 channel: 6,
1282 security: sec,
1283 rssi_dbm: -50,
1284 beacons: 1,
1285 last_seen_ms: 0,
1286 akms: Vec::new(),
1287 };
1288 let rogue = ap("evil-twin", Security::Wpa2);
1289 let weak = ap("open-wifi", Security::Open);
1290 let wep = ap("old-ap", Security::Wep);
1291 let fine = ap("home", Security::Wpa2);
1292 assert_eq!(risk_rank(&rogue, &rogues), 2);
1293 assert_eq!(risk_rank(&weak, &rogues), 1);
1294 assert_eq!(risk_rank(&wep, &rogues), 1);
1295 assert_eq!(risk_rank(&fine, &rogues), 0);
1296 // A hidden SSID can never be flagged rogue (nothing to match).
1297 let hidden = ap("", Security::Wpa2);
1298 assert_eq!(risk_rank(&hidden, &rogues), 0);
1299 // Sorting by the FLAGS column puts the worst first ascending.
1300 let mut order = [fine.clone(), weak.clone(), rogue.clone()];
1301 order.sort_by_key(|a| risk_rank(a, &rogues));
1302 assert_eq!(order[0].ssid, "home");
1303 assert_eq!(order[1].ssid, "open-wifi");
1304 assert_eq!(order[2].ssid, "evil-twin");
1305 }
1306
1307 /// Ten tags on one AP must not grow the cell, push its neighbours, or
1308 /// silently vanish: whatever does not fit becomes `+N`, and the tag the
1309 /// user must not miss (the worst) is always the one drawn.
1310 #[test]
1311 fn flags_column_collapses_overflow_into_a_marker() {
1312 // A synthetic worst case: ten tags of the shape real ones have.
1313 let many: Vec<RiskTag> = (0..10)
1314 .map(|i| RiskTag {
1315 label: if i % 2 == 0 { "rogue?" } else { "weak" },
1316 severity: 2,
1317 })
1318 .collect();
1319
1320 let (shown, hidden) = fit_tags(&many, FLAGS_W);
1321 assert!(shown < many.len(), "ten tags cannot all fit one cell");
1322 assert_eq!(shown + hidden, many.len(), "every tag is accounted for");
1323 assert!(shown >= 1, "at least the worst tag stays visible");
1324 // What is drawn — badges plus the marker — stays inside the column.
1325 let drawn: f32 = many[..shown]
1326 .iter()
1327 .map(|t| badge_width(t.label))
1328 .sum::<f32>()
1329 + FLAGS_GAP * shown.saturating_sub(1) as f32
1330 + FLAGS_MORE_W;
1331 assert!(
1332 drawn <= FLAGS_W,
1333 "drawn width {drawn} must fit the {FLAGS_W} px column"
1334 );
1335 }
1336
1337 #[test]
1338 fn fit_tags_is_conservative_at_every_width() {
1339 let tags = |n: usize| -> Vec<RiskTag> {
1340 (0..n)
1341 .map(|_| RiskTag {
1342 label: "rogue?",
1343 severity: 2,
1344 })
1345 .collect()
1346 };
1347 for n in 0..=12 {
1348 let list = tags(n);
1349 for width in [0., 20., 40., 80., 120., FLAGS_W, 300., 1000.] {
1350 let (shown, hidden) = fit_tags(&list, width);
1351 assert_eq!(
1352 shown + hidden,
1353 n,
1354 "tags must be conserved (n={n}, w={width})"
1355 );
1356 let drawn: f32 = list[..shown]
1357 .iter()
1358 .map(|t| badge_width(t.label))
1359 .sum::<f32>()
1360 + FLAGS_GAP * shown.saturating_sub(1) as f32
1361 + if hidden > 0 { FLAGS_MORE_W } else { 0.0 };
1362 assert!(
1363 drawn <= width.max(FLAGS_MORE_W),
1364 "n={n} width={width}: drawn {drawn} overflows"
1365 );
1366 if n > 0 && width >= badge_width("rogue?") + FLAGS_MORE_W {
1367 assert!(shown >= 1, "n={n} width={width}: nothing shown");
1368 }
1369 }
1370 }
1371 assert_eq!(fit_tags(&[], FLAGS_W), (0, 0));
1372 }
1373
1374 /// One order for tags everywhere: worst first, and the column sort uses
1375 /// the worst tag's severity.
1376 #[test]
1377 fn risk_tags_are_ordered_worst_first() {
1378 let mut rogues = std::collections::HashSet::new();
1379 rogues.insert(norm_ssid("evil-twin"));
1380 let ap = |ssid: &str, sec: Security| AccessPoint {
1381 bssid: MacAddr([9, 9, 9, 9, 9, 9]),
1382 ssid: ssid.to_string(),
1383 channel: 6,
1384 security: sec,
1385 rssi_dbm: -50,
1386 beacons: 1,
1387 last_seen_ms: 0,
1388 akms: Vec::new(),
1389 };
1390 let labels = |ap: &AccessPoint| -> Vec<&'static str> {
1391 risk_tags(ap, &rogues).iter().map(|t| t.label).collect()
1392 };
1393 assert_eq!(labels(&ap("evil-twin", Security::Open)), ["rogue?", "weak"]);
1394 assert_eq!(labels(&ap("open-wifi", Security::Open)), ["weak"]);
1395 assert_eq!(labels(&ap("home", Security::Wpa2)), [] as [&str; 0]);
1396 assert_eq!(risk_rank(&ap("evil-twin", Security::Wep), &rogues), 2);
1397 assert_eq!(risk_rank(&ap("home", Security::Wpa2), &rogues), 0);
1398 }
1399}