Files
alkane-toolkit/crates/alkane-gui/src/ui.rs
T
noahandClaude Opus 4.8 d88df603ba Fix GUI layout/crash bugs; add operator features, tests, and dev loop
Round 1 (bug fixes + test harness):
- Fix table rendering in the top-left corner: the dvlc was never added to the
  sizer; add it (proportion 1) and re-run layout; drop the space-eating stretch.
- Fix abort on dialog buttons: the dialog root sizers passed ALIGN_CENTRE_VERTICAL
  to a vertical sizer, tripping a wx consistency assert whose handler pumps a
  nested event loop, re-entering dispatch while it held the App RefCell borrow.
  Remove the invalid flags; split dispatch into two phases with try_borrow_mut.
- Fix header-click sort mapping when columns are hidden (use display_columns);
  drag-reorder splices back into the full order without dropping hidden columns.
- Add offline fixtures + ALKANE_FAKE_SCAN and ALKANE_SELFTEST modes; scripts
  ui-selftest.sh and ui-screenshot.sh; AGENTS.md documents the dev loop.

Round 2 (operator requests):
- Redesigned color-coded KPI cards; light/dark mode follows the system theme.
- SI-formatted hashrate/power on the KPIs and columns (685 TH/s, 21.3 kW).
- Scan ranges accept CIDR, single IP, and A.B.C.D-E.F.G.H / A.B.C.D-N ranges;
  oversized ranges (> 1,000,000 addresses) are rejected.
- Scan progress bar over the table + status-bar text; out-of-range miners are
  dropped when a scan starts.
- Columns panel exposes every scannable MinerData metric (All / None / Defaults).
- Excel-style filter panel: per-category value checklists, per-column All/None,
  Apply / Reset / Cancel, blank handling.
- Sort direction marker in the header (updated in place); double-click a row
  opens the miner in the default browser.

wx-rs: extend the widget bridge (gauge, in-place column title, sort indicator,
browser launch, system appearance/colours, widget colours, item-activated);
patches 0002/0003 regenerated and round-trip validated.

Verified: 22 unit tests + a 13-check headless UI self-test, plus a live scan
against the bench fleet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-16 16:24:05 -06:00

798 lines
33 KiB
Rust

//! Primary view per docs/UI-SPEC.md: KPI header, scan-ranges editor,
//! Excel-style filter panel, columns panel, sortable/drag-reorderable table.
use crate::model::*;
use crate::scan::{self, ScanMsg};
use std::cell::RefCell;
use std::collections::HashSet;
use std::sync::mpsc::Receiver;
use wx_rs::{Widget, WxEvent, WxEventKind, sizer_flags as sf};
pub const ID_RANGES: i32 = 101;
pub const ID_FILTER: i32 = 102;
pub const ID_COLUMNS: i32 = 103;
pub const ID_RESCAN: i32 = 104;
const ID_RANGES_APPLY: i32 = 201;
const ID_RANGES_CANCEL: i32 = 202;
const ID_COLUMNS_OK: i32 = 203;
const ID_COLUMNS_CANCEL: i32 = 204;
const ID_COLUMNS_ALL: i32 = 207;
const ID_COLUMNS_NONE: i32 = 208;
const ID_COLUMNS_RESET: i32 = 209;
const ID_FILTER_OK: i32 = 205;
const ID_FILTER_CANCEL: i32 = 206;
const ID_FILTER_RESET: i32 = 210;
// Per-column "All"/"None" buttons in the filter panel are ID_FILTER_ALL_BASE +
// column index (and the None equivalent). 100 columns of headroom each.
const ID_FILTER_ALL_BASE: i32 = 300;
const ID_FILTER_NONE_BASE: i32 = 500;
const TIMER_SCAN: i32 = 1;
/// Theme-aware palette for the KPI cards. Health is encoded in colour so a red
/// "Not hashing" or amber "Slow" draws the eye immediately.
struct Palette {
card_bg: (u8, u8, u8),
label: (u8, u8, u8),
neutral: (u8, u8, u8),
green: (u8, u8, u8),
amber: (u8, u8, u8),
red: (u8, u8, u8),
accent: (u8, u8, u8),
}
fn palette(dark: bool) -> Palette {
if dark {
Palette {
card_bg: (44, 46, 51),
label: (150, 156, 164),
neutral: (228, 230, 234),
green: (74, 222, 128),
amber: (245, 190, 66),
red: (245, 110, 100),
accent: (108, 168, 250),
}
} else {
Palette {
card_bg: (255, 255, 255),
label: (108, 114, 122),
neutral: (28, 32, 38),
green: (33, 140, 80),
amber: (176, 120, 10),
red: (198, 55, 45),
accent: (40, 100, 170),
}
}
}
pub struct App {
pub rows: Vec<MinerRow>,
pub view: ViewState,
pub view_idx: Vec<usize>,
kpi_total: Widget,
kpi_hashing: Widget,
kpi_slow: Widget,
kpi_not: Widget,
kpi_hashrate: Widget,
kpi_power: Widget,
ranges_btn: Widget,
progress: Widget,
pub table: Option<Widget>,
table_parent: Widget,
root_sizer: Widget,
pub scan_rx: Option<Receiver<ScanMsg>>,
pub scanning: bool,
scan_total: usize,
target_ips: HashSet<String>,
ranges_dialog: Widget,
ranges_edit: Widget,
columns_dialog: Widget,
columns_list: Widget,
filter_dialog: Widget,
filter_lists: Vec<(Column, Widget)>,
}
pub fn build(frame: Widget) -> App {
let dark = wx_rs::is_dark();
let pal = palette(dark);
let panel = Widget::panel(frame);
let root = Widget::box_sizer(true);
// KPI header: a row of equal-width cards, each a big value over a small
// label. Health KPIs are colour-coded (green/amber/red); hashrate uses the
// accent colour so totals stand apart from counts.
let kpi_row = Widget::box_sizer(false);
let mk_card = |label: &str, value_color: (u8, u8, u8)| -> Widget {
let card = Widget::panel(panel);
card.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
let cs = Widget::box_sizer(true);
let value = Widget::static_text(card, "0");
value.set_font_size(19);
value.set_bold();
value.set_fg(value_color.0, value_color.1, value_color.2);
value.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
let lbl = Widget::static_text(card, label);
lbl.set_font_size(9);
lbl.set_fg(pal.label.0, pal.label.1, pal.label.2);
lbl.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
cs.add(value, 0, sf::BORDER_LEFT | sf::BORDER_TOP | sf::BORDER_RIGHT, 12);
cs.add(lbl, 0, sf::BORDER_LEFT | sf::BORDER_BOTTOM | sf::BORDER_RIGHT, 12);
cs.set_sizer_on(card);
kpi_row.add(card, 1, sf::EXPAND | sf::BORDER_ALL, 4);
value
};
let kpi_total = mk_card("Total", pal.neutral);
let kpi_hashing = mk_card("Hashing", pal.green);
let kpi_slow = mk_card("Slow", pal.amber);
let kpi_not = mk_card("Not hashing", pal.red);
let kpi_hashrate = mk_card("Hashrate", pal.accent);
let kpi_power = mk_card("Est. power", pal.neutral);
root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6);
// Controls row: scan-ranges button on the left; Filter / Columns / Rescan
// pushed to the right.
let ctl = Widget::box_sizer(false);
let ranges_btn = Widget::button(panel, "Scan ranges", ID_RANGES);
ctl.add(ranges_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
ctl.add_stretch(1);
let filter_btn = Widget::button(panel, "Filter", ID_FILTER);
ctl.add(filter_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
let columns_btn = Widget::button(panel, "Columns", ID_COLUMNS);
ctl.add(columns_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
let rescan_btn = Widget::button(panel, "Rescan", ID_RESCAN);
ctl.add(rescan_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
// Scan-progress bar across the top of the table (hidden when idle).
let progress = Widget::gauge(panel, 1);
root.add(progress, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
progress.show(false);
// The table is created in rebuild_table and added to `root` there.
let table_parent = panel;
root.set_sizer_on(panel);
let frame_sizer = Widget::box_sizer(true);
frame_sizer.add(panel, 1, sf::EXPAND, 0);
frame_sizer.set_sizer_on(frame);
frame.set_min_size(1200, 720);
// A status bar carries scan state (was an inline label).
wx_rs::create_status_bar();
wx_rs::set_status_text("starting scan...");
let ranges = scan::load_ranges();
let mut app = App {
rows: Vec::new(),
view: ViewState::default(),
view_idx: Vec::new(),
kpi_total,
kpi_hashing,
kpi_slow,
kpi_not,
kpi_hashrate,
kpi_power,
ranges_btn,
progress,
table: None,
table_parent,
root_sizer: root,
scan_rx: Some(scan::start_scan(ranges.clone())),
scanning: true,
scan_total: 0,
target_ips: HashSet::new(),
ranges_dialog: frame,
ranges_edit: frame,
columns_dialog: frame,
columns_list: frame,
filter_dialog: frame,
filter_lists: Vec::new(),
};
app.ranges_btn.set_label(&format!("Scan ranges: {}", ranges.join(", ")));
app.rebuild_table();
Widget::timer(TIMER_SCAN, 1000);
app
}
impl App {
pub fn rebuild_table(&mut self) {
// Detach the old table from the sizer before destroying it, so the
// sizer never holds a dangling item, then drop it.
if let Some(t) = self.table.take() {
self.root_sizer.detach(t);
t.destroy();
}
let t = Widget::dvlc(self.table_parent);
// creation order == display order: Sel toggle column first (fixed),
// then Ip (fixed), then the reorderable statistics columns. The active
// sort column carries an ASCII direction marker in its header ("^" asc,
// "v" desc) -- wx's native SetSortOrder re-sorts the store lexically and
// would fight our numeric sort, so we mark the header text instead.
t.dvlc_append_toggle_col(28);
for c in self.view.display_columns().iter().skip(1) {
let fixed = self.view.is_fixed(*c);
let mut title = c.title().to_string();
match self.view.sort {
Some((sc, true)) if sc == *c => title.push_str(" ^"),
Some((sc, false)) if sc == *c => title.push_str(" v"),
_ => {}
}
t.dvlc_append_text_col(&title, c.width(), !fixed);
}
// Add the table to the root sizer (proportion 1 => fills the area under
// the KPI + controls rows) and re-run the panel's layout so it is
// positioned, not left floating at (0,0). This was the "table in the
// top-left corner" bug: the control was created but never sized.
self.root_sizer.add(t, 1, sf::EXPAND | sf::BORDER_ALL, 4);
self.table = Some(t);
self.table_parent.layout();
self.fill_rows();
}
pub fn fill_rows(&mut self) {
let Some(t) = self.table else { return };
t.dvlc_clear();
self.view_idx = self.view.view(&self.rows);
let cols = self.view.display_columns();
for &ri in &self.view_idx {
let r = &self.rows[ri];
// The toggle column carries the checked state ("1"/"0") so a refresh
// preserves selection; other columns carry their text.
let cells: Vec<String> = cols
.iter()
.map(|c| match c {
Column::Sel => if r.selected { "1".to_string() } else { "0".to_string() },
_ => c.cell(r),
})
.collect();
let refs: Vec<&str> = cells.iter().map(|s| s.as_str()).collect();
t.dvlc_append_row(&refs);
}
self.refresh_kpis();
}
pub fn refresh_kpis(&self) {
let k = compute_kpis(&self.rows, &self.view_idx);
self.kpi_total.set_label(&k.total.to_string());
self.kpi_hashing.set_label(&k.hashing.to_string());
self.kpi_slow.set_label(&k.slow.to_string());
self.kpi_not.set_label(&k.not_hashing.to_string());
self.kpi_hashrate.set_label(&format_si(k.total_hashrate_ths * 1e12, "H/s"));
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
}
pub fn drain_scan(&mut self) {
let Some(rx) = &self.scan_rx else { return };
let mut changed = false;
loop {
match rx.try_recv() {
Ok(ScanMsg::Started { total, targets }) => {
// Drop miners no longer in the target range.
let before = self.rows.len();
self.rows.retain(|r| targets.contains(&r.ip));
changed |= self.rows.len() != before;
self.target_ips = targets;
self.scan_total = total;
self.scanning = true;
self.progress.gauge_set_range(total.max(1) as i32);
self.progress.gauge_set_value(0);
self.progress.show(true);
self.table_parent.layout();
wx_rs::set_status_text(&format!("scanning {total} addresses..."));
}
Ok(ScanMsg::Progress { done, total }) => {
self.scan_total = total;
self.progress.gauge_set_value(done.min(total) as i32);
wx_rs::set_status_text(&format!(
"scanning {done}/{total} - {} found",
self.rows.len()
));
}
Ok(ScanMsg::Row(row)) => {
// Ignore stray rows outside the current target set.
if self.target_ips.is_empty() || self.target_ips.contains(&row.ip) {
row.upsert_into(&mut self.rows);
changed = true;
}
}
Ok(ScanMsg::Done(s)) => {
self.scanning = false;
self.progress.gauge_set_value(self.scan_total.max(1) as i32);
self.progress.show(false);
self.table_parent.layout();
wx_rs::set_status_text(&format!("scan complete: {} found in {s}", self.rows.len()));
}
Ok(ScanMsg::Failed(e)) => {
self.scanning = false;
self.progress.show(false);
self.table_parent.layout();
wx_rs::set_status_text(&format!("scan failed: {e}"));
}
Err(_) => break,
}
}
if changed {
self.fill_rows();
}
}
fn toggle_select(&mut self, store_row: usize, _col: usize) {
// The toggle renderer + list store update themselves visually; we
// flip the model and refresh the KPIs (selection is not a KPI, but
// keep state coherent for future bulk actions).
if let Some(&ri) = self.view_idx.get(store_row) {
if let Some(r) = self.rows.get_mut(ri) {
r.selected = !r.selected;
}
}
}
/// Row activated (double-click / Enter): open the miner's web UI in the
/// system browser.
fn activate_row(&mut self, store_row: usize) {
if let Some(&ri) = self.view_idx.get(store_row) {
if let Some(r) = self.rows.get(ri) {
if !r.ip.is_empty() {
wx_rs::launch_browser(&format!("http://{}", r.ip));
}
}
}
}
fn header_click(&mut self, creation_idx: usize) {
// Columns are appended to the table in display order (toggle col first,
// then each visible column). Map the clicked creation index back to a
// model column through display_columns(), not view.order, so hidden
// columns don't shift the mapping.
let cols = self.view.display_columns();
if creation_idx == 0 || creation_idx >= cols.len() {
return; // toggle column (idx 0) is not sortable
}
let col = cols[creation_idx];
self.view.sort = match self.view.sort {
Some((c, true)) if c == col => Some((col, false)),
Some((c, false)) if c == col => None,
_ => Some((col, true)),
};
// Update the header marker in place + re-sort rows. Avoids destroying and
// recreating the whole control on every sort click (janky on big fleets).
self.update_headers();
self.fill_rows();
}
/// Refresh each column header's ASCII sort marker ("^" asc, "v" desc) in
/// place, without recreating the table.
fn update_headers(&self) {
let Some(t) = self.table else { return };
for (i, c) in self.view.display_columns().iter().enumerate() {
if i == 0 {
continue; // toggle column has no title
}
let mut title = c.title().to_string();
match self.view.sort {
Some((sc, true)) if sc == *c => title.push_str(" ^"),
Some((sc, false)) if sc == *c => title.push_str(" v"),
_ => {}
}
t.dvlc_set_col_title(i, &title);
}
}
fn column_reordered(&mut self) {
let Some(t) = self.table else { return };
// The table only holds the VISIBLE columns; a creation index maps to a
// model column via display_columns(). Read the new visible order from
// the drag result and hand it to the model, which splices it back into
// the full column order while leaving hidden columns in place.
let disp = self.view.display_columns();
let n = t.dvlc_col_count();
let mut new_visible = Vec::with_capacity(n);
for pos in 0..n {
let creation = t.dvlc_col_at_pos(pos).unwrap_or(pos);
if let Some(&c) = disp.get(creation) {
new_visible.push(c);
}
}
self.view.apply_visible_reorder(&new_visible);
}
/// Build (but do not show) the ranges editor. The caller shows it modally
/// *after* releasing the App borrow; see `dispatch`.
fn build_ranges_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Edit IP scanning ranges");
let root = Widget::box_sizer(true);
let hint = Widget::static_text(
dlg,
"One range per line:\n CIDR 10.255.1.0/24\n range 10.253.1.3-10.253.1.234\n single 10.253.1.5",
);
root.add(hint, 0, sf::BORDER_ALL, 6);
let edit = Widget::text_ctrl(dlg, true);
edit.set_value(&scan::load_ranges().join("\n"));
root.add(edit, 1, sf::EXPAND | sf::BORDER_ALL, 6);
let btns = Widget::box_sizer(false);
let apply = Widget::button(dlg, "Apply", ID_RANGES_APPLY);
btns.add(apply, 0, sf::BORDER_ALL, 6);
let cancel = Widget::button(dlg, "Cancel", ID_RANGES_CANCEL);
btns.add(cancel, 0, sf::BORDER_ALL, 6);
// `root` is a vertical sizer: only border flags are valid here. Using
// ALIGN_CENTRE_VERTICAL trips a wxWidgets consistency assert whose
// handler pumps a nested event loop -> re-entrant dispatch -> crash.
root.add_sizer(btns, 0, sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
self.ranges_dialog = dlg;
self.ranges_edit = edit;
dlg
}
fn apply_ranges(&mut self) {
let text = self.ranges_edit.get_value();
let lines: Vec<String> = text
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(String::from)
.collect();
if lines.is_empty() {
wx_rs::set_status_text("no ranges given");
self.ranges_dialog.close(0);
return;
}
if let Err(e) = scan::validate_ranges(&lines) {
wx_rs::set_status_text(&format!("invalid range: {e}"));
return; // keep dialog open
}
let _ = scan::save_ranges(&lines);
self.scan_rx = Some(scan::start_scan(lines.clone()));
self.scanning = true;
wx_rs::set_status_text("scanning...");
self.ranges_btn.set_label(&format!("Scan ranges: {}", lines.join(", ")));
self.ranges_dialog.close(1);
}
/// The columns available to show/hide: every metric except the fixed
/// Sel + Ip columns, in registry order (matches the check-list order).
fn selectable_columns() -> Vec<Column> {
ALL_COLUMNS
.iter()
.copied()
.filter(|c| *c != Column::Sel && *c != Column::Ip)
.collect()
}
/// Build (but do not show) the columns chooser. Every scannable metric is
/// listed, so any of them can be shown.
fn build_columns_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Choose columns");
let root = Widget::box_sizer(true);
let hint = Widget::static_text(dlg, "Show any scannable metric (IP is always shown):");
root.add(hint, 0, sf::BORDER_ALL, 6);
let list = Widget::check_list_box(dlg);
for c in Self::selectable_columns() {
list.clb_append(c.title());
list.clb_set_checked(list.clb_count() - 1, self.view.visible.contains(&c));
}
root.add(list, 1, sf::EXPAND | sf::BORDER_ALL, 6);
// quick actions
let quick = Widget::box_sizer(false);
quick.add(Widget::button(dlg, "All", ID_COLUMNS_ALL), 0, sf::BORDER_ALL, 4);
quick.add(Widget::button(dlg, "None", ID_COLUMNS_NONE), 0, sf::BORDER_ALL, 4);
quick.add(Widget::button(dlg, "Defaults", ID_COLUMNS_RESET), 0, sf::BORDER_ALL, 4);
root.add_sizer(quick, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
let btns = Widget::box_sizer(false);
btns.add(Widget::button(dlg, "OK", ID_COLUMNS_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_COLUMNS_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
self.columns_dialog = dlg;
self.columns_list = list;
dlg
}
/// Check or uncheck every item in the columns list (visual only).
fn columns_check_all(&self, checked: bool) {
let list = self.columns_list;
for i in 0..list.clb_count() {
list.clb_set_checked(i, checked);
}
}
/// Reset the columns list to the default-visible set (visual only).
fn columns_reset_defaults(&self) {
let list = self.columns_list;
for (i, c) in Self::selectable_columns().iter().enumerate() {
list.clb_set_checked(i, DEFAULT_VISIBLE.contains(c));
}
}
fn apply_columns(&mut self) {
let list = self.columns_list;
for (i, c) in Self::selectable_columns().iter().enumerate() {
if list.clb_checked(i) {
self.view.visible.insert(*c);
} else {
self.view.visible.remove(c);
}
}
// keep sort column visible-ish: drop sort if hidden
if let Some((c, _)) = self.view.sort {
if !self.view.visible.contains(&c) {
self.view.sort = None;
}
}
self.columns_dialog.close(1);
self.rebuild_table();
}
/// Build (but do not show) the Excel-style filter panel. Every visible
/// column with more than one distinct value gets a per-column value
/// checklist with All / None controls; filters AND across columns and OR
/// within a column. Blank cells show as "(blank)".
fn build_filter_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Filter");
let root = Widget::box_sizer(true);
let content = Widget::box_sizer(false); // side-by-side column filters
let mut lists = Vec::new();
for c in self.view.display_columns() {
// Value checklists only make sense for categorical columns; skip the
// checkbox column and continuous numeric metrics.
if c == Column::Sel || c.is_numeric() {
continue;
}
let mut values: Vec<String> = self.rows.iter().map(|r| c.cell(r)).collect();
values.sort();
values.dedup();
if values.len() < 2 {
continue;
}
let idx = lists.len() as i32;
let colbox = Widget::box_sizer(true);
let head = Widget::box_sizer(false);
let lbl = Widget::static_text(dlg, c.title());
lbl.set_bold();
head.add(lbl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
head.add(Widget::button(dlg, "All", ID_FILTER_ALL_BASE + idx), 0, sf::BORDER_ALL, 1);
head.add(Widget::button(dlg, "None", ID_FILTER_NONE_BASE + idx), 0, sf::BORDER_ALL, 1);
colbox.add_sizer(head, 0, sf::EXPAND | sf::BORDER_ALL, 2);
let lst = Widget::check_list_box(dlg);
lst.set_min_size(140, 220); // so Fit gives the checklist real space
let current: Option<HashSet<String>> = self.view.filters.get(&c).cloned();
for v in &values {
let shown = if v.is_empty() { "(blank)" } else { v.as_str() };
lst.clb_append(shown);
let checked = match &current {
Some(allowed) => allowed.contains(v),
None => true,
};
lst.clb_set_checked(lst.clb_count() - 1, checked);
}
colbox.add(lst, 1, sf::EXPAND | sf::BORDER_ALL, 2);
content.add_sizer(colbox, 1, sf::EXPAND | sf::BORDER_ALL, 4);
lists.push((c, lst));
}
if lists.is_empty() {
let lbl = Widget::static_text(dlg, "Nothing to filter yet - run a scan first.");
content.add(lbl, 0, sf::BORDER_ALL, 8);
}
root.add_sizer(content, 1, sf::EXPAND | sf::BORDER_ALL, 4);
let btns = Widget::box_sizer(false);
btns.add(Widget::button(dlg, "Apply", ID_FILTER_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Reset", ID_FILTER_RESET), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_FILTER_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
// Size the dialog to fit however many category columns there are.
dlg.fit(dlg);
self.filter_dialog = dlg;
self.filter_lists = lists;
dlg
}
/// Check or uncheck every value in one column's list (0-based index into
/// `filter_lists`).
fn filter_check_all(&self, idx: usize, checked: bool) {
if let Some((_c, lst)) = self.filter_lists.get(idx) {
for i in 0..lst.clb_count() {
lst.clb_set_checked(i, checked);
}
}
}
fn apply_filter(&mut self) {
for (c, lst) in &self.filter_lists {
let count = lst.clb_count();
let mut allowed = HashSet::new();
for i in 0..count {
if lst.clb_checked(i) {
// map the shown "(blank)" back to the empty string
let v = lst.clb_string(i).unwrap_or_default();
allowed.insert(if v == "(blank)" { String::new() } else { v });
}
}
if allowed.is_empty() || allowed.len() == count {
self.view.filters.remove(c); // all (or none) checked = no filter
} else {
self.view.filters.insert(*c, allowed);
}
}
self.filter_dialog.close(1);
self.fill_rows();
}
fn reset_filters(&mut self) {
self.view.filters.clear();
self.filter_dialog.close(1);
self.fill_rows();
}
/// Handle one widget event under the App borrow. Returns a dialog to show
/// modally *after* the borrow is released (see `dispatch`); all in-place
/// work is done here, so most events return None.
fn handle(&mut self, ev: WxEvent) -> Option<Widget> {
match ev.kind {
WxEventKind::ButtonClicked => {
let id = ev.p1 as i32;
match id {
ID_RANGES => return Some(self.build_ranges_dialog()),
ID_RANGES_APPLY => self.apply_ranges(),
ID_RANGES_CANCEL => self.ranges_dialog.close(0),
ID_COLUMNS => return Some(self.build_columns_dialog()),
ID_COLUMNS_OK => self.apply_columns(),
ID_COLUMNS_CANCEL => self.columns_dialog.close(0),
ID_COLUMNS_ALL => self.columns_check_all(true),
ID_COLUMNS_NONE => self.columns_check_all(false),
ID_COLUMNS_RESET => self.columns_reset_defaults(),
ID_FILTER => return Some(self.build_filter_dialog()),
ID_FILTER_OK => self.apply_filter(),
ID_FILTER_CANCEL => self.filter_dialog.close(0),
ID_FILTER_RESET => self.reset_filters(),
ID_RESCAN => {
let ranges = scan::load_ranges();
self.scan_rx = Some(scan::start_scan(ranges));
self.scanning = true;
wx_rs::set_status_text("scanning...");
}
_ if (ID_FILTER_ALL_BASE..ID_FILTER_NONE_BASE).contains(&id) => {
self.filter_check_all((id - ID_FILTER_ALL_BASE) as usize, true);
}
_ if (ID_FILTER_NONE_BASE..ID_FILTER_NONE_BASE + 200).contains(&id) => {
self.filter_check_all((id - ID_FILTER_NONE_BASE) as usize, false);
}
_ => {}
}
}
WxEventKind::DvlcHeaderClick => self.header_click(ev.p1 as usize),
WxEventKind::DvlcValueChanged => self.toggle_select(ev.p1 as usize, ev.p2 as usize),
WxEventKind::DvlcActivated => self.activate_row(ev.p1 as usize),
WxEventKind::DvlcReordered => self.column_reordered(),
WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => self.drain_scan(),
_ => {}
}
None
}
/// Headless workflow self-test: load the bench-fleet fixtures, render them
/// through the real widgets, then read back what the table and KPIs
/// actually display and compare to the expected hardware output. Prints one
/// line per check and returns true iff every check passed.
pub fn run_fixture_selftest(&mut self) -> bool {
self.rows = crate::fixtures::bench_fleet();
self.view = ViewState::default();
self.fill_rows();
let mut ok = true;
let mut check = |name: &str, pass: bool, detail: String| {
println!("[{}] {}{}", if pass { "PASS" } else { "FAIL" }, name,
if detail.is_empty() { String::new() } else { format!(" -- {detail}") });
ok &= pass;
};
// 1. KPI values: independent, hand-computed from the fixtures. The
// labels are static; the value widgets carry the numbers.
let want_kpis = [
(self.kpi_total, "Total", "9"),
(self.kpi_hashing, "Hashing", "6"),
(self.kpi_slow, "Slow", "1"),
(self.kpi_not, "Not hashing", "2"),
(self.kpi_hashrate, "Hashrate", "685 TH/s"),
(self.kpi_power, "Est. power", "21.3 kW"),
];
for (w, name, want) in want_kpis {
let got = w.get_label();
check(&format!("kpi {name} == \"{want}\""), got == want, format!("got \"{got}\""));
}
let Some(t) = self.table else {
check("table exists", false, "no table widget".into());
return false;
};
let cols = self.view.display_columns();
// 2. Row count in the store matches the (unfiltered) fixture count.
let want_rows = self.view_idx.len();
check("table row count == 9",
t.dvlc_row_count() == 9 && want_rows == 9,
format!("store={}, view={}", t.dvlc_row_count(), want_rows));
// 3. Every store cell equals what the model produced for that row/col
// (catches column-order / off-by-one / append bugs).
let mut mismatches = 0;
for (disp_row, &ri) in self.view_idx.iter().enumerate() {
let r = &self.rows[ri];
for (j, c) in cols.iter().enumerate().skip(1) {
let want = c.cell(r);
let got = t.dvlc_get_cell(disp_row, j).unwrap_or_default();
if got != want {
if mismatches < 5 {
println!(" cell[{disp_row}][{j}] {}: want \"{want}\" got \"{got}\"", c.title());
}
mismatches += 1;
}
}
}
check("every table cell matches the model", mismatches == 0,
format!("{mismatches} mismatched cells"));
// 4. Independent spot-checks by IP against the known hardware output.
let ip_col = cols.iter().position(|c| *c == Column::Ip);
let status_col = cols.iter().position(|c| *c == Column::Status);
let hr_col = cols.iter().position(|c| *c == Column::Hashrate);
let find = |ip: &str| -> Option<usize> {
self.view_idx.iter().position(|&ri| self.rows[ri].ip == ip)
};
let cell = |row: usize, col: Option<usize>| -> String {
match col { Some(c) => t.dvlc_get_cell(row, c).unwrap_or_default(), None => String::new() }
};
if let (Some(row), Some(_)) = (find("10.255.1.149"), status_col) {
check("S21 Pro (.149) is slow", cell(row, status_col) == "slow",
format!("status=\"{}\"", cell(row, status_col)));
check("S21 Pro (.149) hashrate == 60.0 TH/s", cell(row, hr_col) == "60.0 TH/s",
format!("hashrate=\"{}\"", cell(row, hr_col)));
} else {
check("S21 Pro (.149) present", false, "row not found".into());
}
if let Some(row) = find("10.255.1.112") {
check("S17 (.112) is not hashing", cell(row, status_col) == "not hashing",
format!("status=\"{}\"", cell(row, status_col)));
check("S17 (.112) blank hashrate", cell(row, hr_col).is_empty(),
format!("hashrate=\"{}\"", cell(row, hr_col)));
} else {
check("S17 (.112) present", false, "row not found".into());
}
check("IP is the first text column", ip_col == Some(1),
format!("ip col index = {ip_col:?}"));
ok
}
}
// The wx event loop is single-threaded; keep the app in a thread-local.
thread_local! {
static APP: RefCell<Option<App>> = const { RefCell::new(None) };
}
pub fn install(app: App) {
APP.with(|a| *a.borrow_mut() = Some(app));
}
/// Single event entry point. Runs in two phases so that a modal dialog's nested
/// event loop never runs while the App borrow is held — the old code held
/// `borrow_mut()` across `show_modal()`, so any event fired inside the dialog
/// (a button, or the 1 s scan timer) re-entered here and panicked with a
/// double `BorrowMutError`, crashing the app on every dialog button.
pub fn dispatch(ev: WxEvent) {
let to_show = APP.with(|cell| {
// try_borrow_mut, not borrow_mut: if some nested wx event loop (an
// assert box, a system dialog) re-enters us while we already hold the
// borrow, drop this event instead of aborting the whole app. A dropped
// timer tick or click is harmless; a non-unwinding panic is fatal.
let Ok(mut app_ref) = cell.try_borrow_mut() else { return None };
app_ref.as_mut().and_then(|app| app.handle(ev))
});
if let Some(dlg) = to_show {
dlg.show_modal(); // nested loop, no App borrow held; blocks until EndModal
dlg.destroy(); // tear the dialog down (needs no App borrow, so none is taken)
}
}