Files
alkane-toolkit/crates/alkane-gui/src/ui.rs
T
noahandClaude Opus 4.8 eb08a9ef97 GUI: per-miner capabilities + live config write path (right-click actions)
Completes the right-click config menu (round-2 item 11): the menu now offers
real actions computed from the intersection of what every selected miner
supports, and applies them to the fleet over the network.

- Capability detection: to_row probes each miner's asic-rs supports_* methods
  (fault light, restart, pause, resume, power limit, tuning) at scan time and
  stores them in MinerRow.caps -- no extra network round-trip.
- Intersection: MinerCaps::intersect_all yields the actions common to the whole
  selection; the context menu offers only those (a mixed mining + idle selection
  shows just fault light + restart; an all-mining selection shows everything).
- Write path: scan::start_config_action runs on a background thread -- it
  re-discovers each selected miner with asic-rs scan_miner(ip), applies the
  setter, and reports per-IP results that drain into the status bar (running
  progress while applying, a pass/fail summary when done). Cancellable, and a
  new action cancels any in-flight one so two never overlap. In fake-scan mode
  it simulates success so the flow is exercisable offline.
- Actions: fault light on/off, pause, resume, restart apply immediately; set
  power limit and set tuning % open a small value-prompt dialog first. Factory
  reset, change password, and firmware upgrade are deliberately not exposed in a
  casual right-click.

Adds the `measurements` dependency (already in the lock, transitive via asic-rs)
for Power::from_watts.

Review fixes (one review pass):
- Restart / pause / resume now require a confirmation dialog (naming the count)
  so a misclick can't stop a producing fleet; fault light stays instant, and
  power/tuning are confirmed by their value entry.
- The action result is held on the status bar for a few ticks so a fleet
  action's outcome (including failures) isn't clobbered by the next timer tick.
- The action loop uses a current-thread tokio runtime (it applies to one miner
  at a time; a worker pool was wasted).
- The value prompt validates before closing: a bad value keeps the dialog and
  the captured selection so it can be corrected.
- The menu's "(N)" counts use the rows-backed selection, matching what is
  actually acted on.

Verified off-screen: capability intersection (mixed vs all-mining selections),
the value-prompt and confirmation nested modals (menu -> dialog) with no crash,
the end-to-end apply flow, 46 unit tests (incl. a caps-intersection test), and
the headless self-test.

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

1577 lines
66 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::{HashMap, HashSet};
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_PLAY: i32 = 104;
pub const ID_PAUSE: i32 = 105;
pub const ID_STOP: i32 = 106;
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_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;
// Right-click context-menu item ids.
const ID_CTX_OPEN: i32 = 720;
const ID_CTX_SELALL: i32 = 721;
const ID_CTX_CLEAR: i32 = 722;
// Config actions on the selection (capability intersection).
const ID_CTX_LIGHT_ON: i32 = 723;
const ID_CTX_LIGHT_OFF: i32 = 724;
const ID_CTX_PAUSE: i32 = 725;
const ID_CTX_RESUME: i32 = 726;
const ID_CTX_TUNING: i32 = 727;
const ID_CTX_POWER: i32 = 728;
const ID_CTX_RESTART: i32 = 729;
// Value-prompt dialog for power-limit / tuning-percent actions.
const ID_ACTION_OK: i32 = 740;
const ID_ACTION_CANCEL: i32 = 741;
// Confirmation dialog for disruptive actions (restart / pause / resume).
const ID_CONFIRM_OK: i32 = 742;
const ID_CONFIRM_CANCEL: i32 = 743;
// Ticks (~seconds) to keep an action's result on the status bar before the
// idle/countdown status takes over again.
const ACTION_RESULT_TICKS: u8 = 8;
// Filter dialog: the column-selector dropdown + the comparator dropdown.
const ID_FILTER_COL: i32 = 730;
const ID_FILTER_OP: i32 = 731;
const TIMER_SCAN: i32 = 1;
// Deferred-rebuild ids: run a rebuild from outside the triggering widget's own
// event (destroying a control mid-event is unsafe). See `wx_rs::call_after`.
const DEFER_TABLE: i32 = 1;
const DEFER_FILTER: i32 = 2;
/// Theme-aware palette for the KPI cards. Health is encoded in colour so a red
/// "Not hashing" or amber "Slow" draws the eye immediately. Colours derive from
/// the live system theme so the cards follow light/dark correctly (relying on
/// wxAppearance alone left the cards white under some GTK dark themes).
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 luminance(c: (u8, u8, u8)) -> f32 {
0.299 * c.0 as f32 + 0.587 * c.1 as f32 + 0.114 * c.2 as f32
}
fn nudge(c: (u8, u8, u8), d: i32) -> (u8, u8, u8) {
let f = |v: u8| (v as i32 + d).clamp(0, 255) as u8;
(f(c.0), f(c.1), f(c.2))
}
/// Format a filter's numeric bound without a trailing ".0" for whole numbers.
fn fmt_num(v: f64) -> String {
if v.is_finite() && v == v.trunc() && v.abs() < 1e15 {
format!("{}", v as i64)
} else {
format!("{v}")
}
}
/// Short mm:ss-ish duration for the rescan countdown ("4m 12s", "45s").
fn fmt_secs(s: u64) -> String {
if s >= 60 {
format!("{}m {:02}s", s / 60, s % 60)
} else {
format!("{s}s")
}
}
/// Which palette colour a KPI card's value uses, so the card can be re-themed
/// when the system switches light/dark while the app is open.
#[derive(Clone, Copy)]
enum ColorKind {
Neutral,
Green,
Amber,
Red,
Accent,
}
fn kind_color(pal: &Palette, k: ColorKind) -> (u8, u8, u8) {
match k {
ColorKind::Neutral => pal.neutral,
ColorKind::Green => pal.green,
ColorKind::Amber => pal.amber,
ColorKind::Red => pal.red,
ColorKind::Accent => pal.accent,
}
}
/// A miner row's text colour, by status: green = hashing, amber = slow, muted
/// grey = not hashing. This both conveys status and separates rows visually
/// (GTK's native zebra/alt-row support is unreliable and fights selection).
fn status_color(pal: &Palette, r: &MinerRow) -> (u8, u8, u8) {
if r.slow {
pal.amber
} else if r.is_mining {
pal.green
} else {
pal.label
}
}
fn palette() -> Palette {
let win = wx_rs::system_color(0); // window background
let text = wx_rs::system_color(1); // window text
let dark = luminance(win) < 128.0;
Palette {
// Cards read as slightly elevated vs the window: lighter in dark mode,
// pure white on a light-grey window.
card_bg: if dark { nudge(win, 14) } else { (255, 255, 255) },
label: if dark { (150, 156, 164) } else { (108, 114, 122) },
neutral: text,
green: if dark { (74, 222, 128) } else { (33, 140, 80) },
amber: if dark { (245, 190, 66) } else { (176, 120, 10) },
red: if dark { (245, 110, 100) } else { (198, 55, 45) },
accent: if dark { (108, 168, 250) } else { (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,
progress: Widget,
pub table: Option<Widget>,
table_parent: Widget,
root_sizer: Widget,
pub scan: Option<scan::ScanHandle>,
pub scanning: bool,
scan_total: usize,
target_ips: HashSet<String>,
// scan loop (play/pause/stop + auto-rescan)
playing: bool,
auto_secs: u64,
countdown: u64,
// selection (replaces the old checkbox column), tracked by IP so it
// survives table refreshes during a scan.
selected_ips: HashSet<String>,
// current theme palette + the KPI cards (panel, value, caption, colour role)
// so both can be repainted when the system light/dark theme changes.
pal: Palette,
kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)>,
// A context menu built on right-click, popped up outside the App borrow.
pending_popup: Option<(Widget, Widget)>,
// A running config action (fault light / restart / pause / power / tuning)
// applied to the selection, plus the value-prompt dialog for power/tuning.
action: Option<scan::ActionHandle>,
action_ips: Vec<String>,
action_prompt: Widget,
action_input: Widget,
action_is_power: bool,
action_total: usize,
action_done: usize,
// A confirmation dialog for disruptive actions, plus its pending target.
confirm_dialog: Widget,
pending_confirm: Option<(Vec<String>, scan::ConfigAction)>,
// The last action's result, kept on the status bar for a few ticks.
action_result: Option<String>,
action_result_ticks: u8,
ranges_dialog: Widget,
ranges_edit: Widget,
ranges_auto: Widget,
columns_dialog: Widget,
columns_list: Widget,
// Filter dialog (Excel-style, one column at a time via a dropdown).
filter_dialog: Widget,
filter_col_choice: Widget, // which column to filter
filter_controls: Widget, // panel rebuilt per column with its criterion controls
filter_op: Widget, // comparator dropdown
filter_values: Widget, // value checklist (text "is any of")
filter_values_data: Vec<String>, // the checklist's real values, by index
filter_text: Widget, // text input (text predicates)
filter_num_a: Widget, // numeric input a
filter_num_b: Widget, // numeric input b (Between)
filter_cols: Vec<Column>, // columns offered in the dropdown, in order
filter_cur: usize, // index into filter_cols currently edited
filter_active_op: i32, // the op index the visible controls were built for
filter_pending_op: Option<i32>, // op to rebuild for, deferred off the choice event
filter_working: HashMap<Column, ColFilter>, // edits, committed on Apply
}
pub fn build(frame: Widget) -> App {
let pal = palette();
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 mut kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)> = Vec::new();
let mut mk_card = |label: &str, kind: ColorKind| -> Widget {
let vc = kind_color(&pal, kind);
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(vc.0, vc.1, vc.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);
kpi_cards.push((card, value, lbl, kind));
value
};
let kpi_total = mk_card("Total", ColorKind::Neutral);
let kpi_hashing = mk_card("Hashing", ColorKind::Green);
let kpi_slow = mk_card("Slow", ColorKind::Amber);
let kpi_not = mk_card("Not hashing", ColorKind::Red);
let kpi_hashrate = mk_card("Hashrate", ColorKind::Accent);
let kpi_power = mk_card("Est. power", ColorKind::Neutral);
drop(mk_card);
root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6);
// Controls row: scan-ranges + play/pause/stop on the left; Filter / Columns
// 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_spacer(8);
// Play / pause / stop as coloured media icons (green / amber / red). Vivid
// fixed colours read well on both light and dark themes.
let play_btn = Widget::media_button(panel, ID_PLAY, 0, (56, 190, 108));
ctl.add(play_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
let pause_btn = Widget::media_button(panel, ID_PAUSE, 1, (240, 172, 40));
ctl.add(pause_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
let stop_btn = Widget::media_button(panel, ID_STOP, 2, (226, 72, 60));
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
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);
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...");
// Repaint custom-coloured widgets when the OS switches light/dark.
frame.bind_sys_colour();
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,
progress,
table: None,
table_parent,
root_sizer: root,
scan: Some(scan::start_scan(ranges.clone())),
scanning: true,
scan_total: 0,
target_ips: HashSet::new(),
playing: true,
auto_secs: scan::load_auto_secs(),
countdown: 0,
selected_ips: HashSet::new(),
pal,
kpi_cards,
pending_popup: None,
action: None,
action_ips: Vec::new(),
action_prompt: frame,
action_input: frame,
action_is_power: false,
action_total: 0,
action_done: 0,
confirm_dialog: frame,
pending_confirm: None,
action_result: None,
action_result_ticks: 0,
ranges_dialog: frame,
ranges_edit: frame,
ranges_auto: frame,
columns_dialog: frame,
columns_list: frame,
filter_dialog: frame,
filter_col_choice: frame,
filter_controls: frame,
filter_op: frame,
filter_values: frame,
filter_values_data: Vec::new(),
filter_text: frame,
filter_num_a: frame,
filter_num_b: frame,
filter_cols: Vec::new(),
filter_cur: 0,
filter_active_op: 0,
filter_pending_op: None,
filter_working: HashMap::new(),
};
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. IP is the fixed first column (not
// reorderable); the rest are reorderable. 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.
for c in self.view.display_columns() {
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).
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];
let cells: Vec<String> = cols.iter().map(|c| c.cell(r)).collect();
let refs: Vec<&str> = cells.iter().map(|s| s.as_str()).collect();
t.dvlc_append_row(&refs);
}
// Colour each row's text by status (also separates rows visually).
for (disp, &ri) in self.view_idx.iter().enumerate() {
t.dvlc_set_row_color(disp, Some(status_color(&self.pal, &self.rows[ri])));
}
// Re-apply the selection (a refresh clears the control's selection).
let sel: Vec<usize> = self
.view_idx
.iter()
.enumerate()
.filter(|(_, &ri)| self.selected_ips.contains(&self.rows[ri].ip))
.map(|(disp, _)| disp)
.collect();
if !sel.is_empty() {
t.dvlc_select_rows(&sel);
}
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"));
}
/// Re-apply the theme palette to the KPI cards and table rows after the OS
/// switches light/dark while the app is open.
fn repaint_theme(&mut self) {
self.pal = palette();
for (card, value, caption, kind) in &self.kpi_cards {
let vc = kind_color(&self.pal, *kind);
card.set_bg(self.pal.card_bg.0, self.pal.card_bg.1, self.pal.card_bg.2);
value.set_bg(self.pal.card_bg.0, self.pal.card_bg.1, self.pal.card_bg.2);
value.set_fg(vc.0, vc.1, vc.2);
caption.set_bg(self.pal.card_bg.0, self.pal.card_bg.1, self.pal.card_bg.2);
caption.set_fg(self.pal.label.0, self.pal.label.1, self.pal.label.2);
}
self.fill_rows(); // re-colour rows with the new palette
self.table_parent.layout();
}
/// Right-click: build a context menu of actions for the current selection.
/// The menu is popped up outside the App borrow (see `dispatch`), because
/// `popup_menu` runs a nested event loop that re-enters us.
fn show_context_menu(&mut self) {
let Some(t) = self.table else { return };
// Count and act on the same set: only selected IPs still backed by a row.
let n = self.selected_ip_list().len();
let menu = Widget::menu_new();
if n >= 1 {
let open = if n == 1 { "Open in browser".to_string() } else { format!("Open {n} miners in browser") };
menu.menu_append(ID_CTX_OPEN, &open);
// Config actions common to the whole selection (capability
// intersection): an action is offered only if every selected miner
// supports it.
let caps = MinerCaps::intersect_all(
self.rows
.iter()
.filter(|r| self.selected_ips.contains(&r.ip))
.map(|r| r.caps),
);
if !caps.is_empty() {
let sfx = if n == 1 { String::new() } else { format!(" ({n})") };
menu.menu_append_separator();
if caps.fault_light {
menu.menu_append(ID_CTX_LIGHT_ON, &format!("Fault light on{sfx}"));
menu.menu_append(ID_CTX_LIGHT_OFF, &format!("Fault light off{sfx}"));
}
if caps.pause {
menu.menu_append(ID_CTX_PAUSE, &format!("Pause mining{sfx}"));
}
if caps.resume {
menu.menu_append(ID_CTX_RESUME, &format!("Resume mining{sfx}"));
}
if caps.tuning {
menu.menu_append(ID_CTX_TUNING, &format!("Set tuning %...{sfx}"));
}
if caps.power_limit {
menu.menu_append(ID_CTX_POWER, &format!("Set power limit...{sfx}"));
}
if caps.restart {
menu.menu_append(ID_CTX_RESTART, &format!("Restart{sfx}"));
}
}
menu.menu_append_separator();
}
menu.menu_append(ID_CTX_SELALL, "Select all");
if n >= 1 {
menu.menu_append(ID_CTX_CLEAR, &format!("Clear selection ({n})"));
}
self.pending_popup = Some((t, menu));
}
fn take_pending_popup(&mut self) -> Option<(Widget, Widget)> {
self.pending_popup.take()
}
/// The IPs of the currently-selected miners.
fn selected_ip_list(&self) -> Vec<String> {
self.rows
.iter()
.filter(|r| !r.ip.is_empty() && self.selected_ips.contains(&r.ip))
.map(|r| r.ip.clone())
.collect()
}
/// Start a config action against `ips` on a background thread, cancelling any
/// action already in flight so two never run at once.
fn start_action(&mut self, ips: Vec<String>, action: scan::ConfigAction) {
if ips.is_empty() {
return;
}
if let Some(old) = self.action.take() {
old.stop();
}
let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len());
self.action = Some(scan::start_config_action(ips, action));
wx_rs::set_status_text(&msg);
}
/// A menu item was chosen. Direct actions start immediately; the value-input
/// actions (power limit / tuning %) return a prompt dialog to show modally.
fn on_menu_item(&mut self, id: i32) -> Option<Widget> {
match id {
ID_CTX_OPEN => {
for ip in self.selected_ip_list() {
wx_rs::launch_browser(&format!("http://{ip}"));
}
}
ID_CTX_SELALL => {
let all: Vec<usize> = (0..self.view_idx.len()).collect();
if let Some(t) = self.table {
t.dvlc_select_rows(&all);
}
self.on_selection_changed();
}
ID_CTX_CLEAR => {
self.selected_ips.clear();
for r in &mut self.rows {
r.selected = false;
}
if let Some(t) = self.table {
t.dvlc_select_rows(&[]);
}
}
// Fault light is harmless -> apply immediately.
ID_CTX_LIGHT_ON => self.start_action(self.selected_ip_list(), scan::ConfigAction::FaultLight(true)),
ID_CTX_LIGHT_OFF => self.start_action(self.selected_ip_list(), scan::ConfigAction::FaultLight(false)),
// Disruptive to running hardware -> confirm first.
ID_CTX_PAUSE => return Some(self.build_confirm_dialog(scan::ConfigAction::Pause)),
ID_CTX_RESUME => return Some(self.build_confirm_dialog(scan::ConfigAction::Resume)),
ID_CTX_RESTART => return Some(self.build_confirm_dialog(scan::ConfigAction::Restart)),
// Value entry is itself the confirmation.
ID_CTX_POWER => return Some(self.build_action_prompt(true)),
ID_CTX_TUNING => return Some(self.build_action_prompt(false)),
_ => {}
}
None
}
/// Confirm a disruptive action (restart / pause / resume) before applying it
/// to the selection, so a misclick can't stop a producing fleet.
fn build_confirm_dialog(&mut self, action: scan::ConfigAction) -> Widget {
let ips = self.selected_ip_list();
let n = ips.len();
let (verb, btn) = match &action {
scan::ConfigAction::Restart => ("Restart", "Restart"),
scan::ConfigAction::Pause => ("Pause mining on", "Pause"),
scan::ConfigAction::Resume => ("Resume mining on", "Resume"),
_ => ("Apply to", "Confirm"),
};
let msg = format!("{verb} {n} selected miner(s)? This affects running hardware.");
self.pending_confirm = Some((ips, action));
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Confirm action");
let root = Widget::box_sizer(true);
root.add(Widget::static_text(dlg, &msg), 0, sf::BORDER_ALL, 12);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, btn, ID_CONFIRM_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_CONFIRM_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(360, 120);
dlg.fit(dlg);
self.confirm_dialog = dlg;
dlg
}
/// A small modal to enter a power limit (watts) or tuning percent for the
/// selection. Built here, shown modally by `dispatch` outside the App borrow.
fn build_action_prompt(&mut self, is_power: bool) -> Widget {
self.action_ips = self.selected_ip_list();
self.action_is_power = is_power;
let n = self.action_ips.len();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, if is_power { "Set power limit" } else { "Set tuning percent" });
let root = Widget::box_sizer(true);
let lbl = if is_power {
format!("Power limit in watts for {n} miner(s):")
} else {
format!("Tuning percent (0-100) for {n} miner(s):")
};
root.add(Widget::static_text(dlg, &lbl), 0, sf::BORDER_ALL, 8);
let input = Widget::text_ctrl(dlg, false);
input.set_min_size(200, -1);
root.add(input, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Apply", ID_ACTION_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_ACTION_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(320, 140);
dlg.fit(dlg);
self.action_prompt = dlg;
self.action_input = input;
dlg
}
/// Apply the value-prompt: parse the input, and only on a valid value close
/// the dialog and start the action. A bad value keeps the dialog (and the
/// captured selection) so the operator can correct it.
fn apply_action_prompt(&mut self) {
let val = self.action_input.get_value();
let action = if self.action_is_power {
match val.trim().parse::<f64>() {
Ok(w) if w > 0.0 && w.is_finite() => Some(scan::ConfigAction::PowerLimit(w)),
_ => None,
}
} else {
match val.trim().parse::<u8>() {
Ok(p) if p <= 100 => Some(scan::ConfigAction::TuningPercent(p)),
_ => None,
}
};
match action {
Some(a) => {
let ips = std::mem::take(&mut self.action_ips);
self.action_prompt.close(1);
self.start_action(ips, a);
}
None => {
let hint = if self.action_is_power {
"enter a positive number of watts"
} else {
"enter a percent from 0 to 100"
};
wx_rs::set_status_text(&format!("invalid value - {hint}"));
}
}
}
/// Drain a running config action's results into the status bar (per-miner
/// progress while running, a summary when done).
fn drain_action(&mut self) {
let Some(h) = &self.action else { return };
let mut status: Option<String> = None;
let mut finished = false;
loop {
match h.rx.try_recv() {
Ok(scan::ActionMsg::Started { total }) => {
self.action_total = total;
self.action_done = 0;
status = Some(format!("applying to 0/{total} miner(s)..."));
}
Ok(scan::ActionMsg::Result { ip, ok, detail }) => {
self.action_done += 1;
let (d, t) = (self.action_done, self.action_total);
status = Some(if ok {
format!("applying... {d}/{t} ({ip} ok)")
} else {
format!("applying... {d}/{t} ({ip}: {detail})")
});
}
Ok(scan::ActionMsg::Done { ok, total }) => {
status = Some(if ok == total {
format!("applied to {ok}/{total} miner(s)")
} else {
format!("applied to {ok}/{total} miner(s), {} failed", total - ok)
});
finished = true;
break;
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
status = Some("action ended".into());
finished = true;
break;
}
}
}
if finished {
self.action = None;
// Keep the summary on the status bar for a few ticks so a fleet
// action's outcome (incl. failures) isn't clobbered by the next tick.
self.action_result = status.clone();
self.action_result_ticks = ACTION_RESULT_TICKS;
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
}
}
pub fn drain_scan(&mut self) {
let Some(handle) = &self.scan else { return };
let mut changed = false;
loop {
match handle.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;
// Drop selections that are no longer in range.
let keep = std::mem::take(&mut self.selected_ips);
self.selected_ips = keep.into_iter().filter(|ip| self.target_ips.contains(ip)).collect();
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, ip }) => {
self.scan_total = total;
self.progress.gauge_set_value(done.min(total) as i32);
let where_ = if ip.is_empty() { String::new() } else { format!(" - scanning {ip}") };
wx_rs::set_status_text(&format!(
"{done}/{total}{where_} ({} 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();
// Arm the next automatic scan (if the loop is running).
self.countdown = if self.playing { self.auto_secs } else { 0 };
}
Ok(ScanMsg::Failed(e)) => {
self.scanning = false;
self.progress.show(false);
self.table_parent.layout();
wx_rs::set_status_text(&format!("scan failed: {e}"));
self.countdown = if self.playing { self.auto_secs } else { 0 };
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
// The scan thread ended. Normally this follows Done/Failed
// (handled above); if it ended without either (panic/hang
// recovery), don't leave the loop stuck "scanning".
if self.scanning {
self.scanning = false;
self.progress.show(false);
self.table_parent.layout();
self.countdown = if self.playing { self.auto_secs } else { 0 };
}
self.scan = None;
break;
}
}
}
if changed {
self.fill_rows();
}
}
/// Called every second by the scan timer: drain scan messages, then run the
/// scan-loop scheduler (countdown to the next automatic rescan, or idle).
fn tick(&mut self) {
self.drain_scan();
self.drain_action();
if self.scanning {
return; // status already shows scan progress
}
if self.action.is_some() {
return; // a config action is in flight; keep its status
}
if self.action_result_ticks > 0 {
// Hold the last action's result on the status bar briefly.
self.action_result_ticks -= 1;
if let Some(m) = &self.action_result {
wx_rs::set_status_text(m);
}
return;
}
if self.playing && self.auto_secs > 0 {
if self.countdown > 1 {
self.countdown -= 1;
wx_rs::set_status_text(&format!(
"{} miners - next scan in {}",
self.rows.len(),
fmt_secs(self.countdown)
));
} else {
self.start_new_scan();
}
} else {
wx_rs::set_status_text(&format!(
"{} miners - {}",
self.rows.len(),
if self.playing { "auto-rescan off" } else { "paused" }
));
}
}
/// Cancel any in-flight scan, then start a fresh one over `lines`. Signalling
/// the old scan to stop before replacing it prevents two scan threads (and
/// two tokio runtimes) probing the network at once.
fn begin_scan(&mut self, lines: Vec<String>) {
if let Some(old) = self.scan.take() {
old.stop();
}
self.scan = Some(scan::start_scan(lines));
self.scanning = true;
self.countdown = 0;
}
/// Start a fresh scan of the saved ranges.
fn start_new_scan(&mut self) {
self.begin_scan(scan::load_ranges());
wx_rs::set_status_text("scanning...");
}
/// The table's selection changed (ctrl/shift-click). Mirror it into the
/// model, tracked by IP so it survives table refreshes during a scan.
fn on_selection_changed(&mut self) {
let Some(t) = self.table else { return };
let rows_sel = t.dvlc_get_selections();
self.selected_ips.clear();
for disp in rows_sel {
if let Some(&ri) = self.view_idx.get(disp) {
self.selected_ips.insert(self.rows[ri].ip.clone());
}
}
for r in &mut self.rows {
r.selected = self.selected_ips.contains(&r.ip);
}
}
/// 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 in display order; map the clicked creation index
// back to a model column through display_columns() (hidden columns don't
// shift the mapping). Every column, including IP at index 0, is sortable.
let cols = self.view.display_columns();
if creation_idx >= cols.len() {
return;
}
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() {
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);
// Rebuild so the control's column creation order matches the new display
// order again (fill_rows/header_click/update_headers assume creation
// order == display_columns()). Deferred: rebuild_table destroys the very
// wxDataViewCtrl now delivering this reorder event, which is unsafe to do
// from inside the event -- run it after the event unwinds.
wx_rs::call_after(DEFER_TABLE);
}
/// 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);
// Auto-rescan interval (seconds; 0 = off).
let auto_row = Widget::box_sizer(false);
let auto_lbl = Widget::static_text(dlg, "Rescan (s):");
auto_row.add(auto_lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let auto_edit = Widget::text_ctrl(dlg, false);
auto_edit.set_value(&self.auto_secs.to_string());
auto_row.add(auto_edit, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(auto_row, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 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.add_sizer(btns, 0, sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
self.ranges_dialog = dlg;
self.ranges_edit = edit;
self.ranges_auto = auto_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
}
// Save the auto-rescan interval too.
if let Ok(secs) = self.ranges_auto.get_value().trim().parse::<u64>() {
self.auto_secs = secs;
let _ = scan::save_auto_secs(secs);
}
let _ = scan::save_ranges(&lines);
self.begin_scan(lines);
wx_rs::set_status_text("scanning...");
self.ranges_dialog.close(1);
}
/// The columns available to show/hide: every metric except the fixed IP
/// column, in registry order (the rearrange-list's item index space).
fn selectable_columns() -> Vec<Column> {
ALL_COLUMNS.iter().copied().filter(|c| *c != Column::Ip).collect()
}
/// Build (but do not show) the columns chooser: a rearrangeable checklist of
/// every scannable metric. Check to show; drag or use the up/down arrows to
/// reorder. IP is always the first column and is not listed here.
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,
"Check to show a metric; drag or use the arrows to reorder (IP is always first).",
);
root.add(hint, 0, sf::BORDER_ALL, 6);
// Base list is registry order; the wx order array lists items in the
// current arranged order, encoding checked = visible (a negative value
// ~idx means item idx unchecked).
let base = Self::selectable_columns();
let titles: Vec<&str> = base.iter().map(|c| c.title()).collect();
let mut order: Vec<i32> = Vec::with_capacity(base.len());
for c in self.view.order.iter().filter(|c| **c != Column::Ip) {
if let Some(idx) = base.iter().position(|b| b == c) {
let idx = idx as i32;
order.push(if self.view.visible.contains(c) { idx } else { !idx });
}
}
let list = Widget::rearrange_list(dlg, &order, &titles);
root.add(list, 1, sf::EXPAND | sf::BORDER_ALL, 6);
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);
dlg.fit(dlg);
self.columns_dialog = dlg;
self.columns_list = list;
dlg
}
fn apply_columns(&mut self) {
let base = Self::selectable_columns();
let order = self.columns_list.rearrange_get_order();
let mut new_order: Vec<Column> = vec![Column::Ip];
let mut visible: HashSet<Column> = HashSet::from([Column::Ip]);
for entry in order {
let (idx, checked) = if entry < 0 { ((!entry) as usize, false) } else { (entry as usize, true) };
if let Some(&c) = base.get(idx) {
new_order.push(c);
if checked {
visible.insert(c);
}
}
}
// Only accept a full permutation (no dropped/duplicated columns); apply
// order + visibility together so they never desync.
if new_order.len() == self.view.order.len() {
self.view.order = new_order;
self.view.visible = visible;
}
// Drop the sort if its column was hidden (IP is always shown).
if let Some((c, _)) = self.view.sort {
if c != Column::Ip && !self.view.visible.contains(&c) {
self.view.sort = None;
}
}
self.columns_dialog.close(1);
self.rebuild_table();
}
/// Operator labels offered for a column, by type.
fn filter_ops(col: Column) -> &'static [&'static str] {
if col.is_numeric() {
&["between", "=", "!=", ">", ">=", "<", "<="]
} else {
&["is any of", "contains", "does not contain", "begins with", "ends with", "equals"]
}
}
/// The operator index that matches an existing filter (for prefilling).
fn filter_op_index(existing: Option<&ColFilter>) -> i32 {
match existing {
Some(ColFilter::Values(_)) => 0,
Some(ColFilter::Text { op, .. }) => match op {
TextOp::Contains => 1,
TextOp::NotContains => 2,
TextOp::BeginsWith => 3,
TextOp::EndsWith => 4,
TextOp::Equals => 5,
},
Some(ColFilter::Num { op, .. }) => match op {
NumOp::Between => 0,
NumOp::Eq => 1,
NumOp::Ne => 2,
NumOp::Gt => 3,
NumOp::Ge => 4,
NumOp::Lt => 5,
NumOp::Le => 6,
},
None => 0,
}
}
/// Build (but do not show) the filter dialog: an Excel-style, one-column-at-
/// a-time filter. A dropdown at the top-left picks the column; the controls
/// below adapt to its type -- numeric columns get a comparator
/// (between / = / != / > / >= / < / <=) with one or two number inputs; text
/// columns get a value checklist ("is any of") or a text predicate (contains
/// / does not contain / begins with / ends with / equals). Filters AND across
/// columns; edits are held in a working copy and committed on Apply.
fn build_filter_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Filter");
let root = Widget::box_sizer(true);
self.filter_cols = self.view.display_columns();
self.filter_working = self.view.filters.clone();
self.filter_cur = 0;
let top = Widget::box_sizer(false);
top.add(Widget::static_text(dlg, "Column:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
let col_choice = Widget::choice(dlg, ID_FILTER_COL);
for c in &self.filter_cols {
col_choice.choice_append(c.title());
}
col_choice.choice_set_selection(0);
top.add(col_choice, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
root.add_sizer(top, 0, sf::EXPAND | sf::BORDER_ALL, 6);
self.filter_col_choice = col_choice;
// The criterion controls live in this panel, rebuilt on column/op change.
let controls = Widget::panel(dlg);
controls.set_min_size(380, 250);
root.add(controls, 1, sf::EXPAND | sf::BORDER_ALL, 6);
self.filter_controls = controls;
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
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::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(460, 400);
dlg.fit(dlg);
self.filter_dialog = dlg;
self.build_filter_controls(None);
dlg
}
/// Rebuild the criterion controls for the current column (`filter_cur`). `op`
/// picks the operator; `None` derives it from the working filter (or 0).
fn build_filter_controls(&mut self, op: Option<i32>) {
let col = self.filter_cols[self.filter_cur];
let panel = self.filter_controls;
panel.destroy_children();
let ops = Self::filter_ops(col);
let existing = self.filter_working.get(&col).cloned();
let op_idx = op
.unwrap_or_else(|| Self::filter_op_index(existing.as_ref()))
.clamp(0, ops.len() as i32 - 1);
self.filter_active_op = op_idx;
let cs = Widget::box_sizer(true);
let oprow = Widget::box_sizer(false);
oprow.add(Widget::static_text(panel, "Keep rows where value is"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
let op_choice = Widget::choice(panel, ID_FILTER_OP);
for o in ops {
op_choice.choice_append(o);
}
op_choice.choice_set_selection(op_idx);
oprow.add(op_choice, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
cs.add_sizer(oprow, 0, sf::EXPAND | sf::BORDER_ALL, 4);
self.filter_op = op_choice;
// Unused input handles point at the panel and are never read (commit
// dispatches on column type + active op).
self.filter_values = panel;
self.filter_values_data.clear();
self.filter_text = panel;
self.filter_num_a = panel;
self.filter_num_b = panel;
if col.is_numeric() {
let row = Widget::box_sizer(false);
let a = Widget::text_ctrl(panel, false);
a.set_min_size(120, -1);
row.add(a, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
self.filter_num_a = a;
if op_idx == 0 {
row.add(Widget::static_text(panel, "and"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
let b = Widget::text_ctrl(panel, false);
b.set_min_size(120, -1);
row.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
self.filter_num_b = b;
}
cs.add_sizer(row, 0, sf::EXPAND | sf::BORDER_ALL, 4);
if let Some(ColFilter::Num { a: wa, b: wb, .. }) = &existing {
self.filter_num_a.set_value(&fmt_num(*wa));
if op_idx == 0 {
self.filter_num_b.set_value(&fmt_num(*wb));
}
}
} else if op_idx == 0 {
let head = Widget::box_sizer(false);
head.add(Widget::button(panel, "All", ID_FILTER_ALL_BASE), 0, sf::BORDER_ALL, 2);
head.add(Widget::button(panel, "None", ID_FILTER_NONE_BASE), 0, sf::BORDER_ALL, 2);
cs.add_sizer(head, 0, sf::BORDER_ALL, 2);
let clb = Widget::check_list_box(panel);
clb.set_min_size(340, 180);
let mut values: Vec<String> = self.rows.iter().map(|r| col.cell(r)).collect();
values.sort();
values.dedup();
let checked_set = match &existing {
Some(ColFilter::Values(set)) => Some(set.clone()),
_ => None,
};
for v in &values {
let shown = if v.is_empty() { "(blank)" } else { v.as_str() };
clb.clb_append(shown);
let checked = match &checked_set {
Some(s) => s.contains(v),
None => true,
};
clb.clb_set_checked(clb.clb_count() - 1, checked);
}
cs.add(clb, 1, sf::EXPAND | sf::BORDER_ALL, 4);
self.filter_values = clb;
self.filter_values_data = values; // real values, indexed like the checklist
} else {
let inp = Widget::text_ctrl(panel, false);
inp.set_min_size(340, -1);
if let Some(ColFilter::Text { needle, .. }) = &existing {
inp.set_value(needle);
}
cs.add(inp, 0, sf::EXPAND | sf::BORDER_ALL, 4);
self.filter_text = inp;
}
cs.set_sizer_on(panel);
panel.layout();
self.filter_dialog.layout();
}
/// Read the visible criterion controls into the working filter for the
/// current column (removing it when the criterion is empty / matches all).
fn commit_filter_current(&mut self) {
if self.filter_cols.is_empty() {
return;
}
let col = self.filter_cols[self.filter_cur];
let op_idx = self.filter_active_op;
let f: Option<ColFilter> = if col.is_numeric() {
match self.filter_num_a.get_value().trim().parse::<f64>() {
Err(_) => None,
Ok(a) => {
let op = match op_idx {
0 => NumOp::Between,
1 => NumOp::Eq,
2 => NumOp::Ne,
3 => NumOp::Gt,
4 => NumOp::Ge,
5 => NumOp::Lt,
_ => NumOp::Le,
};
let b = if op_idx == 0 {
self.filter_num_b.get_value().trim().parse::<f64>().unwrap_or(a)
} else {
a
};
Some(ColFilter::Num { op, a, b })
}
}
} else if op_idx == 0 {
let clb = self.filter_values;
let count = clb.clb_count();
let mut allowed = HashSet::new();
for i in 0..count {
if clb.clb_checked(i) {
// Map back to the real value by index, so a genuine cell whose
// text is literally "(blank)" is not confused with an empty one.
allowed.insert(self.filter_values_data.get(i).cloned().unwrap_or_default());
}
}
if allowed.is_empty() || allowed.len() == count {
None // all (or none) checked == no filter
} else {
Some(ColFilter::Values(allowed))
}
} else {
let needle = self.filter_text.get_value().trim().to_string();
if needle.is_empty() {
None
} else {
let op = match op_idx {
1 => TextOp::Contains,
2 => TextOp::NotContains,
3 => TextOp::BeginsWith,
4 => TextOp::EndsWith,
_ => TextOp::Equals,
};
Some(ColFilter::Text { op, needle })
}
};
match f {
Some(f) => {
self.filter_working.insert(col, f);
}
None => {
self.filter_working.remove(&col);
}
}
}
/// Check or uncheck every value in the current column's checklist.
fn filter_check_all(&self, checked: bool) {
let clb = self.filter_values;
for i in 0..clb.clb_count() {
clb.clb_set_checked(i, checked);
}
}
fn on_choice_changed(&mut self, id: i32, sel: i32) {
match id {
ID_FILTER_COL => {
self.commit_filter_current();
self.filter_cur = (sel.max(0) as usize).min(self.filter_cols.len().saturating_sub(1));
self.build_filter_controls(None);
}
ID_FILTER_OP => {
// The op dropdown lives inside the controls panel that
// build_filter_controls destroys, so rebuilding here would delete
// this very wxChoice mid-event. Defer it off the choice event.
self.commit_filter_current();
self.filter_pending_op = Some(sel);
wx_rs::call_after(DEFER_FILTER);
}
_ => {}
}
}
/// A deferred rebuild requested via `wx_rs::call_after`, run after the
/// triggering widget's own event has unwound.
fn on_deferred(&mut self, id: i32) {
match id {
DEFER_TABLE => self.rebuild_table(),
DEFER_FILTER => {
let op = self.filter_pending_op.take();
self.build_filter_controls(op);
}
_ => {}
}
}
fn apply_filter(&mut self) {
self.commit_filter_current();
self.view.filters = self.filter_working.clone();
self.filter_dialog.close(1);
self.fill_rows();
}
fn reset_filters(&mut self) {
self.filter_working.clear();
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_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_ACTION_OK => self.apply_action_prompt(),
ID_ACTION_CANCEL => self.action_prompt.close(0),
ID_CONFIRM_OK => {
if let Some((ips, action)) = self.pending_confirm.take() {
self.confirm_dialog.close(1);
self.start_action(ips, action);
}
}
ID_CONFIRM_CANCEL => {
self.pending_confirm = None;
self.confirm_dialog.close(0);
}
ID_PLAY => {
// Resume/start the scan loop: scan now (unless one is
// already running) + auto-rescan on.
self.playing = true;
if !self.scanning {
self.start_new_scan();
}
}
ID_PAUSE => {
// Stop the auto-rescan loop (a scan in flight finishes).
self.playing = false;
wx_rs::set_status_text(&format!("{} miners - paused", self.rows.len()));
}
ID_STOP => {
// Halt the loop and cancel any in-flight scan (dropping
// the receiver alone would leave the thread probing).
self.playing = false;
self.countdown = 0;
self.scanning = false;
if let Some(old) = self.scan.take() {
old.stop();
}
self.progress.show(false);
self.table_parent.layout();
wx_rs::set_status_text(&format!("{} miners - stopped", self.rows.len()));
}
ID_FILTER_ALL_BASE => self.filter_check_all(true),
ID_FILTER_NONE_BASE => self.filter_check_all(false),
_ => {}
}
}
WxEventKind::DvlcHeaderClick => self.header_click(ev.p1 as usize),
WxEventKind::DvlcSelectionChanged => self.on_selection_changed(),
WxEventKind::DvlcActivated => self.activate_row(ev.p1 as usize),
WxEventKind::DvlcReordered => self.column_reordered(),
WxEventKind::DvlcContextMenu => self.show_context_menu(),
WxEventKind::MenuItem => return self.on_menu_item(ev.p1 as i32),
WxEventKind::ChoiceChanged => self.on_choice_changed(ev.p1 as i32, ev.p2 as i32),
WxEventKind::SysColour => self.repaint_theme(),
WxEventKind::Deferred => self.on_deferred(ev.p1 as i32),
WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => self.tick(),
_ => {}
}
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() {
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 column", ip_col == Some(0),
format!("ip col index = {ip_col:?}"));
// default view is IP-ascending
let ips: Vec<String> = self.view_idx.iter().map(|&ri| self.rows[ri].ip.clone()).collect();
let mut sorted = ips.clone();
sorted.sort();
check("default sort is IP ascending", ips == sorted, String::new());
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)
}
// Phase 3: a pending right-click context menu. popup_menu runs its own nested
// loop and its MenuItem event re-enters dispatch, so it must run with no App
// borrow held (like a modal). The menu is deleted by popup_menu itself.
let popup = APP.with(|cell| {
let Ok(mut app_ref) = cell.try_borrow_mut() else { return None };
app_ref.as_mut().and_then(|app| app.take_pending_popup())
});
if let Some((on, menu)) = popup {
on.popup_menu(menu);
}
}