//! Networks page: sortable AP table, clients table, row-click target //! selection. use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px}; use gpuikit::elements::badge::badge; use gpuikit::elements::button::button; use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table}; use gpuikit::elements::text_field::text_field; use gpuikit::elements::typography::{h3, small, text}; use gpuikit::layout::{h_stack, v_stack}; use gpuikit::theme::{ActiveTheme, Themeable}; use crate::common::{AccessPoint, ClientInfo, MacAddr, ProbeInfo, Security}; use crate::ui::app::AppRoot; use std::collections::VecDeque; const COL_BSSID: usize = 0; const COL_SSID: usize = 1; /// Risk tags (`rogue?` / `weak`) that used to be stacked under the SSID. const COL_FLAGS: usize = 2; // Column-order documentation; vendor columns are not sortable, so nothing // references these by value (sort arms only name the sortable consts). #[allow(dead_code)] const COL_VENDOR: usize = 3; const COL_LABEL: usize = 4; const COL_CH: usize = 5; const COL_BAND: usize = 6; const COL_SEC: usize = 7; const COL_RSSI: usize = 8; const COL_BEACONS: usize = 9; const COL_AGE: usize = 10; const CCOL_MAC: usize = 0; #[allow(dead_code)] const CCOL_VENDOR: usize = 1; const CCOL_STATE: usize = 2; const CCOL_LABEL: usize = 3; const CCOL_AP: usize = 4; const CCOL_RSSI: usize = 5; const CCOL_FRAMES: usize = 6; const CCOL_AGE: usize = 7; // Device-group id (MAC-randomization pairing); not sortable. #[allow(dead_code)] const CCOL_ID: usize = 8; /// Human "last seen" age, e.g. `2s`, `5m`, `1h`. `last_seen_ms` comes from /// the UI/service-side process-local clock ([`crate::common::now_ms`]). pub fn age(last_seen_ms: u64) -> String { let s = crate::common::now_ms().saturating_sub(last_seen_ms) / 1000; if s < 60 { format!("{s}s") } else if s < 3600 { format!("{}m", s / 60) } else { format!("{}h", s / 3600) } } /// Band label for display: 2.4 GHz when the channel maps below 3 GHz, /// else 5 GHz. (6 GHz channel numbers collide with 2.4 GHz in this app — /// the scanner treats them as cosmetic, so 6 GHz APs may read "2.4".) pub(crate) fn band(ch: u8) -> &'static str { match crate::common::freq_of_channel(ch) { Some(f) if f < 3000 => "2.4", Some(_) => "5", None => "?", } } pub(crate) fn sec_badge_label(label: &str, sec: Security) -> gpuikit::elements::badge::Badge { match sec { Security::Open => badge(label).outline(), Security::Wep => badge(label).destructive(), Security::Wpa | Security::Wpa2 => badge(label), Security::Wpa3 => badge(label).secondary(), } } /// Refined security label for the badge. The AKM suites of the RSN IE know /// more than the broad `Security` buckets: a transition AP (PSK+SAE) reads /// `WPA2/3`, an SAE-only AP reads `WPA3`, an OWE-only AP `OWE`. pub(crate) fn sec_label(ap: &AccessPoint) -> String { let has = |k: crate::common::Akm| ap.akms.contains(&k); if ap.security == Security::Wpa3 && has(crate::common::Akm::Sae) { let pskish = has(crate::common::Akm::Psk) || has(crate::common::Akm::PskSha256) || has(crate::common::Akm::FtPsk); if !pskish { return "WPA3".to_string(); } } // OWE ("enhanced open") still carries an RSN IE, so it lands in the // Wpa2 bucket — only the AKM list reveals it. if has(crate::common::Akm::Owe) && ap.akms.len() == 1 { return "OWE".to_string(); } ap.security.label().to_string() } /// Station liveness badge: `up` while frames are flowing, `down` once the /// scanner observed a deauth/disassoc hitting this client. fn conn_badge(cl: &ClientInfo) -> gpuikit::elements::badge::Badge { if cl.connected { badge("up").secondary() } else { badge("down").destructive() } } /// Client-table text cell. Disconnected rows are dimmed so the flagged /// stations visually recede from the live ones. fn client_cell(cl: &ClientInfo, body: String, cx: &mut gpui::App) -> gpui::AnyElement { let mut cell = div().child(body); if !cl.connected { cell = cell.text_color(cx.theme().fg_muted()); } cell.into_any_element() } /// Clients-section subtitle: `N stations`, `N stations (M down)` when the /// scanner flagged disconnects. fn client_counts(app: &AppRoot) -> String { let total = app.state.clients.len(); let down = app.state.clients.values().filter(|c| !c.connected).count(); if down == 0 { format!("{total} stations") } else { format!("{total} stations ({down} down)") } } /// OUI vendor for a MAC; `random` for locally-administered MACs (modern /// phones/laptops rotate these — look at the ID column for the pairing), /// `—` for unknown prefixes. pub(crate) fn vendor_of(mac: &MacAddr) -> &'static str { if crate::oui::is_locally_administered(mac) { "random" } else { crate::oui::lookup(mac).unwrap_or("—") } } /// Normalized (trim + lowercase) form matching `state.rogue_ssids` keys. fn norm_ssid(s: &str) -> String { s.trim().to_lowercase() } /// Sparkline cell: up to 20 bars from the recent RSSI history of `mac`, /// right-aligned in recency order (last 20 values), padded to a stable /// 20-slot width with transparent placeholders. Height maps rssi -95..-30 /// dBm onto 2..10 px. pub(crate) fn sparkline(hist: Option<&VecDeque>, accent: gpui::Hsla) -> gpui::AnyElement { let mut bars: Vec = Vec::with_capacity(20); if let Some(hist) = hist { for &r in hist.iter().rev().take(20) { let r = r as f32; let h = ((r + 95.0) / 65.0 * 8.0 + 2.0).clamp(2.0, 10.0); bars.push(div().w(px(3.)).h(px(h)).bg(accent)); } bars.reverse(); } while bars.len() < 20 { bars.insert(0, div().w(px(3.)).h(px(1.))); } h_stack() .items_end() .gap(px(1.)) .h(px(10.)) .children(bars) .into_any_element() } /// MAC of the row the label editor targets: a selected client wins over /// the selected AP. fn label_target(app: &AppRoot) -> Option { app.selected_client.or(app.selected) } /// Prefill the label input with the current label of `mac` (empty when /// none) — called whenever a row becomes the label target. fn prefill_label(app: &AppRoot, mac: MacAddr, cx: &mut Context) { let cur = app.state.labels.get(&mac).cloned().unwrap_or_default(); app.label_input .update(cx, |input, cx| input.set_content(cur, cx)); } /// Save button: write the input as the label of the current target (empty /// input = clear), then persist the whole map to `~/wifi_lab/labels.json`. fn save_label(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { view.update(cx, |app, cx| { let Some(mac) = label_target(app) else { app.state .push_log("label: select an AP or client row first"); cx.notify(); return; }; let raw = app.label_input.read(cx).content().trim().to_string(); if raw.is_empty() { if app.state.labels.remove(&mac).is_some() { app.state.push_log(format!("label cleared: {mac}")); } } else { app.state.labels.insert(mac, raw.clone()); app.state.push_log(format!("label set: {mac} = \"{raw}\"")); } if let Err(e) = crate::store::save(&app.state.labels) { app.state.push_log(format!("label save FAILED: {e:#}")); } cx.notify(); }); } /// One risk tag of an AP. `severity` orders the FLAGS column and the /// briefing list (higher = worse). [`risk_tags`] is the single source of /// truth: the column, its sorting and the Attacks briefing all read it, so /// a new tag is one line there. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct RiskTag { pub(crate) label: &'static str, pub(crate) severity: u8, } /// Every risk tag of `ap`, worst first. Today: `rogue?` (same SSID on a /// different BSSID with different security) and `weak` (Open/WEP). pub(crate) fn risk_tags( ap: &AccessPoint, rogues: &std::collections::HashSet, ) -> Vec { let mut tags = Vec::new(); if !ap.ssid.is_empty() && rogues.contains(&norm_ssid(&ap.ssid)) { tags.push(RiskTag { label: "rogue?", severity: 2, }); } if matches!(ap.security, Security::Open | Security::Wep) { tags.push(RiskTag { label: "weak", severity: 1, }); } tags.sort_by_key(|t| std::cmp::Reverse(t.severity)); tags } /// Risk rank for sorting the FLAGS column: severity of the worst tag (0 = /// no tags). Higher = worse. pub(crate) fn risk_rank(ap: &AccessPoint, rogues: &std::collections::HashSet) -> u8 { risk_tags(ap, rogues).first().map_or(0, |t| t.severity) } /// Width budget of the FLAGS column — fixed, so badges can never push the /// neighbouring columns around. const FLAGS_W: f32 = 150.; /// Gap between badges (mirrors the cell's `gap_2`). const FLAGS_GAP: f32 = 8.; /// Width of the `+N` overflow marker (`text_xs` text). const FLAGS_MORE_W: f32 = 26.; /// Estimated width of one badge: Small control metrics are 16 px tall with /// 6 px horizontal padding, a 1 px border per side and 11 px semibold text /// (≈ 7 px per character at this scale). The estimate only decides how many /// badges to draw — the cell also clips, so an under-estimate can never /// bleed into the next column. fn badge_width(label: &str) -> f32 { label.chars().count() as f32 * 7.0 + 14.0 } /// How many of `tags` fit the FLAGS column: `(shown, hidden)`. Whatever does /// not fit collapses into one `+N` marker, so ten tags still occupy a single /// constant-width cell; the full list stays readable on the Attacks /// briefing card. fn fit_tags(tags: &[RiskTag], width: f32) -> (usize, usize) { if tags.is_empty() { return (0, 0); } // Width of the first `n` badges, gaps included. let drawn = |n: usize| -> f32 { if n == 0 { 0.0 } else { tags[..n].iter().map(|t| badge_width(t.label)).sum::() + FLAGS_GAP * (n - 1) as f32 } }; if drawn(tags.len()) <= width { return (tags.len(), 0); } // Drop tags from the tail until the survivors plus the marker fit. for shown in (0..tags.len()).rev() { let marker = if shown > 0 { FLAGS_GAP } else { 0.0 } + FLAGS_MORE_W; if drawn(shown) + marker <= width { return (shown, tags.len() - shown); } } (0, tags.len()) } fn sorted_aps(app: &AppRoot) -> Vec { let mut rows: Vec = app.state.aps.values().cloned().collect(); if let Some(sort) = app.ap_sort { let labels = &app.state.labels; let rogues = &app.state.rogue_ssids; let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column { COL_BSSID => l.bssid.cmp(&r.bssid), COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)), COL_FLAGS => risk_rank(l, rogues) .cmp(&risk_rank(r, rogues)) .then_with(|| l.bssid.cmp(&r.bssid)), COL_LABEL => labels .get(&l.bssid) .cmp(&labels.get(&r.bssid)) .then_with(|| l.bssid.cmp(&r.bssid)), COL_CH => l.channel.cmp(&r.channel), COL_BAND => band(l.channel).cmp(band(r.channel)), COL_SEC => l.security.label().cmp(r.security.label()), COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), COL_BEACONS => l.beacons.cmp(&r.beacons), COL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), // newest = 0s first _ => std::cmp::Ordering::Equal, }; rows.sort_by(|l, r| match sort.direction { SortDirection::Ascending => ord(l, r), SortDirection::Descending => ord(l, r).reverse(), }); } rows } fn sorted_clients(app: &AppRoot) -> Vec { let mut rows: Vec = app.state.clients.values().cloned().collect(); if let Some(sort) = app.client_sort { let labels = &app.state.labels; let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column { CCOL_MAC => l.mac.cmp(&r.mac), CCOL_STATE => l.connected.cmp(&r.connected), CCOL_LABEL => labels .get(&l.mac) .cmp(&labels.get(&r.mac)) .then_with(|| l.mac.cmp(&r.mac)), CCOL_AP => { // Sort by what the column shows: the AP's SSID (bssid falls // back behind named entries, ties on raw MAC). let key = |c: &ClientInfo| { c.ap.and_then(|b| app.state.aps.get(&b)) .filter(|a| !a.ssid.is_empty()) .map(|a| a.ssid.to_lowercase()) .unwrap_or_else(|| "\u{10ffff}".into()) }; key(l).cmp(&key(r)).then_with(|| l.ap.cmp(&r.ap)) } CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), CCOL_FRAMES => l.frames.cmp(&r.frames), CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), _ => std::cmp::Ordering::Equal, }; rows.sort_by(|l, r| match sort.direction { SortDirection::Ascending => ord(l, r), SortDirection::Descending => ord(l, r).reverse(), }); } // Disconnected (deauth-flagged) stations sink below every connected // row regardless of the active sort — the state column answers "what // is still here", the partition is the answer at a glance. Stable // sort keeps the user-chosen order within each group. rows.sort_by_key(|c| !c.connected); rows } fn ap_table(app: &AppRoot, view: &Entity) -> Table { let selected = app.selected; let rows = sorted_aps(app) .into_iter() .map(|ap| { let bssid = ap.bssid; let view = view.clone(); Row::new(ap) .selected(selected == Some(bssid)) .on_click(move |_window, cx| { view.update(cx, |app, cx| { app.selected = Some(bssid); // Keep the target's AP row for the Attacks card — // the live record can vanish (host-capture mode // never re-scans), the snapshot holds. if let Some(row) = app.state.aps.get(&bssid) { app.selected_ap = Some(row.clone()); } app.selected_client = None; prefill_label(app, bssid, cx); app.state.push_log(format!("target selected: {bssid}")); cx.notify(); }); }) }) .collect::>(); let rogues = app.state.rogue_ssids.clone(); let rssi_hist = app.state.rssi_hist.clone(); table("networks-aps") .column( Column::new("BSSID", |ap: &AccessPoint, _w, _cx| { div().child(ap.bssid.to_string()).into_any_element() }) .sortable() .min_width(px(150.)), ) .column({ Column::new("SSID", |ap: &AccessPoint, _w, _cx| { // SSID text only — risk tags live in the FLAGS column (they // used to be stacked under the SSID, which made the column // two lines tall and squeezed the text). div() .w_full() .overflow_hidden() .text_ellipsis() .whitespace_nowrap() .child(if ap.ssid.is_empty() { "".to_string() } else { ap.ssid.clone() }) .into_any_element() }) .sortable() .flex(2.0) .min_width(px(120.)) }) .column({ let rogues = rogues.clone(); Column::new("FLAGS", move |ap: &AccessPoint, _w, _cx| { let tags = risk_tags(ap, &rogues); // Constant-width cell: badges that do not fit collapse into // `+N` (full list on the Attacks briefing), and the cell // clips as a hard backstop — gpuikit cells do not clip by // themselves, so no badge can paint over VENDOR. let (shown, hidden) = fit_tags(&tags, FLAGS_W); let mut row = h_stack().gap_2().items_center(); for tag in tags.iter().take(shown) { row = row.child(badge(tag.label).destructive()); } if hidden > 0 { row = row.child(small(format!("+{hidden}")).muted()); } div() .w(px(FLAGS_W)) .flex_none() .overflow_hidden() .child(row) .into_any_element() }) .sortable() .fixed(px(FLAGS_W)) }) .column( Column::new("VENDOR", |ap: &AccessPoint, _w, _cx| { div().child(vendor_of(&ap.bssid)).into_any_element() }) .flex(1.0) .min_width(px(90.)), ) .column({ // Snapshot per render pass (the table is rebuilt with fresh // state each time anyway). let labels = app.state.labels.clone(); Column::new("LABEL", move |ap: &AccessPoint, _w, _cx| { div() .child(labels.get(&ap.bssid).cloned().unwrap_or_default()) .into_any_element() }) .sortable() .flex(1.0) .min_width(px(100.)) }) .column( Column::new("CH", |ap: &AccessPoint, _w, _cx| { div().child(ap.channel.to_string()).into_any_element() }) .sortable() .fixed(px(60.)) .end(), ) .column( Column::new("BAND", |ap: &AccessPoint, _w, _cx| { div() .child(format!("{} GHz", band(ap.channel))) .into_any_element() }) .sortable() .fixed(px(80.)) .end(), ) .column( Column::new("SEC", |ap: &AccessPoint, _w, _cx| { // Fixed-width badge slot: the AKM text starts at the same x in // every row regardless of badge-label width. 64 px fits the // longest badge ("WPA2/3"); 52 clipped it mid-glyph over the // AKM text. The cell itself is bounded so an over-long AKM join // ellipsizes instead of painting into SIGNAL. let badge_slot = div() .w(px(64.)) .flex_none() .child(sec_badge_label(&sec_label(ap), ap.security)); let joined = ap .akms .iter() .map(|a| a.label()) .collect::>() .join("+"); let mut cell = h_stack() .gap_1() .items_center() .w_full() .overflow_hidden() .child(badge_slot); if !joined.is_empty() { cell = cell .child( div() .flex_1() .min_w_0() .overflow_hidden() .text_ellipsis() .whitespace_nowrap() .child(small(joined)), ) .justify_start(); } cell.into_any_element() }) .sortable() .fixed(px(170.)) .align(CellAlign::Center), ) .column({ let rssi_hist = rssi_hist.clone(); Column::new("SIGNAL", move |ap: &AccessPoint, _w, cx| { sparkline(rssi_hist.get(&ap.bssid), cx.theme().accent()) }) .sortable() .fixed(px(90.)) .align(CellAlign::Center) }) .column( Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| { div().child(ap.beacons.to_string()).into_any_element() }) .sortable() .fixed(px(100.)) .end(), ) .column( Column::new("AGE", |ap: &AccessPoint, _w, _cx| { div().child(age(ap.last_seen_ms)).into_any_element() }) .sortable() .fixed(px(70.)) .end(), ) .rows(rows) .sorted_by(app.ap_sort) .on_sort({ let view = view.clone(); move |request, _window, cx| { view.update(cx, |app, cx| { app.ap_sort = Some(request.suggested()); cx.notify(); }); } }) .max_h(px(340.)) .empty("No access points heard yet — is capture running?") } fn client_table(app: &AppRoot, view: &Entity) -> Table { let rows = sorted_clients(app) .into_iter() .map(|cl| { // Clicking a client selects the (AP, client) pair: its AP // becomes the target and the client is remembered for deauth. let ap = cl.ap; let mac = cl.mac; let view = view.clone(); Row::new(cl) .selected(app.selected_client == Some(mac)) .on_click(move |_window, cx| { view.update(cx, |app, cx| { match ap { // Mapped client: its AP becomes the target. Some(ap) => { app.selected = Some(ap); if let Some(row) = app.state.aps.get(&ap) { app.selected_ap = Some(row.clone()); } app.selected_client = Some(mac); prefill_label(app, mac, cx); app.state .push_log(format!("target selected: {ap} (client {mac})")); cx.notify(); } // Unmapped client (scanner never resolved the // association): keep the current target, target // the client at it for deauth. None if app.selected.is_some() => { let target = app.selected.expect("checked above"); app.selected_client = Some(mac); prefill_label(app, mac, cx); app.state.push_log(format!( "client selected: {mac} (AP unmapped — deauth targets {target})" )); cx.notify(); } None => { app.state.push_log(format!( "client {mac}: AP unknown — pick a target AP row first" )); cx.notify(); } } }); }) }) .collect::>(); table("networks-clients") .column( Column::new("MAC", |cl: &ClientInfo, _w, cx| { client_cell(cl, cl.mac.to_string(), cx) }) .sortable() .min_width(px(150.)), ) .column( Column::new("VENDOR", |cl: &ClientInfo, _w, cx| { client_cell(cl, vendor_of(&cl.mac).to_string(), cx) }) .flex(1.0) .min_width(px(90.)), ) .column( Column::new("STATE", |cl: &ClientInfo, _w, _cx| { conn_badge(cl).into_any_element() }) .sortable() .fixed(px(90.)) .align(CellAlign::Center), ) .column({ let labels = app.state.labels.clone(); Column::new("LABEL", move |cl: &ClientInfo, _w, cx| { client_cell(cl, labels.get(&cl.mac).cloned().unwrap_or_default(), cx) }) .sortable() .flex(1.0) .min_width(px(100.)) }) .column({ // BSSID → SSID resolution: "which network does this client // belong to" reads as a name, not a MAC. let ap_names: std::collections::BTreeMap = app .state .aps .iter() .filter(|(_, a)| !a.ssid.is_empty()) .map(|(b, a)| (*b, a.ssid.clone())) .collect(); Column::new("AP", move |cl: &ClientInfo, _w, cx| { let Some(bssid) = cl.ap else { return client_cell(cl, "—".into(), cx); }; match ap_names.get(&bssid) { None => client_cell(cl, bssid.to_string(), cx), Some(name) => { let mut cell = div().child(name.clone()); if !cl.connected { cell = cell.text_color(cx.theme().fg_muted()); } let sub = div() .text_color(cx.theme().fg_muted()) .child(small(bssid.to_string())); v_stack().child(cell).child(sub).into_any_element() } } }) .sortable() .min_width(px(150.)) }) .column( Column::new("RSSI", |cl: &ClientInfo, _w, cx| { client_cell(cl, format!("{} dBm", cl.rssi_dbm), cx) }) .sortable() .fixed(px(90.)) .end(), ) .column( Column::new("FRAMES", |cl: &ClientInfo, _w, cx| { client_cell(cl, cl.frames.to_string(), cx) }) .sortable() .fixed(px(90.)) .end(), ) .column( Column::new("AGE", |cl: &ClientInfo, _w, cx| { client_cell(cl, age(cl.last_seen_ms), cx) }) .sortable() .fixed(px(70.)) .end(), ) .column({ // Device-group id + member count (`#1~ (2)`: group 1, "~" = // strong witness, two known MACs — the MAC-randomization // pairing). Confidence labels per `IdentConfidence::label`. let counts: std::collections::BTreeMap = app .state .ident_groups .iter() .map(|(g, ms)| (*g, ms.len())) .collect(); Column::new("ID", move |cl: &ClientInfo, _w, cx| { let Some(gid) = cl.ident_group else { return client_cell(cl, String::new(), cx); }; let conf = cl.ident_conf.map(|c| c.label()).unwrap_or(""); let n = counts.get(&gid).copied().unwrap_or(1); let body = if n > 1 { format!("#{gid}{conf} ({n})") } else { format!("#{gid}{conf}") }; let mut cell = div().child(body); if n > 1 { cell = cell.text_color(cx.theme().accent()); } cell.into_any_element() }) .fixed(px(90.)) .align(CellAlign::Center) }) .rows(rows) .sorted_by(app.client_sort) .on_sort({ let view = view.clone(); move |request, _window, cx| { view.update(cx, |app, cx| { app.client_sort = Some(request.suggested()); cx.notify(); }); } }) .max_h(px(220.)) .empty("No client stations observed") } /// Recently observed probe requests, newest first, capped at 300 rows. fn probe_table(app: &AppRoot) -> Table { let rows: Vec = app.state.probes.iter().rev().take(300).cloned().collect(); let rogues = app.state.rogue_ssids.clone(); table("networks-probes") .column( Column::new("CLIENT", |p: &ProbeInfo, _w, _cx| { div() .child(format!("{} ({})", p.client, vendor_of(&p.client))) .into_any_element() }) .min_width(px(190.)), ) .column({ let rogues = rogues.clone(); Column::new("SSID", move |p: &ProbeInfo, _w, cx| match &p.ssid { Some(s) => { let mut cell = div().child(s.clone()); if !s.is_empty() && rogues.contains(&norm_ssid(s)) { cell = cell.text_color(cx.theme().warning()); } cell.into_any_element() } None => div().child("").into_any_element(), }) .flex(2.0) .min_width(px(120.)) }) .column( Column::new("RSSI", |p: &ProbeInfo, _w, _cx| { div() .child(format!("{} dBm", p.rssi_dbm)) .into_any_element() }) .fixed(px(90.)) .end(), ) .column( Column::new("AGE", |p: &ProbeInfo, _w, _cx| { div().child(age(p.at_ms)).into_any_element() }) .fixed(px(70.)) .end(), ) .rows(rows.into_iter().map(Row::new).collect::>()) .max_h(px(220.)) .empty("No probe requests observed") } /// Fixed row count per activity column. Constant by design: the block must /// not resize when channels appear or disappear. const TL_ROWS: usize = 8; /// Per-snapshot columns drawn per row (older samples scroll off the left). const TL_COLUMNS: usize = 45; /// AP count on one channel that triggers the crowded warning. const TL_CROWD_WARN: usize = 4; /// Width one column block needs: channel label + [`TL_COLUMNS`] cells + the /// trailing frame counter, plus stack gaps. Blocks are laid out side by /// side, so extra channels cost WIDTH, never height. const TL_BLOCK_WIDTH: f32 = 360.; /// Hard cap on side-by-side blocks (4 × 8 = 32 channels on screen). const TL_MAX_BLOCKS: usize = 4; /// Horizontal space that is not the timeline (page nav, paddings) — ignored /// when deciding how many blocks fit. const TL_RESERVED_WIDTH: f32 = 220.; /// One timeline row. A blank slot (`channel: None`) exists purely to keep /// the block's height constant. #[derive(Clone, Debug, PartialEq)] struct TimelineRow { channel: Option, /// Frame deltas per snapshot, oldest→newest (may exceed [`TL_COLUMNS`]; /// the renderer shows the newest columns). deltas: Vec, /// Cumulative frames seen for the channel — shown before a second /// snapshot makes a delta meaningful. total: u64, /// APs currently on the channel. aps: usize, } /// The rendered timeline: `blocks` side-by-side column stacks of exactly /// [`TL_ROWS`] rows each, plus how many channels the newest snapshot /// reported and how many of them made it on screen. #[derive(Clone, Debug, Default, PartialEq)] struct TimelineView { blocks: Vec>, shown: usize, active: usize, } /// Lay the timeline out for `available_width` px of horizontal space: the /// busiest channels of the newest snapshot — ordered by channel number and /// split into side-by-side column blocks of [`TL_ROWS`] rows — padded to /// whole blocks with blank rows. The row count per block (and therefore the /// block height) is constant whatever the channel set does; channels beyond /// the width's capacity are dropped by frame count, and the caller reports /// them via [`TimelineView::active`] vs [`TimelineView::shown`]. fn timeline_view( tl: &VecDeque>, crowd: &std::collections::HashMap, available_width: f32, ) -> TimelineView { let Some(latest) = tl.back() else { return TimelineView::default(); }; let mut busy = latest.clone(); busy.sort_by_key(|s| std::cmp::Reverse(s.frames)); let active = busy.len(); let blocks = (((available_width.max(0.) / TL_BLOCK_WIDTH) as usize).clamp(1, TL_MAX_BLOCKS)) .min(active.div_ceil(TL_ROWS).max(1)); let capacity = blocks * TL_ROWS; busy.truncate(capacity); busy.sort_by_key(|s| s.channel); let mut rows: Vec = busy .into_iter() .map(|b| { // Frame series across the snapshots that reported this channel // (missed snapshots are skipped, minor skew). let series: Vec = tl .iter() .filter_map(|snap| { snap.iter() .find(|s| s.channel == b.channel) .map(|s| s.frames) }) .collect(); TimelineRow { channel: Some(b.channel), deltas: series .windows(2) .map(|w| w[1].saturating_sub(w[0])) .collect(), total: series.last().copied().unwrap_or(b.frames), aps: *crowd.get(&b.channel).unwrap_or(&0), } }) .collect(); let shown = rows.len(); while rows.len() < capacity { rows.push(TimelineRow { channel: None, deltas: Vec::new(), total: 0, aps: 0, }); } TimelineView { blocks: rows.chunks(TL_ROWS).map(|c| c.to_vec()).collect(), shown, active, } } /// Timeline of per-channel activity: one row per busiest channel, each row /// a right-aligned run of per-snapshot frame-delta columns (opacity = /// relative intensity). A channel hosting ≥4 APs gets a crowded warning — /// overlapping BSSs eat each other's airtime. /// /// Rows are laid out in side-by-side column blocks sized to the available /// width, so a wide window shows more channels instead of wasting the space /// to the right. Every block always renders exactly [`TL_ROWS`] rows — /// unused slots are blank placeholders, same geometry — so channels entering /// or leaving the scan never resize the block: the tables below stay put. fn channel_timeline( app: &AppRoot, theme: &gpuikit::theme::Theme, available_width: f32, ) -> Option { let tl = &app.state.chan_timeline; if tl.is_empty() { return None; } // AP count per channel → crowded-channel warning. let mut crowd: std::collections::HashMap = std::collections::HashMap::new(); for ap in app.state.aps.values() { if ap.channel > 0 { *crowd.entry(ap.channel).or_default() += 1; } } let accent = theme.accent(); // One row builder for data AND placeholder rows: identical geometry is // what keeps the block height constant. let build_row = |label_text: String, warn: bool, cols: Vec, trailer: String| { let mut label = div().w(px(80.)).flex_none().text_xs(); label = if warn { label.text_color(theme.warning()) } else { label.text_color(theme.fg_muted()) }; h_stack() .gap_2() .items_center() .child(label.child(label_text)) .child(h_stack().items_end().children(cols)) .child( div() .w(px(70.)) .flex_none() .text_xs() .text_color(theme.fg_muted()) .child(trailer), ) .into_any_element() }; let blank_cols = || (0..TL_COLUMNS).map(|_| div().w(px(4.)).h(px(12.))); let view = timeline_view(tl, &crowd, available_width); let render_row = |r: &TimelineRow| -> gpui::AnyElement { let Some(ch) = r.channel else { // Unused slot: invisible, but occupying its row. The NBSP // keeps the label/trailer line boxes at full text height so // blank rows match data rows exactly. return build_row( "\u{00a0}".to_string(), false, blank_cols().collect(), "\u{00a0}".to_string(), ); }; let max = r.deltas.iter().copied().max().unwrap_or(0).max(1) as f32; let shown: &[u64] = &r.deltas[r.deltas.len().saturating_sub(TL_COLUMNS)..]; let mut cols: Vec = Vec::with_capacity(TL_COLUMNS); // Left-pad quiet history so rows align at the newest edge. cols.extend(blank_cols().take(TL_COLUMNS.saturating_sub(shown.len()))); for &d in shown { let a = 0.15 + 0.85 * (d as f32 / max); cols.push(div().w(px(4.)).h(px(12.)).bg(accent.opacity(a))); } let warn = r.aps >= TL_CROWD_WARN; let label_text = if warn { format!("ch{ch} ⚠{} APs", r.aps) } else { format!("ch{ch}") }; // Before a second snapshot there is no delta to show — the row // carries the cumulative count instead of a misleading `0 fr`. let last = r.deltas.last().copied().unwrap_or(r.total); build_row(label_text, warn, cols, format!("{last} fr")) }; // Side by side: extra channels widen the block, they never make it // taller. let blocks: Vec = view .blocks .iter() .map(|block| { v_stack() .gap_1() .flex_none() .children(block.iter().map(&render_row).collect::>()) .into_any_element() }) .collect(); let header = if tl.len() < 2 { "channel activity — first snapshot, waiting for deltas".to_string() } else { let mut h = format!( "channel activity — last {} snapshots (one column each), brightest = busiest", tl.len() ); if view.active > view.shown { h.push_str(&format!( " · {} busiest of {} active channels shown", view.shown, view.active )); } h }; Some( v_stack() .gap_1() .child(small(header)) .child(h_stack().gap_6().items_start().children(blocks)) .into_any_element(), ) } /// Channel activity visualization: the fixed-height per-channel timeline, /// hidden only until the first snapshot arrives. `available_width` is the /// window width the timeline may occupy. fn channel_activity( app: &AppRoot, theme: &gpuikit::theme::Theme, available_width: f32, ) -> Option { channel_timeline(app, theme, available_width) } pub fn render( app: &mut AppRoot, view: &Entity, window: &mut Window, cx: &mut Context, ) -> gpui::Div { // Persistent label editor: applies to the selected row (a selected // client wins over the selected AP — see [`label_target`]). let label_bar = label_target(app).map(|mac| { h_stack() .items_center() .gap_2() .child(small("label for")) .child(text(mac.to_string()).code().small().into_any_element()) .child( div() .w(px(240.)) .child(text_field(&app.label_input, cx).placeholder("name this device…")), ) .child(button("btn-label-save", "Save").on_click({ let view = view.clone(); move |_, window, cx| save_label(&view, window, cx) })) .child(small("(empty saves as no label)")) .into_any_element() }); v_stack() .size_full() .gap_3() .p_4() .child( gpuikit::layout::h_stack() .items_center() .gap_3() .child(h3("Access Points")) .child(small(format!( "{} networks — click a row to pick a target", app.state.aps.len() ))), ) .children(label_bar) .children(channel_activity( app, cx.theme(), f32::from(window.viewport_size().width) - TL_RESERVED_WIDTH, )) .child(ap_table(app, view)) .child( gpuikit::layout::h_stack() .items_center() .gap_3() .child(h3("Clients")) .child(small(client_counts(app))), ) .child(client_table(app, view)) .child( gpuikit::layout::h_stack() .items_center() .gap_3() .child(h3("Probes")) .child(small(format!("{} observed", app.state.probes.len()))), ) .child(probe_table(app)) } #[cfg(test)] mod tests { use super::*; use crate::common::ChannelStat; use std::collections::HashMap; fn snap(pairs: &[(u8, u64)]) -> Vec { pairs .iter() .map(|&(channel, frames)| ChannelStat { channel, frames, beacons: 0, }) .collect() } fn timeline(snaps: Vec>) -> VecDeque> { snaps.into() } /// Window width that fits every block (tests use it to isolate the /// channel-count behaviour from the width behaviour). const WIDE: f32 = TL_BLOCK_WIDTH * TL_MAX_BLOCKS as f32; fn rows_of(view: &TimelineView) -> Vec { view.blocks.iter().flatten().cloned().collect() } /// The reported bug: the activity block resized (pushing everything /// below it) when channels were added to or removed from the scan. /// Height is now `TL_ROWS` rows per block whatever the channel set does /// — 4 channels and 20 channels produce the same block height. #[test] fn timeline_height_is_constant_across_channel_sets() { let cases: Vec> = vec![ vec![], vec![(1, 10)], vec![(1, 10), (6, 200), (11, 30), (36, 5)], (1..=12).map(|c| (c, c as u64 * 7)).collect(), (1..=20).map(|c| (c, c as u64 * 7)).collect(), (1..=40).map(|c| (c, c as u64 * 7)).collect(), ]; for set in cases { let view = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), WIDE); for (i, block) in view.blocks.iter().enumerate() { assert_eq!( block.len(), TL_ROWS, "channel set {set:?} block {i} must hold exactly TL_ROWS rows" ); } let rows = rows_of(&view); // Blank slots only ever trail the data rows. let first_blank = rows.iter().position(|r| r.channel.is_none()); if let Some(i) = first_blank { assert!( rows[i..].iter().all(|r| r.channel.is_none()), "blank slots must be trailing: {rows:?}" ); } } // An empty timeline yields no blocks at all (block hidden). assert!( timeline_view(&timeline(vec![]), &HashMap::new(), WIDE) .blocks .is_empty() ); } /// 20 channels: as many column blocks as the width allows, and every /// one of them exactly TL_ROWS rows tall. #[test] fn timeline_uses_horizontal_space_for_many_channels() { let set: Vec<(u8, u64)> = (1..=20).map(|c| (c, 1000 - c as u64)).collect(); let view = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), WIDE); assert_eq!(view.active, 20); assert_eq!(view.shown, 20, "wide window must show all 20 channels"); assert_eq!(view.blocks.len(), 20usize.div_ceil(TL_ROWS)); assert!(view.blocks.iter().all(|b| b.len() == TL_ROWS)); // Narrow window: fewer blocks, extras dropped by frame count (the // busiest survive), height unchanged. let narrow = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), TL_BLOCK_WIDTH); assert_eq!(narrow.blocks.len(), 1); assert_eq!(narrow.shown, TL_ROWS); assert_eq!(narrow.active, 20); let kept: Vec = rows_of(&narrow).iter().filter_map(|r| r.channel).collect(); assert_eq!( kept, vec![1, 2, 3, 4, 5, 6, 7, 8], "busiest kept, ascending" ); // No more blocks than the cap, however wide the window gets. The // block count is also bounded by how many channels exist — a 40 // channel set is what can actually reach the cap. let many: Vec<(u8, u64)> = (1..=40).map(|c| (c, 1000 - c as u64)).collect(); let huge = timeline_view(&timeline(vec![snap(&many)]), &HashMap::new(), 100_000.); assert_eq!(huge.blocks.len(), TL_MAX_BLOCKS); assert_eq!(huge.shown, TL_MAX_BLOCKS * TL_ROWS, "capacity is the cap"); assert_eq!(huge.active, 40); assert!( huge.shown < huge.active, "the header must be able to report dropped channels" ); } /// Surviving channels keep their relative order whatever else joins or /// leaves the busiest set, so rows don't shuffle between scans. #[test] fn timeline_order_is_by_channel() { let sets = [ vec![(1, 10), (6, 200), (36, 5)], vec![(3, 900), (1, 10), (36, 5), (11, 40)], vec![(11, 40), (36, 5)], ]; for set in sets { let view = timeline_view(&timeline(vec![snap(&set)]), &HashMap::new(), WIDE); let channels: Vec = rows_of(&view).iter().filter_map(|r| r.channel).collect(); let mut sorted = channels.clone(); sorted.sort_unstable(); assert_eq!(channels, sorted, "rows must ascend by channel: {set:?}"); } } #[test] fn timeline_deltas_and_totals() { let mut crowd = HashMap::new(); crowd.insert(6, 5); // ch6 reported in every snapshot, ch11 missing from the middle one. let tl = timeline(vec![ snap(&[(6, 100), (11, 10)]), snap(&[(6, 160)]), snap(&[(6, 200), (11, 50)]), ]); let view = timeline_view(&tl, &crowd, WIDE); let rows = rows_of(&view); let ch6 = rows.iter().find(|r| r.channel == Some(6)).expect("ch6 row"); assert_eq!(ch6.deltas, vec![60, 40], "consecutive deltas"); assert_eq!(ch6.total, 200); assert_eq!(ch6.aps, 5); let ch11 = rows .iter() .find(|r| r.channel == Some(11)) .expect("ch11 row"); // Missed snapshot skipped: the delta spans the gap. assert_eq!(ch11.deltas, vec![40]); assert_eq!(ch11.total, 50); // A single snapshot has no delta yet — the row shows the total. let view = timeline_view(&timeline(vec![snap(&[(1, 42)])]), &HashMap::new(), WIDE); let ch1 = rows_of(&view) .into_iter() .find(|r| r.channel == Some(1)) .expect("ch1 row"); assert!(ch1.deltas.is_empty()); assert_eq!(ch1.total, 42); } #[test] fn risk_rank_orders_rogue_over_weak_over_none() { let mut rogues = std::collections::HashSet::new(); rogues.insert(norm_ssid("evil-twin")); let ap = |ssid: &str, sec: Security| AccessPoint { bssid: MacAddr([1, 2, 3, 4, 5, 6]), ssid: ssid.to_string(), channel: 6, security: sec, rssi_dbm: -50, beacons: 1, last_seen_ms: 0, akms: Vec::new(), }; let rogue = ap("evil-twin", Security::Wpa2); let weak = ap("open-wifi", Security::Open); let wep = ap("old-ap", Security::Wep); let fine = ap("home", Security::Wpa2); assert_eq!(risk_rank(&rogue, &rogues), 2); assert_eq!(risk_rank(&weak, &rogues), 1); assert_eq!(risk_rank(&wep, &rogues), 1); assert_eq!(risk_rank(&fine, &rogues), 0); // A hidden SSID can never be flagged rogue (nothing to match). let hidden = ap("", Security::Wpa2); assert_eq!(risk_rank(&hidden, &rogues), 0); // Sorting by the FLAGS column puts the worst first ascending. let mut order = [fine.clone(), weak.clone(), rogue.clone()]; order.sort_by_key(|a| risk_rank(a, &rogues)); assert_eq!(order[0].ssid, "home"); assert_eq!(order[1].ssid, "open-wifi"); assert_eq!(order[2].ssid, "evil-twin"); } /// Ten tags on one AP must not grow the cell, push its neighbours, or /// silently vanish: whatever does not fit becomes `+N`, and the tag the /// user must not miss (the worst) is always the one drawn. #[test] fn flags_column_collapses_overflow_into_a_marker() { // A synthetic worst case: ten tags of the shape real ones have. let many: Vec = (0..10) .map(|i| RiskTag { label: if i % 2 == 0 { "rogue?" } else { "weak" }, severity: 2, }) .collect(); let (shown, hidden) = fit_tags(&many, FLAGS_W); assert!(shown < many.len(), "ten tags cannot all fit one cell"); assert_eq!(shown + hidden, many.len(), "every tag is accounted for"); assert!(shown >= 1, "at least the worst tag stays visible"); // What is drawn — badges plus the marker — stays inside the column. let drawn: f32 = many[..shown] .iter() .map(|t| badge_width(t.label)) .sum::() + FLAGS_GAP * shown.saturating_sub(1) as f32 + FLAGS_MORE_W; assert!( drawn <= FLAGS_W, "drawn width {drawn} must fit the {FLAGS_W} px column" ); } #[test] fn fit_tags_is_conservative_at_every_width() { let tags = |n: usize| -> Vec { (0..n) .map(|_| RiskTag { label: "rogue?", severity: 2, }) .collect() }; for n in 0..=12 { let list = tags(n); for width in [0., 20., 40., 80., 120., FLAGS_W, 300., 1000.] { let (shown, hidden) = fit_tags(&list, width); assert_eq!( shown + hidden, n, "tags must be conserved (n={n}, w={width})" ); let drawn: f32 = list[..shown] .iter() .map(|t| badge_width(t.label)) .sum::() + FLAGS_GAP * shown.saturating_sub(1) as f32 + if hidden > 0 { FLAGS_MORE_W } else { 0.0 }; assert!( drawn <= width.max(FLAGS_MORE_W), "n={n} width={width}: drawn {drawn} overflows" ); if n > 0 && width >= badge_width("rogue?") + FLAGS_MORE_W { assert!(shown >= 1, "n={n} width={width}: nothing shown"); } } } assert_eq!(fit_tags(&[], FLAGS_W), (0, 0)); } /// One order for tags everywhere: worst first, and the column sort uses /// the worst tag's severity. #[test] fn risk_tags_are_ordered_worst_first() { let mut rogues = std::collections::HashSet::new(); rogues.insert(norm_ssid("evil-twin")); let ap = |ssid: &str, sec: Security| AccessPoint { bssid: MacAddr([9, 9, 9, 9, 9, 9]), ssid: ssid.to_string(), channel: 6, security: sec, rssi_dbm: -50, beacons: 1, last_seen_ms: 0, akms: Vec::new(), }; let labels = |ap: &AccessPoint| -> Vec<&'static str> { risk_tags(ap, &rogues).iter().map(|t| t.label).collect() }; assert_eq!(labels(&ap("evil-twin", Security::Open)), ["rogue?", "weak"]); assert_eq!(labels(&ap("open-wifi", Security::Open)), ["weak"]); assert_eq!(labels(&ap("home", Security::Wpa2)), [] as [&str; 0]); assert_eq!(risk_rank(&ap("evil-twin", Security::Wep), &rogues), 2); assert_eq!(risk_rank(&ap("home", Security::Wpa2), &rogues), 0); } }