Files
alkane-toolkit/crates/alkane-gui/src/ui.rs
T
noahandClaude Opus 4.8 1fbadedc47
build-test-release / release (push) Successful in 10m37s
GUI round 11 (#4): drag-reorder + multi-select columns dialog (no up/down buttons)
Replaces the columns dialog's wxRearrangeCtrl (checkboxes + up/down buttons)
with a wxListCtrl-based list (new wxbr_reorder_list / Widget::reorder_list):
- No up/down buttons; rows are reordered by dragging.
- Native multi-select: Shift/Ctrl-click and rubber-band drag.
- Keeps per-row checkboxes for show/hide; same [idx | !idx] order encoding, so
  apply_columns is unchanged.

Drag-reorder is implemented by recording the selected rows' base indices on
wxEVT_LIST_BEGIN_DRAG and moving that group to the row under the cursor on the
following mouse-up (no real DnD loop is started, so the mouse-up still arrives).

Verified: the dialog opens without crashing and renders the checkable, button-
free list (headless click test). The drag and shift/ctrl multi-select
interactions are not headlessly simulatable and need interactive confirmation.

Bridge + Rust mirrored into patches 0002 (widgets.rs) and 0003
(widgets_bridge.cpp) per ADR 0003.

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

3182 lines
141 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::credentials;
use crate::model::*;
use crate::scan::{self, ScanMsg};
use asic_rs::core::data::firmware::FirmwareImage;
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;
pub const ID_SCAN_CREDS: i32 = 107;
pub const ID_PRESETS: i32 = 108;
// Presets dialog.
const ID_PRESET_LOAD: i32 = 770;
const ID_PRESET_SAVE: i32 = 771;
const ID_PRESET_DELETE: i32 = 772;
const ID_PRESET_CLOSE: i32 = 773;
const ID_PRESET_CHOICE: i32 = 774;
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;
// KPI header quick-filter cards (Hashing / Slow / Not hashing / Paused):
// clicking one filters the table to that status, clicking again clears it.
const ID_KPI_HASHING: i32 = 150;
const ID_KPI_SLOW: i32 = 151;
const ID_KPI_NOT: i32 = 152;
const ID_KPI_PAUSED: i32 = 153;
// Click the hashrate KPI card to cycle through per-algorithm hashrate totals.
const ID_KPI_HASHRATE: i32 = 154;
// Right-click context-menu item ids.
const ID_CTX_OPEN: i32 = 720;
const ID_CTX_REFRESH: i32 = 732;
const ID_CTX_FLASH: i32 = 733;
// 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;
const ID_CTX_PIC_PROBE: i32 = 730;
const ID_CTX_ACCESS_PROBE: i32 = 731;
// SSH PIC-probe credentials dialog.
const ID_PICSSH_OK: i32 = 780;
const ID_PICSSH_CANCEL: i32 = 781;
// 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;
// Strong typed-confirmation dialog for flashing firmware.
const ID_FLASH_OK: i32 = 744;
const ID_FLASH_CANCEL: i32 = 745;
// Scan-credentials dialog.
const ID_CREDS_SAVE: i32 = 746;
const ID_CREDS_CLEAR: i32 = 747;
const ID_CREDS_CANCEL: i32 = 748;
// Column-header right-click menu (Excel-style).
const ID_HDR_SORT_ASC: i32 = 760;
const ID_HDR_SORT_DESC: i32 = 761;
const ID_HDR_HIDE: i32 = 762;
const ID_HDR_AUTOSIZE: i32 = 763;
const ID_HDR_COLUMNS: i32 = 764;
// Relative-hashrate (actual/expected) sort, offered on the Hashrate header only
// (round 11 #16).
const ID_HDR_SORT_REL_ASC: i32 = 765;
const ID_HDR_SORT_REL_DESC: i32 = 766;
// 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),
/// Odd-row (zebra) background: a subtle tint of the window colour.
zebra: (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
}
/// Human-facing algorithm name for the hashrate KPI label. asic-rs renders the
/// SHA-256 variant as "SHA256"; everything else already reads well as-is.
fn pretty_algo(algo: &str) -> String {
match algo {
"SHA256" => "SHA-256".to_string(),
other => other.to_string(),
}
}
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))
}
/// Blend `base` toward `target` by fraction `f` (0.0 = base, 1.0 = target).
fn tint_toward(base: (u8, u8, u8), target: (u8, u8, u8), f: f64) -> (u8, u8, u8) {
let lerp = |a: u8, b: u8| (a as f64 + (b as f64 - a as f64) * f).round() as u8;
(lerp(base.0, target.0), lerp(base.1, target.1), lerp(base.2, target.2))
}
/// Colour for a combined actual/expected ratio (Hashrate/Hashboards/
/// TotalChips): full red at 50% (or below), amber at 75%, green at 100%+,
/// interpolated linearly -- calibrated so a miner running at half its expected
/// output reads as clearly bad, and 100% reads green.
fn ratio_color(pal: &Palette, ratio: f64) -> (u8, u8, u8) {
let t = ((ratio - 0.5) / 0.5).clamp(0.0, 1.0);
if t <= 0.5 {
tint_toward(pal.red, pal.amber, t / 0.5)
} else {
tint_toward(pal.amber, pal.green, (t - 0.5) / 0.5)
}
}
/// Colour for a firmware family (round-10 #3). Stock -- and any family we don't
/// recognise -- returns None so the Firmware cell keeps the theme default text
/// colour (which tracks light/dark and focus). The rest get a distinctive,
/// fixed hue chosen to read on both light and dark backgrounds.
fn firmware_color(family: &str) -> Option<(u8, u8, u8)> {
Some(match family.trim().to_ascii_lowercase().as_str() {
"braiins" => (150, 90, 210), // purple
"luxos" | "lux" => (185, 150, 20), // yellow/gold
"vnish" => (40, 165, 70), // green
"bixbit" => (225, 105, 175), // pink
"epic" => (70, 160, 225), // light blue
"hive" | "hiveos" => (235, 140, 35), // orange
"alkane" => (80, 100, 205), // navy
_ => return None, // Stock / unknown -> theme default
})
}
/// Colour for a chip-temperature reading: cool blue at/below 40 C fading to hot
/// red at/above 90 C, so a hot miner reads red at a glance.
fn temp_color(pal: &Palette, temp_c: f64) -> (u8, u8, u8) {
tint_toward(pal.accent, pal.red, ((temp_c - 40.0) / 50.0).clamp(0.0, 1.0))
}
/// Colour for one cooling-fan RPM: muted grey (stopped/unknown) fading to
/// accent blue as the RPM approaches 6000 (comfortably above a healthy fan's
/// typical ceiling, so a spinning fan reads as a clear, saturated blue).
fn fan_color(pal: &Palette, rpm: f64) -> (u8, u8, u8) {
tint_toward(pal.label, pal.accent, (rpm / 6000.0).clamp(0.0, 1.0))
}
/// Build the segment-encoded cell for a combined actual/expected column
/// (Hashrate/Hashboards/TotalChips) from its already-formatted parts: the
/// actual half is coloured by `ratio` when both halves are known, the separator
/// `sep` and the expected half stay the default text colour, and an unknown
/// actual shows "-". Round-trips (via decode_segments_plain) to the same plain
/// text the model's combined cell produces.
fn encode_combined_cell(
pal: &Palette,
actual: Option<String>,
expected: Option<String>,
sep: &str,
ratio: Option<f64>,
) -> String {
match (actual, expected) {
(None, None) => encode_segments(&[(None, String::new())]),
(Some(a), None) => encode_segments(&[(None, a)]),
(a, Some(e)) => encode_segments(&[
(ratio.map(|r| ratio_color(pal, r)), a.unwrap_or_else(|| "-".to_string())),
(None, sep.to_string()),
(None, e),
]),
}
}
/// Segment-encoded Chip-temp cell: the reading coloured on the blue-to-red
/// temperature scale (blank cell stays blank).
fn encode_temp_cell(pal: &Palette, plain: &str, temp_c: f64) -> String {
if plain.is_empty() {
encode_segments(&[(None, String::new())])
} else {
encode_segments(&[(Some(temp_color(pal, temp_c)), plain.to_string())])
}
}
/// Segment-encoded per-hashboard Chip-temp cell ("77 / 64 / 74"): each board's
/// temperature coloured on the blue-to-red scale, the " / " separators in the
/// default text colour. Falls back to the single average when there are no
/// per-board readings.
fn encode_board_temps_cell(pal: &Palette, temps: &[f64], avg: f64) -> String {
if temps.is_empty() {
let plain = if avg > 0.0 { format!("{avg:.0}") } else { String::new() };
return encode_temp_cell(pal, &plain, avg);
}
let mut segs: Vec<(Option<(u8, u8, u8)>, String)> = Vec::with_capacity(temps.len() * 2 - 1);
for (i, &t) in temps.iter().enumerate() {
if i > 0 {
segs.push((None, " / ".to_string()));
}
segs.push((Some(temp_color(pal, t)), format!("{t:.0}")));
}
encode_segments(&segs)
}
/// Segment-encoded single-colour cell (Access/Errors): `plain` in `color`, or
/// the default text colour when `color` is None.
fn encode_flag_cell(plain: &str, color: Option<(u8, u8, u8)>) -> String {
encode_segments(&[(color, plain.to_string())])
}
/// Shape-sentinel strings the SegmentRenderer draws as small vector icons rather
/// than text (round 11 #10/#13). These byte values MUST match the SHAPE_* set in
/// widgets_bridge.cpp. They are control characters, never emoji/pictographs.
const SHAPE_DOT: &str = "\u{0007}";
const SHAPE_LOCK: &str = "\u{0002}";
const SHAPE_UNLOCK: &str = "\u{0003}";
/// Boards column: one status dot per hashboard (round 11 #10). Board 1 is the
/// rightmost dot, so boards render high-position-first (left to right). green =
/// present and hashing, red = present but idle/faulty, grey = not detected.
fn encode_board_dots(pal: &Palette, status: &[crate::model::BoardHealth]) -> String {
use crate::model::BoardHealth;
if status.is_empty() {
return encode_segments(&[(None, String::new())]);
}
let segs: Vec<(Option<(u8, u8, u8)>, String)> = status
.iter()
.rev()
.map(|h| {
let color = match h {
BoardHealth::Ok => pal.green,
BoardHealth::Fault => pal.red,
BoardHealth::Missing => pal.label,
};
(Some(color), SHAPE_DOT.to_string())
})
.collect();
encode_segments(&segs)
}
/// Access column: a green open padlock (writable) or red closed padlock
/// (view-only); blank when the lock state is unknown (round 11 #13).
fn encode_access_icon(pal: &Palette, write_locked: Option<bool>) -> String {
match write_locked {
Some(true) => encode_segments(&[(Some(pal.red), SHAPE_LOCK.to_string())]),
Some(false) => encode_segments(&[(Some(pal.green), SHAPE_UNLOCK.to_string())]),
None => encode_segments(&[(None, String::new())]),
}
}
/// Light column: a yellow dot while the miner's locate light is flashing, else
/// blank (round 11 #10).
fn encode_light_dot(pal: &Palette, flashing: Option<bool>) -> String {
match flashing {
Some(true) => encode_segments(&[(Some(pal.amber), SHAPE_DOT.to_string())]),
_ => encode_segments(&[(None, String::new())]),
}
}
/// Build the segment-encoded cell text for the Cooling column: each fan's RPM
/// gets its own grey-to-blue colour by speed, and the "/" separators between
/// them stay in the default text colour.
fn encode_cooling_cell(pal: &Palette, fans: &[f64]) -> String {
if fans.is_empty() {
return encode_segments(&[(None, String::new())]);
}
let mut segs: Vec<(Option<(u8, u8, u8)>, String)> = Vec::with_capacity(fans.len() * 2 - 1);
for (i, &rpm) in fans.iter().enumerate() {
if i > 0 {
segs.push((None, "/".to_string()));
}
segs.push((Some(fan_color(pal, rpm)), format_fan_rpm(rpm)));
}
encode_segments(&segs)
}
/// 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,
Blue,
}
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,
ColorKind::Blue => pal.accent,
}
}
/// The palette colour for one of `MinerRow::status()`'s values. Shared by row
/// text colouring and the KPI quick-filter card highlight, so both agree on
/// what each status "looks like".
fn status_kind_color(pal: &Palette, status: &str) -> (u8, u8, u8) {
match status {
"not hashing" => pal.red,
"paused" => pal.accent,
"slow" => pal.amber,
"hashing" => pal.green,
_ => 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) },
// Subtle zebra tint of the window: slightly lighter in dark mode, a
// touch darker than the light window.
zebra: if dark { nudge(win, 12) } else { nudge(win, -10) },
}
}
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_paused: Widget,
kpi_hashrate: Widget,
// The hashrate card's caption label, retitled to "<Algo> Hashrate" as the
// per-algorithm cycle advances (the card itself is re-laid-out with the rest
// in refresh_kpis).
kpi_hashrate_lbl: Widget,
// Which per-algorithm total the hashrate card is currently showing; clicking
// the card advances it, wrapping around the fleet's running algorithms.
hashrate_algo_idx: usize,
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>,
// A per-IP background refresh (right-click "Refresh"), separate from the
// full network scan so it never restarts the whole fleet probe.
refresh: Option<scan::RefreshHandle>,
// 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)>,
/// The main content panel and the KPI card row sizer, plus whether the two
/// wide KPI cards (Hashrate, Est. power) are currently collapsed because the
/// window is too narrow to fit all seven cards (round 11 #2).
panel: Widget,
kpi_row: Widget,
kpi_collapsed: bool,
// The 4 status KPI cards that double as quick-filters: (status text, its
// ButtonClicked id, card panel, value text, label text). The three widgets
// are all painted for the active-filter highlight (so the whole box tints,
// not just the panel behind the text). `active_kpi_filter` is set iff
// view.filters holds exactly that single-value Status filter.
kpi_filter_cards: [(&'static str, i32, Widget, Widget, Widget); 4],
active_kpi_filter: Option<&'static str>,
// 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
// / firmware flash) 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,
// IPs the current config action targets, re-probed after it completes so the
// table reflects the change (e.g. the identify light toggling).
action_targets: Vec<String>,
// A confirmation dialog for disruptive actions, plus its pending target.
confirm_dialog: Widget,
pending_confirm: Option<(Vec<String>, scan::ConfigAction)>,
// The strong typed-confirmation dialog for flashing firmware, plus its
// pending target (selected IPs, the parsed image, and its file name for
// display).
flash_confirm_dialog: Widget,
flash_confirm_input: Widget,
pending_flash: Option<(Vec<String>, FirmwareImage, String)>,
// True while a firmware flash's ActionHandle is in flight. A flash is the
// one irreversible, hardware-destroying action, so it takes an exclusive
// lock: nothing else (scan / refresh / config action / another flash) may
// start while it runs, and it will not start while anything else is running,
// so no two network operations ever race the same miner mid-upload.
flashing: bool,
// The column a header right-click menu targets (remembered across the menu's
// nested event loop until an item is chosen).
header_menu_col: Option<Column>,
// The "Set scan credentials..." dialog.
creds_dialog: Widget,
creds_user_input: Widget,
creds_pass_input: Widget,
// Background access (lock-state) probe.
access_probe: Option<scan::AccessProbeHandle>,
// Background SSH PIC probe + its credentials dialog.
pic_probe: Option<scan::PicProbeHandle>,
pending_pic_targets: Vec<(String, String)>,
picssh_dialog: Widget,
picssh_user_input: Widget,
picssh_pass_input: Widget,
// Saved view presets + the Presets dialog widgets.
presets: Vec<crate::presets::Preset>,
presets_dialog: Widget,
presets_choice: Widget,
presets_name_input: Widget,
// 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,
/// The columns-dialog "hide empty columns" checkbox, read at Apply.
columns_hide_empty_cb: Widget,
/// When set, columns with no scanned value in any row are hidden from the
/// table (non-destructively -- clearing it restores them) (round 11 #9).
auto_hide_empty: bool,
// 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.
// Horizontal box sizer with every card at proportion 1 + EXPAND, so the
// cards are always equal width AND grow to span the full window; a per-card
// min size floors them at their largest content's width.
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, icon: Option<i32>| -> (Widget, 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);
// Min-content floor (the widest label/value); cards grow equally past
// this to fill the window (proportion 1 + EXPAND on add).
card.set_min_size(116, 62);
let cs = Widget::box_sizer(true);
let value = Widget::static_text(card, "0");
value.set_font_size(19);
value.set_bold();
// Neutral cards (Total, Est. power) keep the default text colour so they
// dim with the rest of the dashboard when the window loses focus; only
// the semantically-coloured cards force a foreground (round-10 #2).
if !matches!(kind, ColorKind::Neutral) {
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);
// Centre both texts horizontally: a stretch spacer on each side (no
// ALIGN_CENTRE_HORIZONTAL flag exists in the bridge).
let centre = |w: Widget| {
let row = Widget::box_sizer(false);
row.add_stretch(1);
row.add(w, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
row.add_stretch(1);
row
};
// The value row optionally leads with a small drawn KPI icon (round 11
// #15). Neutral cards (Est. power) colour the icon amber for pop since
// their value text stays the default (dimming) colour.
let value_row = {
let row = Widget::box_sizer(false);
row.add_stretch(1);
if let Some(ik) = icon {
let icol = if matches!(kind, ColorKind::Neutral) { pal.amber } else { vc };
let ic = Widget::kpi_icon(card, ik, icol);
row.add(ic, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT, 5);
}
row.add(value, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
row.add_stretch(1);
row
};
cs.add_stretch(1);
cs.add_sizer(value_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_TOP | sf::BORDER_RIGHT, 8);
cs.add_sizer(centre(lbl), 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_BOTTOM | sf::BORDER_RIGHT, 8);
cs.add_stretch(1);
cs.set_sizer_on(card);
kpi_row.add(card, 1, sf::EXPAND | sf::BORDER_ALL, 4);
kpi_cards.push((card, value, lbl, kind));
(card, value)
};
// Icons (round 11 #15): rabbit=hashing, turtle=slow, broken glass=not
// hashing, otter=paused, hive=hashrate, lightning=power; Total has none.
let (_card_total, kpi_total) = mk_card("Total", ColorKind::Neutral, None);
let (card_hashing, kpi_hashing) = mk_card("Hashing", ColorKind::Green, Some(0));
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber, Some(1));
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red, Some(2));
let (card_paused, kpi_paused) = mk_card("Paused", ColorKind::Blue, Some(3));
let (card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Accent, Some(4));
let (_card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral, Some(5));
drop(mk_card);
let _ = (card_hashing, card_slow, card_not, card_paused);
// The hashrate card is kpi_cards[5] in build order (Total, Hashing, Slow,
// Not, Paused, Hashrate, Power); its caption is retitled per algorithm.
let kpi_hashrate_lbl = kpi_cards[5].2;
// The hashrate card cycles per-algorithm totals on click; bind the card and
// both its texts (so a click on the number or the label registers too).
card_hashrate.bind_click(ID_KPI_HASHRATE);
kpi_hashrate.bind_click(ID_KPI_HASHRATE);
kpi_hashrate_lbl.bind_click(ID_KPI_HASHRATE);
// The 4 status cards double as quick-filters: clicking one narrows the table
// to that status (see `toggle_kpi_filter`). They are kpi_cards[1..=4] in this
// order. Bind the click on the card AND its value/label texts (a click on the
// text must register too), and keep all three widgets so the highlight can
// fill the whole box, not just the panel behind the text.
let filter_ids = [
("hashing", ID_KPI_HASHING),
("slow", ID_KPI_SLOW),
("not hashing", ID_KPI_NOT),
("paused", ID_KPI_PAUSED),
];
let mut kpi_filter_cards: [(&'static str, i32, Widget, Widget, Widget); 4] =
[("", 0, panel, panel, panel); 4];
for (i, &(status, id)) in filter_ids.iter().enumerate() {
let (card, value, lbl, _) = kpi_cards[i + 1];
card.bind_click(id);
value.bind_click(id);
lbl.bind_click(id);
kpi_filter_cards[i] = (status, id, card, value, lbl);
}
root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6);
// Controls row: scan-ranges + play/pause/stop on the left; Filter / Columns
// / Set scan credentials pushed to the right. wrap_sizer so it reflows at
// narrow widths instead of clipping.
let ctl = Widget::wrap_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 presets_btn = Widget::button(panel, "Presets", ID_PRESETS);
ctl.add(presets_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
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 creds_btn = Widget::button(panel, "Set scan credentials...", ID_SCAN_CREDS);
ctl.add(creds_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);
// Collapse the two wide KPI cards when the window is too narrow to fit all
// seven (round 11 #2): listen for panel resizes.
panel.bind_size();
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(640, 480);
// A status bar carries scan state (was an inline label). A second,
// colour-tinted field pinned to the bottom-right corner carries scan/apply
// errors (red) and warnings (amber) so they don't overwrite the scan state.
wx_rs::create_status_bar();
wx_rs::status_indicator_init(frame);
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_paused,
kpi_hashrate,
kpi_hashrate_lbl,
hashrate_algo_idx: 0,
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(),
refresh: None,
playing: true,
auto_secs: scan::load_auto_secs(),
countdown: 0,
selected_ips: HashSet::new(),
pal,
kpi_cards,
panel,
kpi_row,
kpi_collapsed: false,
kpi_filter_cards,
active_kpi_filter: None,
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,
action_targets: Vec::new(),
confirm_dialog: frame,
pending_confirm: None,
flash_confirm_dialog: frame,
flash_confirm_input: frame,
pending_flash: None,
flashing: false,
header_menu_col: None,
creds_dialog: frame,
creds_user_input: frame,
creds_pass_input: frame,
access_probe: None,
pic_probe: None,
pending_pic_targets: Vec::new(),
picssh_dialog: frame,
picssh_user_input: frame,
picssh_pass_input: frame,
presets: crate::presets::load_presets(),
presets_dialog: frame,
presets_choice: frame,
presets_name_input: frame,
action_result: None,
action_result_ticks: 0,
ranges_dialog: frame,
ranges_edit: frame,
ranges_auto: frame,
columns_dialog: frame,
columns_list: frame,
columns_hide_empty_cb: frame,
auto_hide_empty: false,
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(),
};
// Boot with the first (Default) preset's column layout.
if let Some(p) = app.presets.first() {
app.view = p.view.to_view();
}
app.rebuild_table();
Widget::timer(TIMER_SCAN, 1000);
app
}
impl App {
/// Whether `c` has no scanned value in any current row (round 11 #9). IP is
/// never empty. With no rows loaded, nothing is considered empty (so the
/// table isn't blanked before the first scan).
fn column_is_empty(&self, c: Column) -> bool {
c != Column::Ip
&& !self.rows.is_empty()
&& self.rows.iter().all(|r| c.cell(r).trim().is_empty())
}
/// The columns the table actually shows: the view's display columns, minus
/// any that are empty across all rows when the "hide empty columns" option is
/// on (round 11 #9). Every table-path caller uses this (not
/// `view.display_columns()` directly) so header/sort/reorder indices agree
/// with what is rendered.
fn table_columns(&self) -> Vec<Column> {
let mut cols = self.view.display_columns();
if self.auto_hide_empty {
cols.retain(|c| !self.column_is_empty(*c));
}
cols
}
/// Collapse or restore the two wide KPI cards (Hashrate, Est. power) as the
/// window is resized (round 11 #2). When the panel is too narrow to fit all
/// seven cards at their minimum width, the two wide cards are hidden so the
/// five miner-count cards fill the row; they return when there is room again.
fn on_resize(&mut self, width: i32) {
// Each card is a ~116px min + BORDER_ALL*2 (8px); the row itself is
// inset by the root border. Below the width needed for all seven, drop
// the two wide cards.
const CARD_SLOT: i32 = 116 + 8;
let need_all = CARD_SLOT * 7 + 12;
let want_collapsed = width < need_all;
if want_collapsed == self.kpi_collapsed {
return;
}
self.kpi_collapsed = want_collapsed;
let show = !want_collapsed;
// kpi_cards[5] = Hashrate card, [6] = Est. power card (build order).
let hashrate_card = self.kpi_cards[5].0;
let power_card = self.kpi_cards[6].0;
self.kpi_row.sizer_show(hashrate_card, show);
self.kpi_row.sizer_show(power_card, show);
self.panel.layout();
}
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);
// Zebra striping (theme-aware) for row separation now that rows are no
// longer tinted by status.
t.dvlc_set_zebra(Some(self.pal.zebra));
// 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.table_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"),
_ => {}
}
if matches!(c, Column::Hashrate | Column::Hashboards | Column::TotalChips | Column::ChipTemp | Column::Cooling | Column::Locked | Column::Light | Column::Error | Column::Status | Column::Firmware) {
// These columns show two-tone / multi-tone text (actual vs.
// expected, or one colour per fan) via a custom renderer that
// parses the segment-encoded cell value fill_rows writes.
t.dvlc_append_colored_col(&title, c.width(), !fixed);
} else {
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 };
// Hold the scroll position across the full clear+refill so the table
// doesn't jump back to the top as new rows stream in during a scan.
let top = t.dvlc_get_top_row();
t.dvlc_clear();
self.view_idx = self.view.view(&self.rows);
let cols = self.table_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);
}
// Rows are NOT tinted by status any more: every cell is the default text
// colour except the conditionally-formatted columns below (the Status
// column carries the status colour itself). Zebra striping + gridlines
// (set at table build) separate rows instead.
// Overwrite the conditionally-coloured cells with segment-encoded text
// (the custom renderer these columns use parses it back out).
for (disp, &ri) in self.view_idx.iter().enumerate() {
let r = &self.rows[ri];
for (ci, c) in cols.iter().enumerate() {
let encoded = match c {
// Combined columns are built from parts: the ratio is gated
// on the ACTUAL being known, so an unknown actual renders as
// "-/<expected>" in the default colour rather than a red 0%.
Column::Hashrate => {
let actual = format_hashrate_ths(r.hashrate_ths);
let expected = format_hashrate_ths(r.expected_ths);
let ratio = (r.hashrate_ths > 0.0)
.then(|| actual_expected_ratio(r.hashrate_ths, r.expected_ths))
.flatten();
encode_combined_cell(&self.pal, actual, expected, "/", ratio)
}
// Boards column: per-hashboard health dots (round 11 #10).
Column::Hashboards => encode_board_dots(&self.pal, &r.board_status),
Column::TotalChips => {
let actual = r.total_chips.map(|v| v.to_string());
let expected = r.expected_chips.map(|v| v.to_string());
let ratio = r.total_chips.and_then(|a| {
actual_expected_ratio(
a as f64,
r.expected_chips.map(|v| v as f64).unwrap_or(0.0),
)
});
encode_combined_cell(&self.pal, actual, expected, " / ", ratio)
}
Column::ChipTemp => encode_board_temps_cell(&self.pal, &r.board_temps, r.chip_temp_c),
Column::Cooling => encode_cooling_cell(&self.pal, &r.fan_rpms),
// Access column: a padlock icon, green open (writable) / red
// closed (view-only) (round 11 #13).
Column::Locked => encode_access_icon(&self.pal, r.write_locked),
// Light column: a yellow locate dot while flashing (round 11 #10).
Column::Light => encode_light_dot(&self.pal, r.light_flashing),
Column::Error => {
let color = (!r.errors.is_empty()).then_some(self.pal.red);
encode_flag_cell(&c.cell(r), color)
}
Column::Firmware => encode_flag_cell(&c.cell(r), firmware_color(&r.firmware)),
Column::Status => {
// Status keeps its status colour on its own cell (the
// row is no longer tinted wholesale).
encode_flag_cell(&c.cell(r), Some(status_kind_color(&self.pal, r.status())))
}
_ => continue,
};
t.dvlc_set_cell(disp, ci, &encoded);
// The Errors cell gets the full message list as a hover tooltip.
if matches!(c, Column::Error) {
t.dvlc_set_cell_tooltip(disp, ci, &r.errors.join("\n"));
}
}
}
if let Some(row) = top {
t.dvlc_ensure_visible(row.min(self.view_idx.len().saturating_sub(1)));
}
// 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_paused.set_label(&k.paused.to_string());
// Hashrate KPI: no "/s" suffix (per UI request) -> "685 TH", "1.2 PH".
// With a single algorithm running (the common case) the card shows that
// algorithm's total under a "<Algo> Hashrate" caption; when several are
// running, clicking the card cycles `hashrate_algo_idx` through them.
let (algo_label, algo_ths) = if k.hashrate_by_algo.is_empty() {
("SHA-256".to_string(), 0.0)
} else {
let i = self.hashrate_algo_idx % k.hashrate_by_algo.len();
let (a, t) = &k.hashrate_by_algo[i];
(pretty_algo(a), *t)
};
self.kpi_hashrate.set_label(&format_si(algo_ths * 1e12, "H"));
self.kpi_hashrate_lbl.set_label(&format!("{algo_label} Hashrate"));
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
// set_label resizes the static text; re-run each card's sizer so the
// centring spacers recompute around the new width (otherwise the value
// drifts off-centre when a filter changes a count's digit width).
for (card, _, _, _) in &self.kpi_cards {
card.layout();
}
}
/// Show a scan/apply error (red) in the bottom-right status indicator,
/// separate from the left-hand scan-status text.
fn set_error_indicator(&self, msg: &str) {
let c = self.pal.red;
wx_rs::status_indicator_set(msg, c.0, c.1, c.2);
}
/// Show a scan/apply warning (amber) in the bottom-right status indicator.
fn set_warning_indicator(&self, msg: &str) {
let c = self.pal.amber;
wx_rs::status_indicator_set(msg, c.0, c.1, c.2);
}
/// Clear the bottom-right status indicator.
fn clear_indicator(&self) {
wx_rs::status_indicator_set("", 0, 0, 0);
}
/// 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);
// Neutral cards keep the default (dimming) text colour -- see mk_card.
if !matches!(kind, ColorKind::Neutral) {
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.highlight_kpi_filter();
if let Some(t) = self.table {
t.dvlc_set_zebra(Some(self.pal.zebra));
}
self.fill_rows(); // re-colour rows with the new palette
self.table_parent.layout();
}
/// Tint the active status KPI card's background toward its status colour
/// so the active quick-filter is visible at a glance; every other status
/// card resets to the normal card background.
fn highlight_kpi_filter(&self) {
for &(status, _, card, value, lbl) in &self.kpi_filter_cards {
let bg = if Some(status) == self.active_kpi_filter {
tint_toward(self.pal.card_bg, status_kind_color(&self.pal, status), 0.35)
} else {
self.pal.card_bg
};
// Paint the panel and both static texts so the whole box tints; a
// static_text keeps its own background, so tinting only the card
// would leave an untinted rectangle behind the number and label.
card.set_bg(bg.0, bg.1, bg.2);
value.set_bg(bg.0, bg.1, bg.2);
lbl.set_bg(bg.0, bg.1, bg.2);
}
}
/// Click on the hashrate KPI card: advance to the next running algorithm's
/// total (wrapping around). A no-op when fewer than two algorithms are
/// running, since there is nothing to cycle to.
fn cycle_hashrate_algo(&mut self) {
let n = compute_kpis(&self.rows, &self.view_idx).hashrate_by_algo.len();
if n > 1 {
self.hashrate_algo_idx = (self.hashrate_algo_idx + 1) % n;
self.refresh_kpis();
}
}
/// Click on a status KPI card: quick-filter the table to that status, or
/// clear the filter if the same card is clicked again.
fn toggle_kpi_filter(&mut self, status: &'static str) {
if self.active_kpi_filter == Some(status) {
self.active_kpi_filter = None;
self.view.filters.remove(&Column::Status);
} else {
self.active_kpi_filter = Some(status);
self.view.filters.insert(Column::Status, ColFilter::Values(HashSet::from([status.to_string()])));
}
self.highlight_kpi_filter();
self.fill_rows();
}
/// Recompute `active_kpi_filter` from the current Status filter, so a
/// filter edited or cleared through the full Filter dialog doesn't leave a
/// stale KPI card highlighted. Only set when the Status filter is exactly
/// one of the 4 quick-filter values.
fn resync_kpi_filter(&mut self) {
self.active_kpi_filter = match self.view.filters.get(&Column::Status) {
Some(ColFilter::Values(set)) if set.len() == 1 => {
let v = set.iter().next().map(String::as_str);
self.kpi_filter_cards.iter().map(|&(s, _, _, _, _)| s).find(|&s| Some(s) == v)
}
_ => None,
};
self.highlight_kpi_filter();
}
/// 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();
if n == 0 {
return;
}
let menu = Widget::menu_new();
let open = if n == 1 { "Open in browser".to_string() } else { format!("Open {n} miners in browser") };
menu.menu_append(ID_CTX_OPEN, &open);
// While a firmware flash holds the exclusive lock, offer only the
// read-only "Open in browser" action; every network action is refused
// anyway, so don't dangle them in the menu.
if self.flashing {
self.pending_popup = Some((t, menu));
return;
}
menu.menu_append_separator();
// Refresh is always offered for a non-empty selection, independent of
// the capability intersection below.
menu.menu_append(ID_CTX_REFRESH, "Refresh");
// Real PIC-vs-noPIC detection via an on-board SSH i2c probe (asic-rs
// cannot report it over the network); offered for any selection.
menu.menu_append(ID_CTX_PIC_PROBE, "Detect PIC (SSH)...");
// Real access/lock-state check (credentialed digest GET; uses the saved
// scan credentials).
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
// Config actions common to the whole selection (capability
// intersection): an action is offered only if every selected miner
// supports it.
let selected = self.selected_rows();
let caps = MinerCaps::intersect_all(selected.iter().map(|r| r.caps));
if !caps.is_empty() {
let sfx = if n == 1 { String::new() } else { format!(" ({n})") };
if caps.fault_light {
menu.menu_append(ID_CTX_LIGHT_ON, &format!("Flash lights on{sfx}"));
menu.menu_append(ID_CTX_LIGHT_OFF, &format!("Flash lights 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}"));
}
}
// Firmware flash is offered when AT LEAST ONE selected miner supports
// it (not the full intersection) -- flashing a mixed batch simply
// skips the miners that don't.
let flashable = selected.iter().filter(|r| r.caps.firmware_flash).count();
if flashable > 0 {
menu.menu_append_separator();
let sfx = if flashable == 1 { String::new() } else { format!(" ({flashable})") };
menu.menu_append(ID_CTX_FLASH, &format!("Flash firmware...{sfx}"));
}
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()
}
/// The full rows of the currently-selected miners (as opposed to
/// `selected_ip_list`, which returns just their IPs).
fn selected_rows(&self) -> Vec<&MinerRow> {
self.rows.iter().filter(|r| self.selected_ips.contains(&r.ip)).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 self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
if let Some(old) = self.action.take() {
old.stop();
}
let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len());
self.action_targets = ips.clone();
self.action = Some(scan::start_config_action(ips, action));
// Clear any stale error/warning from a previous operation; the new
// outcome repopulates the indicator when this action finishes.
self.clear_indicator();
wx_rs::set_status_text(&msg);
}
/// Start a background per-IP refresh (right-click "Refresh"): re-probes
/// just the given miners without restarting the full network scan.
/// Cancels any refresh already in flight so two never run at once.
fn start_refresh(&mut self, ips: Vec<String>) {
if ips.is_empty() {
return;
}
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
if let Some(old) = self.refresh.take() {
old.stop();
}
let msg = format!("refreshing {} miner(s)...", ips.len());
self.refresh = Some(scan::start_refresh(ips));
wx_rs::set_status_text(&msg);
}
/// Build the SSH PIC-probe dialog: captures the selected miners, collects
/// SSH credentials (prefilled from the saved SSH login), and on OK runs the
/// on-board i2c probe. Returns None (no dialog) if nothing is selected or a
/// flash holds the exclusive lock.
fn build_pic_probe_dialog(&mut self) -> Option<Widget> {
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return None;
}
if self.pic_probe.is_some() {
wx_rs::set_status_text("a PIC probe is already running");
return None;
}
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.map(|r| (r.ip.clone(), r.control_board.clone()))
.collect();
if targets.is_empty() {
return None;
}
self.pending_pic_targets = targets;
let (saved_user, _) = credentials::load_ssh_credentials().unwrap_or_default();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Detect PIC via SSH");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
&format!(
"Probe {} miner(s) over SSH (runs i2cdump on the control board). SSH login for the miner (root, etc.):",
self.pending_pic_targets.len()
),
),
0,
sf::BORDER_ALL,
8,
);
let user_row = Widget::box_sizer(false);
user_row.add(Widget::static_text(dlg, "SSH user:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let user_input = Widget::text_ctrl(dlg, false);
user_input.set_value(if saved_user.is_empty() { "root" } else { &saved_user });
user_input.set_min_size(180, -1);
user_row.add(user_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(user_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_row = Widget::box_sizer(false);
pass_row.add(Widget::static_text(dlg, "SSH password:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let pass_input = Widget::text_ctrl(dlg, false);
pass_input.set_min_size(180, -1);
pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add(
Widget::static_text(dlg, "(Leave the password blank to use SSH key auth.)"),
0,
sf::BORDER_ALL,
6,
);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Probe", ID_PICSSH_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_PICSSH_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(420, 210);
dlg.fit(dlg);
self.picssh_dialog = dlg;
self.picssh_user_input = user_input;
self.picssh_pass_input = pass_input;
Some(dlg)
}
/// Start the PIC probe with the SSH credentials just entered.
fn apply_pic_probe(&mut self) {
let user = self.picssh_user_input.get_value().trim().to_string();
if user.is_empty() {
wx_rs::set_status_text("enter an SSH user");
return;
}
let pass = self.picssh_pass_input.get_value();
let _ = credentials::save_ssh_credentials(&user, &pass);
self.picssh_dialog.close(1);
let targets = std::mem::take(&mut self.pending_pic_targets);
let n = targets.len();
self.pic_probe = Some(scan::start_pic_probe(
targets,
crate::pic_probe::SshCreds { user, pass },
));
wx_rs::set_status_text(&format!("probing PIC on {n} miner(s) via SSH..."));
}
/// Start the access (lock-state) probe on the selected miners, using the
/// saved scan (web) credentials (defaulting to root/root if none are set).
fn start_access_probe(&mut self) {
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
if self.access_probe.is_some() {
wx_rs::set_status_text("an access check is already running");
return;
}
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.map(|r| (r.ip.clone(), r.firmware.clone()))
.collect();
if targets.is_empty() {
return;
}
let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
let n = targets.len();
self.access_probe = Some(scan::start_access_probe(targets, creds));
wx_rs::set_status_text(&format!("checking access on {n} miner(s)..."));
}
/// Drain the running access probe: update each miner's write_locked as its
/// result arrives, and refresh the table + status when done.
fn drain_access_probe(&mut self) {
let Some(h) = &self.access_probe else { return };
let mut status: Option<String> = None;
let mut done = false;
let mut changed = false;
loop {
match h.rx.try_recv() {
Ok(scan::AccessProbeMsg::Started { total }) => {
status = Some(format!("access check: 0/{total}..."));
}
Ok(scan::AccessProbeMsg::Result { ip, locked, error }) => {
if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) {
if error.is_none() {
r.write_locked = locked;
changed = true;
}
}
status = Some(match (&locked, &error) {
(_, Some(e)) => format!("access {ip}: {e}"),
(Some(true), _) => format!("access {ip}: locked"),
(Some(false), _) => format!("access {ip}: unlocked"),
(None, _) => format!("access {ip}: indeterminate"),
});
}
Ok(scan::AccessProbeMsg::Done { total }) => {
status = Some(format!("access check done ({total} miner(s))"));
done = true;
break;
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
done = true;
break;
}
}
}
if changed {
self.fill_rows();
}
if done {
self.access_probe = None;
self.action_result = status.clone();
self.action_result_ticks = ACTION_RESULT_TICKS;
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
}
}
/// Drain the running PIC probe: update each miner's pic_present as its result
/// arrives, and refresh the table + status when done.
fn drain_pic_probe(&mut self) {
let Some(h) = &self.pic_probe else { return };
let mut status: Option<String> = None;
let mut done = false;
let mut changed = false;
loop {
match h.rx.try_recv() {
Ok(scan::PicProbeMsg::Started { total }) => {
status = Some(format!("PIC probe: 0/{total}..."));
}
Ok(scan::PicProbeMsg::Result { ip, pic, error }) => {
if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) {
if error.is_none() {
r.pic_present = pic;
changed = true;
}
}
status = Some(match (&pic, &error) {
(_, Some(e)) => format!("PIC probe {ip}: {e}"),
(Some(true), _) => format!("PIC probe {ip}: PIC"),
(Some(false), _) => format!("PIC probe {ip}: noPIC"),
(None, _) => format!("PIC probe {ip}: indeterminate"),
});
}
Ok(scan::PicProbeMsg::Done { total }) => {
status = Some(format!("PIC probe done ({total} miner(s))"));
done = true;
break;
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
done = true;
break;
}
}
}
if changed {
self.fill_rows();
}
if done {
self.pic_probe = None;
self.action_result = status.clone();
self.action_result_ticks = ACTION_RESULT_TICKS;
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
}
}
/// 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_HDR_SORT_ASC | ID_HDR_SORT_DESC | ID_HDR_SORT_REL_ASC | ID_HDR_SORT_REL_DESC
| ID_HDR_HIDE | ID_HDR_AUTOSIZE | ID_HDR_COLUMNS => return self.on_header_menu(id),
ID_CTX_OPEN => {
for ip in self.selected_ip_list() {
wx_rs::launch_browser(&format!("http://{ip}"));
}
}
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_FLASH => {
// A flash needs exclusive hardware access; don't even prompt if
// any scan / refresh / action is running (re-checked at confirm).
if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() {
wx_rs::set_status_text("busy (scan/action in progress) -- try again once it finishes");
return None;
}
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.filter(|r| r.caps.firmware_flash)
.map(|r| (r.ip.clone(), r.model.clone()))
.collect();
if targets.is_empty() {
return None;
}
// wxFileDialog runs its own nested modal loop; that's fine to
// do inline here (unlike destroying a control) since
// `dispatch` already tolerates re-entrant events via
// try_borrow_mut while a nested loop is running.
let Some(path) = Widget::file_dialog(Widget::main_frame(), "Choose firmware image") else {
return None;
};
match FirmwareImage::from_file(&path) {
Ok(image) => return Some(self.build_flash_confirm_dialog(&path, targets, image)),
Err(e) => wx_rs::set_status_text(&format!("failed to read firmware image: {e}")),
}
}
// Flashing the identify 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}"));
}
}
}
/// Strong typed confirmation before flashing firmware to hardware: the
/// operator must type FLASH exactly, on top of seeing the image's file
/// name and how many of the selected miners actually support it. Built
/// here, shown modally by `dispatch` outside the App borrow.
fn build_flash_confirm_dialog(
&mut self,
path: &str,
targets: Vec<(String, String)>,
image: FirmwareImage,
) -> Widget {
let n = targets.len();
let name = std::path::Path::new(path)
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| path.to_string());
// List exactly which miners (IP + model) will receive the image, so the
// typed confirmation is informed. Warn loudly if the batch spans more
// than one model, since a single image is rarely valid for all of them.
let mut models: Vec<&str> = targets.iter().map(|(_, m)| m.as_str()).collect();
models.sort_unstable();
models.dedup();
let target_list = targets
.iter()
.map(|(ip, model)| format!(" {ip} ({model})"))
.collect::<Vec<_>>()
.join("\n");
let mixed_warn = if models.len() > 1 {
format!(
"\n\nWARNING: the selection spans {} different models ({}). One image is rarely valid for all of them and a wrong image can brick a miner.",
models.len(),
models.join(", ")
)
} else {
String::new()
};
let ips: Vec<String> = targets.into_iter().map(|(ip, _)| ip).collect();
self.pending_flash = Some((ips, image, name.clone()));
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Flash firmware");
let root = Widget::box_sizer(true);
let msg = format!(
"Flash \"{name}\" to these {n} miner(s)? This overwrites running firmware and cannot be undone.\n\n{target_list}{mixed_warn}\n\nType FLASH to confirm:"
);
root.add(Widget::static_text(dlg, &msg), 0, sf::BORDER_ALL, 12);
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, 12);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Flash", ID_FLASH_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_FLASH_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(420, 170);
dlg.fit(dlg);
self.flash_confirm_dialog = dlg;
self.flash_confirm_input = input;
dlg
}
/// Apply the flash confirmation: only start the action if the operator
/// typed exactly "FLASH"; otherwise keep the dialog open (and the pending
/// target captured) so they can correct it.
fn apply_flash_confirm(&mut self) {
if !flash_confirmed(&self.flash_confirm_input.get_value()) {
wx_rs::set_status_text("type FLASH exactly to confirm");
return;
}
if let Some((ips, image, _name)) = self.pending_flash.take() {
self.flash_confirm_dialog.close(1);
// Authoritative exclusivity check: a scan/refresh/action may have
// started while the dialog was open. A flash must never race another
// network operation on the same miner, so refuse rather than run the
// prior handle's `stop()` (which does not join the in-flight upload).
if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() {
wx_rs::set_status_text("busy (scan/action started) -- flash cancelled, try again");
return;
}
let msg = format!("flashing firmware to {} miner(s)...", ips.len());
self.flashing = true;
self.action = Some(scan::start_firmware_flash_action(ips, image));
wx_rs::set_status_text(&msg);
}
}
/// Build (but do not show) the "Set scan credentials..." dialog: HTTP
/// credentials used for firmware auto-discovery on password-protected
/// miners, prefilled from whatever is already saved on disk.
fn build_creds_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Set scan credentials");
let root = Widget::box_sizer(true);
let (saved_user, saved_pass) = credentials::load_credentials().unwrap_or_default();
// Never re-display the saved password in plaintext. Leave the field
// blank; a blank password on Save keeps whatever is already stored (see
// apply_creds_save), so opening this dialog to change only the username
// does not require -- or reveal -- the password.
let pass_hint = if saved_pass.is_empty() {
"HTTP credentials for firmware auto-discovery on password-protected miners."
} else {
"HTTP credentials for firmware auto-discovery. A password is already saved; leave Password blank to keep it, or type a new one to replace it."
};
let hint = Widget::static_text(dlg, pass_hint);
root.add(hint, 0, sf::BORDER_ALL, 8);
let user_row = Widget::box_sizer(false);
user_row.add(Widget::static_text(dlg, "Username:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let user_input = Widget::text_ctrl(dlg, false);
user_input.set_value(&saved_user);
user_input.set_min_size(200, -1);
user_row.add(user_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(user_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_row = Widget::box_sizer(false);
pass_row.add(Widget::static_text(dlg, "Password:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let pass_input = Widget::text_ctrl(dlg, false);
pass_input.set_min_size(200, -1);
pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Save", ID_CREDS_SAVE), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Clear", ID_CREDS_CLEAR), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_CREDS_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, 190);
dlg.fit(dlg);
self.creds_dialog = dlg;
self.creds_user_input = user_input;
self.creds_pass_input = pass_input;
dlg
}
fn apply_creds_save(&mut self) {
let user = self.creds_user_input.get_value();
let mut pass = self.creds_pass_input.get_value();
// A blank password field means "keep the saved password" (the dialog no
// longer pre-fills it in plaintext), so fall back to the stored value.
if pass.is_empty() {
if let Some((_, saved_pass)) = credentials::load_credentials() {
pass = saved_pass;
}
}
match credentials::save_credentials(&user, &pass) {
Ok(()) => {
self.creds_dialog.close(1);
wx_rs::set_status_text("scan credentials saved");
}
Err(e) => wx_rs::set_status_text(&format!("failed to save credentials: {e}")),
}
}
fn apply_creds_clear(&mut self) {
match credentials::clear_credentials() {
Ok(()) => {
self.creds_dialog.close(1);
wx_rs::set_status_text("scan credentials cleared");
}
Err(e) => wx_rs::set_status_text(&format!("failed to clear credentials: {e}")),
}
}
/// 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;
// Bottom-right indicator to apply after the `h` borrow is released:
// None = leave as-is, Some(None) = clear, Some(Some((is_error, msg))).
let mut indicator: Option<Option<(bool, String)>> = None;
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)
});
// Surface the outcome in the bottom-right indicator: a total
// failure is red, a partial failure amber, full success clears.
indicator = Some(if total == 0 || ok == total {
None
} else if ok == 0 {
Some((true, format!("apply failed on all {total} miner(s)")))
} else {
Some((false, format!("apply: {}/{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;
let was_flash = self.flashing;
// Release the firmware-flash exclusive lock (harmless no-op for a
// plain config action, which never set it).
self.flashing = false;
// 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;
// Re-probe the miners the action touched so the table reflects the
// change (e.g. the identify light). Skip after a flash (the miner is
// rebooting and won't answer a refresh yet).
let targets = std::mem::take(&mut self.action_targets);
if !was_flash && !targets.is_empty() {
self.start_refresh(targets);
}
}
// Apply the captured indicator now the `h` borrow is gone.
if let Some(ind) = indicator {
match ind {
None => self.clear_indicator(),
Some((true, msg)) => self.set_error_indicator(&msg),
Some((false, msg)) => self.set_warning_indicator(&msg),
}
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
}
}
/// Drain a running per-IP refresh's results into the status bar and the
/// rows it touches (mirrors `drain_action`'s shape, but a Row message
/// upserts a fresh row instead of reporting per-miner ok/fail).
fn drain_refresh(&mut self) {
let Some(h) = &self.refresh else { return };
let mut status: Option<String> = None;
let mut finished = false;
let mut changed = false;
loop {
match h.rx.try_recv() {
Ok(scan::RefreshMsg::Started { total }) => {
status = Some(format!("refreshing 0/{total} miner(s)..."));
}
Ok(scan::RefreshMsg::Row(row)) => {
row.upsert_into(&mut self.rows);
changed = true;
}
Ok(scan::RefreshMsg::Failed { ip, detail }) => {
status = Some(format!("refresh failed ({ip}: {detail})"));
}
Ok(scan::RefreshMsg::Done { ok, total }) => {
status = Some(if ok == total {
format!("refreshed {ok}/{total} miner(s)")
} else {
format!("refreshed {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("refresh ended".into());
finished = true;
break;
}
}
}
if finished {
self.refresh = None;
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
}
if changed {
self.fill_rows();
}
}
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();
// A fresh scan supersedes any prior error/warning.
wx_rs::status_indicator_set("", 0, 0, 0);
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}"));
// Surface the failure in the bottom-right indicator (red).
let c = self.pal.red;
wx_rs::status_indicator_set(&format!("scan failed: {e}"), c.0, c.1, c.2);
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();
self.drain_refresh();
self.drain_pic_probe();
self.drain_access_probe();
if self.scanning {
return; // status already shows scan progress
}
if self.pic_probe.is_some() || self.access_probe.is_some() {
return; // a probe is in flight; keep its status
}
if self.action.is_some() {
return; // a config action is in flight; keep its status
}
if self.refresh.is_some() {
return; // a per-IP refresh 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>) {
// Never probe the network while a firmware flash is uploading: a stray
// scan connection to a miner mid-write can interrupt/corrupt the flash.
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- scan deferred");
return;
}
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.table_columns();
if creation_idx >= cols.len() {
return;
}
let col = cols[creation_idx];
self.view.sort = if col == Column::Hashrate {
// The Hashrate header cycles through four modes: absolute asc, absolute
// desc, relative (actual/expected) asc, relative desc, then unsorted
// (round 11 #16).
match self.view.sort {
Some((Column::Hashrate, true)) => Some((Column::Hashrate, false)),
Some((Column::Hashrate, false)) => Some((Column::HashrateRel, true)),
Some((Column::HashrateRel, true)) => Some((Column::HashrateRel, false)),
Some((Column::HashrateRel, false)) => None,
_ => Some((Column::Hashrate, true)),
}
} else {
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();
}
/// Right-click on a column header: Excel-style per-column menu (sort, hide,
/// auto-size, and open the full column picker).
fn header_context_menu(&mut self, creation_idx: usize) {
let Some(t) = self.table else { return };
let cols = self.table_columns();
let Some(&col) = cols.get(creation_idx) else { return };
self.header_menu_col = Some(col);
let menu = Widget::menu_new();
menu.menu_append(ID_HDR_SORT_ASC, &format!("Sort {} ascending", col.title()));
menu.menu_append(ID_HDR_SORT_DESC, &format!("Sort {} descending", col.title()));
// The Hashrate column also offers a relative (actual/expected) sort
// (round 11 #16).
if col == Column::Hashrate {
menu.menu_append(ID_HDR_SORT_REL_ASC, "Sort relative hashrate ascending");
menu.menu_append(ID_HDR_SORT_REL_DESC, "Sort relative hashrate descending");
}
menu.menu_append_separator();
menu.menu_append(ID_HDR_AUTOSIZE, "Auto-size this column");
// The fixed IP column can't be hidden.
if !self.view.is_fixed(col) {
menu.menu_append(ID_HDR_HIDE, &format!("Hide {}", col.title()));
}
menu.menu_append_separator();
menu.menu_append(ID_HDR_COLUMNS, "Columns...");
self.pending_popup = Some((t, menu));
}
/// Apply a header-menu action to the remembered column.
fn on_header_menu(&mut self, id: i32) -> Option<Widget> {
let Some(col) = self.header_menu_col else { return None };
match id {
ID_HDR_SORT_ASC => {
self.view.sort = Some((col, true));
self.update_headers();
self.fill_rows();
}
ID_HDR_SORT_DESC => {
self.view.sort = Some((col, false));
self.update_headers();
self.fill_rows();
}
ID_HDR_SORT_REL_ASC => {
self.view.sort = Some((Column::HashrateRel, true));
self.update_headers();
self.fill_rows();
}
ID_HDR_SORT_REL_DESC => {
self.view.sort = Some((Column::HashrateRel, false));
self.update_headers();
self.fill_rows();
}
ID_HDR_HIDE if !self.view.is_fixed(col) => {
self.view.visible.remove(&col);
self.rebuild_table();
}
ID_HDR_AUTOSIZE => {
if let (Some(t), Some(pos)) =
(self.table, self.table_columns().iter().position(|c| *c == col))
{
t.dvlc_autosize_col(pos);
}
}
ID_HDR_COLUMNS => return Some(self.build_columns_dialog()),
_ => {}
}
None
}
/// 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.table_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"),
// The relative-hashrate sort is a pseudo-column; mark it on the
// Hashrate header with a "%" so the mode is visible (round 11 #16).
Some((Column::HashrateRel, asc)) if *c == Column::Hashrate => {
title.push_str(if asc { " %^" } else { " %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.table_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 view-presets dialog: load a saved view, save
/// the current columns/filters/sort as a named preset, or delete one.
fn build_presets_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "View presets");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
"Load a saved view, or save the current columns, filters and sort as a new preset.",
),
0,
sf::BORDER_ALL,
8,
);
let choice = Widget::choice(dlg, ID_PRESET_CHOICE);
for p in &self.presets {
choice.choice_append(&p.name);
}
choice.choice_set_selection(0);
choice.set_min_size(220, -1);
root.add(choice, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let row = Widget::box_sizer(false);
row.add(Widget::button(dlg, "Load", ID_PRESET_LOAD), 0, sf::BORDER_ALL, 4);
row.add(Widget::button(dlg, "Delete", ID_PRESET_DELETE), 0, sf::BORDER_ALL, 4);
root.add_sizer(row, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let saverow = Widget::box_sizer(false);
saverow.add(
Widget::static_text(dlg, "Save current as:"),
0,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL,
4,
);
let name = Widget::text_ctrl(dlg, false);
name.set_min_size(150, -1);
saverow.add(name, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
saverow.add(Widget::button(dlg, "Save", ID_PRESET_SAVE), 0, sf::BORDER_ALL, 4);
root.add_sizer(saverow, 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, "Close", ID_PRESET_CLOSE), 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(400, 220);
dlg.fit(dlg);
self.presets_dialog = dlg;
self.presets_choice = choice;
self.presets_name_input = name;
dlg
}
/// Load the selected preset, replacing the current view (columns, filters,
/// sort) and rebuilding the table.
fn apply_preset_load(&mut self) {
let sel = self.presets_choice.choice_get_selection();
let Some(p) = usize::try_from(sel).ok().and_then(|i| self.presets.get(i)) else { return };
self.view = p.view.to_view();
self.presets_dialog.close(1);
self.rebuild_table();
self.update_headers();
self.resync_kpi_filter();
wx_rs::set_status_text("preset loaded");
}
/// Save the current view as a new (or replaced) named preset.
fn apply_preset_save(&mut self) {
let name = self.presets_name_input.get_value().trim().to_string();
if name.is_empty() {
wx_rs::set_status_text("enter a preset name");
return;
}
if name == "Default" {
wx_rs::set_status_text("\"Default\" is reserved");
return;
}
let view = crate::presets::PresetView::from_view(&self.view);
let preset = crate::presets::Preset { name: name.clone(), view };
if let Some(existing) = self.presets.iter_mut().find(|p| p.name == name) {
*existing = preset;
} else {
self.presets.push(preset);
}
match crate::presets::save_presets(&self.presets) {
Ok(()) => {
self.presets_dialog.close(1);
wx_rs::set_status_text(&format!("saved preset \"{name}\""));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save preset: {e}")),
}
}
/// Delete the selected preset (the built-in "Default" can't be deleted).
fn apply_preset_delete(&mut self) {
let sel = self.presets_choice.choice_get_selection();
let Some(i) = usize::try_from(sel).ok().filter(|&i| i < self.presets.len()) else { return };
if self.presets[i].name == "Default" {
wx_rs::set_status_text("the Default preset can't be deleted");
return;
}
let name = self.presets.remove(i).name;
match crate::presets::save_presets(&self.presets) {
Ok(()) => {
self.presets_dialog.close(1);
wx_rs::set_status_text(&format!("deleted preset \"{name}\""));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save presets: {e}")),
}
}
/// 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 rows to reorder (IP is always first). Shift/Ctrl-click or drag to select several.",
);
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::reorder_list(dlg, &order, &titles);
root.add(list, 1, sf::EXPAND | sf::BORDER_ALL, 6);
// Option: hide columns with no scanned value in any row (round 11 #9).
let hide_empty = Widget::check_box(dlg, "Hide columns with no scanned values");
hide_empty.set_checked(self.auto_hide_empty);
root.add(hide_empty, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_BOTTOM, 6);
self.columns_hide_empty_cb = hide_empty;
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) {
// Persist the "hide empty columns" option (round 11 #9); table_columns()
// applies it non-destructively when the table is (re)built below.
self.auto_hide_empty = self.columns_hide_empty_cb.is_checked();
let base = Self::selectable_columns();
let order = self.columns_list.reorder_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);
// Offer every column (not just the visible ones) so any metric --
// Algorithm included -- can be filtered without first un-hiding it.
self.filter_cols = self.view.filter_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.resync_kpi_filter();
self.fill_rows();
}
fn reset_filters(&mut self) {
self.filter_working.clear();
self.view.filters.clear();
self.filter_dialog.close(1);
self.resync_kpi_filter();
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_PRESETS => return Some(self.build_presets_dialog()),
ID_PICSSH_OK => self.apply_pic_probe(),
ID_PICSSH_CANCEL => {
self.pending_pic_targets.clear();
self.picssh_dialog.close(0);
}
ID_PRESET_LOAD => self.apply_preset_load(),
ID_PRESET_SAVE => self.apply_preset_save(),
ID_PRESET_DELETE => self.apply_preset_delete(),
ID_PRESET_CLOSE => self.presets_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_FLASH_OK => self.apply_flash_confirm(),
ID_FLASH_CANCEL => {
self.pending_flash = None;
self.flash_confirm_dialog.close(0);
}
ID_SCAN_CREDS => return Some(self.build_creds_dialog()),
ID_CREDS_SAVE => self.apply_creds_save(),
ID_CREDS_CLEAR => self.apply_creds_clear(),
ID_CREDS_CANCEL => self.creds_dialog.close(0),
ID_KPI_HASHING => self.toggle_kpi_filter("hashing"),
ID_KPI_SLOW => self.toggle_kpi_filter("slow"),
ID_KPI_NOT => self.toggle_kpi_filter("not hashing"),
ID_KPI_PAUSED => self.toggle_kpi_filter("paused"),
ID_KPI_HASHRATE => self.cycle_hashrate_algo(),
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::DvlcHeaderRightClick => self.header_context_menu(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::Sized => self.on_resize(ev.p1 as i32),
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", "1"),
(self.kpi_paused, "Paused", "1"),
(self.kpi_hashrate, "SHA-256 Hashrate", "685 TH"),
(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.table_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). The 4
// combined/cooling columns are overwritten with segment-encoded
// coloured text, so decode it back to plain text before comparing.
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() {
// Icon/dot columns (round 11 #10/#13) render shape sentinels, not
// text, so they don't round-trip to c.cell(r); they're verified
// structurally in the icon-column spot-check below.
if matches!(c, Column::Hashboards | Column::Locked | Column::Light) {
continue;
}
let want = c.cell(r);
let raw = t.dvlc_get_cell(disp_row, j).unwrap_or_default();
let got = if matches!(c, Column::Hashrate | Column::TotalChips | Column::ChipTemp | Column::Cooling | Column::Error | Column::Status | Column::Firmware) {
decode_segments_plain(&raw)
} else {
raw
};
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 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 {
// Decode any colour-segment encoding (no-op for plain cells) so the
// combined columns compare as their plain "actual / expected" text.
match col {
Some(c) => decode_segments_plain(&t.dvlc_get_cell(row, c).unwrap_or_default()),
None => String::new(),
}
};
// Status is a model property; the Status column is not in the default
// view (round 11 #12), so verify it straight from the row rather than a
// displayed cell.
let status_of = |row: usize| -> &'static str { self.rows[self.view_idx[row]].status() };
// Icon columns (round 11 #10/#13): the store carries shape sentinels
// (dots / padlock), not text -- verify they are present.
let boards_col = cols.iter().position(|c| *c == Column::Hashboards);
let access_col = cols.iter().position(|c| *c == Column::Locked);
if let (Some(bc), Some(row)) = (boards_col, find("10.255.1.166")) {
let raw = t.dvlc_get_cell(row, bc).unwrap_or_default();
check("Boards column renders dot sentinels for a mining miner",
raw.contains('\u{0007}'), format!("cell={raw:?}"));
}
if let (Some(ac), Some(row)) = (access_col, find("10.255.1.112")) {
let raw = t.dvlc_get_cell(row, ac).unwrap_or_default();
check("Access column renders a closed-padlock sentinel for a locked miner",
raw.contains('\u{0002}'), format!("cell={raw:?}"));
}
if let Some(row) = find("10.255.1.149") {
check("S21 Pro (.149) is slow", status_of(row) == "slow",
format!("status=\"{}\"", status_of(row)));
check("S21 Pro (.149) hashrate == 60.0T/200T",
cell(row, hr_col) == "60.0T/200T",
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", status_of(row) == "not hashing",
format!("status=\"{}\"", status_of(row)));
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());
}
if let Some(row) = find("10.255.1.115") {
check("WardenOS-dev (.115) is paused", status_of(row) == "paused",
format!("status=\"{}\"", status_of(row)));
} else {
check("WardenOS-dev (.115) present", false, "row not found".into());
}
// 4b. Device-naming cleanup (#11): the cleaned Model, split Brand/
// Submodel, and control-board short code, read straight from the row
// (these columns are hidden by default, so not in the store above).
// (ip, brand, model, submodel, control-board code).
let name_cases = [
("10.255.1.167", "Antminer", "S19k Pro", "", "AML (CBE)"),
("10.255.1.112", "Antminer", "S17", "", "XIL (C49)"),
("10.255.1.152", "Antminer", "S19j Pro", "", "AML (C76)"),
("10.255.1.149", "Antminer", "S21 Pro", "", "CVI (C88)"),
("10.255.1.166", "Antminer", "S19", "", "BBB (C77)"),
("10.255.1.131", "WhatsMiner", "M30S+", "VE40", "H616 (CB6)"),
("10.255.1.126", "WhatsMiner", "M30S", "VE40", "H3 (CB2)"),
("10.255.1.148", "WhatsMiner", "M50", "VH50", "H6 (CB4)"),
];
for (ip, brand, model, sub, board) in name_cases {
match self.rows.iter().find(|r| r.ip == ip) {
Some(r) => {
check(&format!("{ip} brand == \"{brand}\""), r.brand == brand,
format!("got \"{}\"", r.brand));
check(&format!("{ip} model == \"{model}\""), r.model == model,
format!("got \"{}\"", r.model));
check(&format!("{ip} submodel == \"{sub}\""), r.submodel == sub,
format!("got \"{}\"", r.submodel));
check(&format!("{ip} control board == \"{board}\""), r.control_board == board,
format!("got \"{}\"", r.control_board));
}
None => check(&format!("{ip} 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 -- compare against the model's own
// numeric dotted-quad order (not a lexical string sort, which only
// coincidentally matches while every fixture octet is the same width).
let ips: Vec<String> = self.view_idx.iter().map(|&ri| self.rows[ri].ip.clone()).collect();
let mut sorted = ips.clone();
sorted.sort_by_key(|ip| ip_to_u32(ip));
check("default sort is IP ascending", ips == sorted, String::new());
// 5. KPI quick-filter: clicking a status card filters the table to that
// status; clicking again clears it back to the full fleet.
let full = self.view_idx.len();
self.toggle_kpi_filter("slow");
let slow_only = self.view_idx.iter().all(|&ri| self.rows[ri].status() == "slow");
check("KPI filter 'slow' shows only slow rows",
self.view_idx.len() == 1 && slow_only && self.active_kpi_filter == Some("slow"),
format!("len={}, active={:?}", self.view_idx.len(), self.active_kpi_filter));
self.toggle_kpi_filter("slow");
check("KPI filter toggled off restores full fleet",
self.view_idx.len() == full && self.active_kpi_filter.is_none(),
format!("len={} (want {full}), active={:?}", self.view_idx.len(), self.active_kpi_filter));
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);
}
}
#[cfg(test)]
mod tests {
//! Pure colour/encoding helpers exercised without any wx display: these are
//! the visual contracts the headless self-test's `decode_segments_plain`
//! cell comparison deliberately strips out, so they need their own coverage.
use super::*;
/// A palette with unambiguous sentinel colours so equality checks are exact.
fn test_pal() -> Palette {
Palette {
card_bg: (1, 1, 1),
label: (10, 20, 30),
neutral: (40, 40, 40),
green: (0, 255, 0),
amber: (255, 128, 0),
red: (255, 0, 0),
accent: (0, 0, 255),
zebra: (245, 245, 245),
}
}
#[test]
fn tint_toward_endpoints_and_midpoint() {
let a = (10, 20, 30);
let b = (200, 100, 250);
assert_eq!(tint_toward(a, b, 0.0), a);
assert_eq!(tint_toward(a, b, 1.0), b);
assert_eq!(tint_toward(a, a, 0.37), a, "same endpoints -> unchanged at any fraction");
assert_eq!(tint_toward((0, 0, 0), (255, 255, 255), 0.5), (128, 128, 128));
}
#[test]
fn ratio_color_stops_and_clamping() {
let p = test_pal();
// Scale bottoms out at 50%: red at/below 0.5, amber at 0.75, green at 1.0+.
assert_eq!(ratio_color(&p, 0.5), p.red, "50% -> full red");
assert_eq!(ratio_color(&p, 0.25), p.red, "below 50% -> still full red");
assert_eq!(ratio_color(&p, 0.75), p.amber, "75% -> amber");
assert_eq!(ratio_color(&p, 1.0), p.green, "100% -> green");
assert_eq!(ratio_color(&p, 9.0), p.green, "clamped above 1 (overperforming -> green)");
}
#[test]
fn temp_color_blue_to_red_scale() {
let p = test_pal();
assert_eq!(temp_color(&p, 40.0), p.accent, "cool -> blue");
assert_eq!(temp_color(&p, 20.0), p.accent, "clamped below 40 C");
assert_eq!(temp_color(&p, 90.0), p.red, "hot -> red");
assert_eq!(temp_color(&p, 110.0), p.red, "clamped above 90 C");
assert_eq!(temp_color(&p, 65.0), tint_toward(p.accent, p.red, 0.5), "midpoint blend");
}
#[test]
fn fan_color_grey_to_blue_scale() {
let p = test_pal();
assert_eq!(fan_color(&p, 0.0), p.label, "stopped fan -> grey label colour");
assert_eq!(fan_color(&p, 6000.0), p.accent, "at/above ceiling -> saturated accent blue");
assert_eq!(fan_color(&p, 12000.0), p.accent, "clamped above the ceiling");
assert_eq!(fan_color(&p, 3000.0), tint_toward(p.label, p.accent, 0.5), "halfway blend");
}
#[test]
fn combined_cell_unknown_actual_is_not_coloured_red() {
let p = test_pal();
// Unknown actual with a known expected shows "-" in the DEFAULT colour
// (no ratio) -- not a red 0%. Hashrate uses a no-space "/" separator.
let unknown = encode_combined_cell(&p, None, Some("200T".to_string()), "/", None);
assert_eq!(
unknown,
encode_segments(&[(None, "-".to_string()), (None, "/".to_string()), (None, "200T".to_string())])
);
assert_eq!(decode_segments_plain(&unknown), "-/200T");
// A known ratio colours only the actual half; the slash + expected stay
// the default colour, and it round-trips to the plain "actual/expected".
let known =
encode_combined_cell(&p, Some("60.0T".to_string()), Some("200T".to_string()), "/", Some(0.3));
let expected = encode_segments(&[
(Some(ratio_color(&p, 0.3)), "60.0T".to_string()),
(None, "/".to_string()),
(None, "200T".to_string()),
]);
assert_eq!(known, expected);
assert_eq!(decode_segments_plain(&known), "60.0T/200T");
// Actual-only (no expected) is a single uncoloured segment.
let actual_only = encode_combined_cell(&p, Some("95.0T".to_string()), None, "/", None);
assert_eq!(decode_segments_plain(&actual_only), "95.0T");
}
#[test]
fn cooling_cell_colours_each_fan_with_black_slashes() {
let p = test_pal();
assert_eq!(
decode_segments_plain(&encode_cooling_cell(&p, &[4800.0, 4600.0])),
"4.8k/4.6k",
);
// Slash segments carry no colour (they render in the default text colour).
let encoded = encode_cooling_cell(&p, &[4800.0, 4600.0]);
let expected = encode_segments(&[
(Some(fan_color(&p, 4800.0)), format_fan_rpm(4800.0)),
(None, "/".to_string()),
(Some(fan_color(&p, 4600.0)), format_fan_rpm(4600.0)),
]);
assert_eq!(encoded, expected);
// No fans -> a single empty segment that decodes to "".
assert_eq!(decode_segments_plain(&encode_cooling_cell(&p, &[])), "");
}
}