Files
alkane-toolkit/crates/alkane-gui/src/ui.rs
T
noahandClaude Opus 4.8 bafbd519bb GUI round 15 (part 2, #13): Settings menu, localization, Logs page
Add a Settings menu (the old Credentials toolbar button is now "Settings")
containing Credentials, a Language sub-menu, and a Logs page.

Localization (#13): a small i18n layer -- visible strings are wrapped in
t("English") and looked up per language, falling back to English. Built-in
translations for Mandarin, Russian, French, Spanish and Portuguese cover the
toolbar buttons, KPI captions and table column headers; changing the language
re-labels them live (columns via a table rebuild) and localizes dialogs as
they open. The choice persists under the config dir and loads at startup.
(Dialog-internal strings and status text are not yet fully translated -- the
framework is in place to extend them.)

Logs page (#13): an in-app activity log (scans, operations applied, export,
language change) shown in Settings > Logs with Refresh / Clear.

New wx-rs bridge: menu sub-menus (menu_append_submenu). Bridge patches
0002/0003 regenerated. Unit tests + headless selftest pass; the Chinese UI
was verified rendering end to end.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-21 14:54:10 -06:00

4057 lines
185 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::restore;
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;
// Export all scan data to CSV (round 15 #14).
pub const ID_EXPORT: i32 = 109;
// Settings menu (round 15 #13): the toolbar button + its menu items.
pub const ID_SETTINGS: i32 = 110;
const ID_LANG_BASE: i32 = 790; // one id per language (790 + index)
const ID_LOGS_OPEN: i32 = 796; // open the Logs page
const ID_LOGS_REFRESH: i32 = 797;
const ID_LOGS_CLEAR: i32 = 798;
const ID_LOGS_CLOSE: i32 = 799;
// 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;
// Column-picker sort buttons (round 13 #1).
const ID_COLS_ALPHA: i32 = 231;
const ID_COLS_CATEGORIES: i32 = 232;
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_ACCESS_PROBE: i32 = 731;
// View a miner's log fetched over its firmware API (round 12 #12).
const ID_CTX_VIEW_LOG: i32 = 734;
const ID_LOGVIEW_CLOSE: i32 = 785;
// Restore aftermarket firmware to stock (round 12 #8a); strong typed confirm.
const ID_CTX_RESTORE_STOCK: i32 = 735;
const ID_RESTORE_OK: i32 = 786;
const ID_RESTORE_CANCEL: i32 = 787;
// Configure pools (round 14 #7): pool address + account + worker-name template.
const ID_CTX_POOLS: i32 = 736;
const ID_POOLS_OK: i32 = 788;
const ID_POOLS_CANCEL: i32 = 789;
// Pool-field "+" dropdown buttons (round 15 #1): 12 buttons (3 rows x 4 fields),
// id = base + row*4 + field. The dropdown menu items use their own id range.
const ID_POOL_PLUS_BASE: i32 = 800;
const ID_POOL_MENU_ADD: i32 = 819; // "add current box value to the dropdown"
const ID_POOL_MENU_BASE: i32 = 820; // one id per dropdown entry (820 + index)
// 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;
// Credentials dialog (round 13 #2): a global "all firmwares" login plus a
// per-firmware row for every registry firmware, all in one dialog.
const ID_FWCREDS_SAVE: i32 = 750;
const ID_FWCREDS_RESET: i32 = 751;
const ID_FWCREDS_CANCEL: i32 = 752;
// 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.
// 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)
}
}
/// Whether a firmware family has a supported restore-to-stock path (round 12
/// #8a): VNish/WildRose (HTTP), LuxOS (:4028), Braiins (SSH). Others (stock,
/// ePIC, etc.) have no in-tool revert here.
fn firmware_is_restorable(family: &str) -> bool {
let f = family.trim().to_ascii_lowercase();
f.contains("vnish")
|| f.contains("wildrose")
|| f.contains("anthill")
|| f.contains("lux")
|| f.contains("braiins")
|| f.contains("bos")
}
/// 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}";
// Status-column KPI icons (round 12 #11): one sentinel per status, each drawn
// from the same SVG as its dashboard KPI card. Registered with the bridge in
// `register_cell_icons` at startup.
const SHAPE_HASHING: &str = "\u{0004}";
const SHAPE_SLOW: &str = "\u{0005}";
const SHAPE_NOTHASHING: &str = "\u{0006}";
const SHAPE_PAUSED: &str = "\u{0008}";
/// Locate-light dot that fades in and out (round 12 #6); distinct from the static
/// `SHAPE_DOT` so only the flashing light pulses, not the hashboard health dots.
const SHAPE_PULSE_DOT: &str = "\u{000B}";
// Component-health icons (round 13 #3): one sentinel per component kind, each
// drawn from the operator-supplied Font Awesome SVG and recoloured per component
// state. Registered in `register_cell_icons`.
const SHAPE_BOLT: &str = "\u{000C}"; // power supply
const SHAPE_BRAIN: &str = "\u{000E}"; // control board
const SHAPE_FAN: &str = "\u{000F}"; // cooling fan
const SHAPE_CHIP: &str = "\u{0010}"; // hashboard
/// Locate-light beacon (round 15 #6): a green dot above a red dot, both flashing
/// quickly. Replaces the single fading amber dot for the Light column.
const SHAPE_LIGHT_BEACON: &str = "\u{0011}";
/// Health-column alignment gap (round 15 #5): one health-icon-width slot that
/// draws nothing, so component icons line up across rows.
const SHAPE_GAP: &str = "\u{0012}";
/// Register every SVG-backed table-cell icon with the bridge (round 12 #9/#11):
/// the access padlocks and the four status KPI icons. Called once at startup;
/// the renderer recolours each per cell. The sentinel code points MUST match the
/// `\u{..}` constants above and the SHAPE_* set in widgets_bridge.cpp.
fn register_cell_icons() {
// (sentinel first char, svg) pairs; the bridge reads the viewBox dims we pass
// to keep each icon's aspect ratio when it rasterises at the cell height.
let icons: [(&str, &str); 10] = [
(SHAPE_LOCK, SVG_LOCK),
(SHAPE_UNLOCK, SVG_UNLOCK),
(SHAPE_HASHING, SVG_RABBIT),
(SHAPE_SLOW, SVG_TURTLE),
(SHAPE_NOTHASHING, SVG_WINE_CRACK),
(SHAPE_PAUSED, SVG_OTTER),
(SHAPE_BOLT, SVG_BOLT_FULL),
(SHAPE_BRAIN, SVG_BRAIN_FULL),
(SHAPE_FAN, SVG_FAN_FULL),
(SHAPE_CHIP, SVG_CHIP_FULL),
];
for (sentinel, svg) in icons {
let cp = sentinel.chars().next().map(|c| c as u32).unwrap_or(0);
let (vbw, vbh) = svg_viewbox(svg);
wx_rs::register_shape_svg(cp, svg, vbw, vbh);
}
}
/// Parse an SVG's viewBox width/height (round 12 #9/#11), defaulting to a square
/// when absent so the bridge can preserve the icon aspect at any cell height.
fn svg_viewbox(svg: &str) -> (i32, i32) {
svg.split("viewBox=\"")
.nth(1)
.and_then(|s| s.split('"').next())
.and_then(|vb| {
let n: Vec<f64> = vb.split_whitespace().filter_map(|x| x.parse().ok()).collect();
(n.len() == 4 && n[2] > 0.0 && n[3] > 0.0).then(|| (n[2].round() as i32, n[3].round() as i32))
})
.unwrap_or((1, 1))
}
/// 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 green-over-red beacon flashing quickly while the miner's
/// locate light is on, else blank (round 15 #6; was a single fading amber dot).
/// The beacon draws its own colours, so the segment colour is unused.
fn encode_light_dot(_pal: &Palette, flashing: Option<bool>) -> String {
match flashing {
Some(true) => encode_segments(&[(None, SHAPE_LIGHT_BEACON.to_string())]),
_ => encode_segments(&[(None, String::new())]),
}
}
/// Status column: the status rendered as its KPI icon in the status colour
/// (round 12 #11) -- rabbit=hashing, turtle=slow, cracked wine glass=not
/// hashing, otter=paused. An unrecognised status falls back to coloured text.
fn encode_status_icon(pal: &Palette, status: &str) -> String {
let shape = match status {
"hashing" => SHAPE_HASHING,
"slow" => SHAPE_SLOW,
"not hashing" => SHAPE_NOTHASHING,
"paused" => SHAPE_PAUSED,
_ => return encode_segments(&[(Some(status_kind_color(pal, status)), status.to_string())]),
};
encode_segments(&[(Some(status_kind_color(pal, status)), shape.to_string())])
}
/// The colour a component-health state renders in (round 13 #3): grey =
/// unreachable, red = detected but down, yellow = sub-optimal, green = healthy.
fn health_color(pal: &Palette, h: crate::model::CompHealth) -> (u8, u8, u8) {
use crate::model::CompHealth;
match h {
CompHealth::Unreachable => pal.label,
CompHealth::Down => pal.red,
CompHealth::Degraded => pal.amber,
CompHealth::Ok => pal.green,
}
}
/// Health column: one coloured icon per component (round 13 #3), in the order
/// power supply, control board, each fan (front-to-back / top-to-bottom), then
/// each hashboard. Replaces the old Errors/Boards/Status columns.
///
/// Icons line up in fixed slots across rows (round 15 #5): the fan and hashboard
/// groups are padded with blank gaps out to `max_fans` / `max_boards` (the widest
/// counts in the current fleet), so a miner with fewer fans/boards leaves a gap
/// where the missing ones would be and its hashboards still align. This is
/// parametric -- the maxima are recomputed from the fleet each refresh.
fn encode_component_health(
pal: &Palette,
r: &crate::model::MinerRow,
max_fans: usize,
max_boards: usize,
) -> String {
let mut segs: Vec<(Option<(u8, u8, u8)>, String)> = Vec::new();
segs.push((Some(health_color(pal, r.power_health())), SHAPE_BOLT.to_string()));
segs.push((Some(health_color(pal, r.control_health())), SHAPE_BRAIN.to_string()));
let fans = r.fan_healths();
for h in &fans {
segs.push((Some(health_color(pal, *h)), SHAPE_FAN.to_string()));
}
for _ in fans.len()..max_fans {
segs.push((None, SHAPE_GAP.to_string()));
}
let boards = r.board_healths();
for h in &boards {
segs.push((Some(health_color(pal, *h)), SHAPE_CHIP.to_string()));
}
for _ in boards.len()..max_boards {
segs.push((None, SHAPE_GAP.to_string()));
}
encode_segments(&segs)
}
// KPI card icons (round 11 #15). The animal/wine-glass SVGs are Font Awesome Pro
// (operator-supplied); bolt/hive are matching in-repo SVGs. All use
// fill="currentColor", recoloured per card at render time.
const SVG_RABBIT: &str = include_str!("../assets/icons/rabbit.svg");
const SVG_TURTLE: &str = include_str!("../assets/icons/turtle.svg");
const SVG_WINE_CRACK: &str = include_str!("../assets/icons/wine-glass-crack.svg");
const SVG_OTTER: &str = include_str!("../assets/icons/otter.svg");
const SVG_HIVE: &str = include_str!("../assets/icons/hive.svg");
const SVG_BOLT: &str = include_str!("../assets/icons/bolt.svg");
// Access-column padlocks (round 12 #9): operator-supplied Font Awesome padlocks
// that replace the hand-drawn vector padlocks in the table.
const SVG_LOCK: &str = include_str!("../assets/icons/lock.svg");
const SVG_UNLOCK: &str = include_str!("../assets/icons/unlock.svg");
// Component-health icons (round 13 #3): operator-supplied Font Awesome solid
// glyphs (no fill attribute -- the renderer injects the per-component colour).
const SVG_BOLT_FULL: &str = include_str!("../assets/icons/bolt-solid-full.svg");
const SVG_BRAIN_FULL: &str = include_str!("../assets/icons/brain-solid-full.svg");
const SVG_FAN_FULL: &str = include_str!("../assets/icons/fan-solid-full.svg");
const SVG_CHIP_FULL: &str = include_str!("../assets/icons/microchip-solid-full.svg");
/// KPI card minimum widths. The count cards (Total/Hashing/...) are narrow; the
/// two wide cards (SHA-256 Hashrate, Est. power) need more room so their
/// icon + units-bearing value never clips (round 12 #2). The wide floor fits the
/// widest realistic value the card can show -- a ~20px icon + 5px gap + a value
/// text up to "118.0 PH" (~127px at 19pt bold) + the card's 16px side inset --
/// so the units ("kW"/"PH"/...) stay visible instead of being squeezed off; the
/// row collapses the wide cards entirely (see `on_resize`) rather than shrink
/// them below this and clip.
const KPI_MIN: i32 = 116;
const KPI_WIDE_MIN: i32 = 176;
/// Recolour an SVG to the KPI card's colour (round 11 #15). Some Font Awesome
/// exports use fill="currentColor" (replaced here); others omit fill entirely and
/// default to black, so a root `fill` is also injected for shapes to inherit.
fn svg_recolored(svg: &str, color: (u8, u8, u8)) -> String {
let hex = format!("#{:02X}{:02X}{:02X}", color.0, color.1, color.2);
let s = svg.replace("currentColor", &hex);
s.replacen("<svg ", &format!("<svg fill=\"{hex}\" "), 1)
}
/// Width to render an SVG at, preserving its viewBox aspect ratio at height `h`.
fn svg_width_for_height(svg: &str, h: i32) -> i32 {
svg.split("viewBox=\"")
.nth(1)
.and_then(|s| s.split('"').next())
.and_then(|vb| {
let n: Vec<f64> = vb.split_whitespace().filter_map(|x| x.parse().ok()).collect();
(n.len() == 4 && n[3] > 0.0).then(|| ((h as f64) * n[2] / n[3]).round() as i32)
})
.unwrap_or(h)
.max(1)
}
/// 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,
// Per-miner scan timeout in seconds (round 14 #2).
scan_timeout_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)>,
// Localizable widgets (toolbar buttons + KPI captions) with their English key,
// re-labelled when the language changes (round 15 #13).
l10n_labels: Vec<(Widget, &'static str)>,
/// 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>,
// Per-miner in-flight operation label (round 14 #4): while a miner has an
// operation running (refresh, config action, light, firmware, restore, access
// check), its Health cell shows this text instead of the component icons.
op_status: std::collections::HashMap<String, 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 optional global "all firmwares" login shown at the top of the
// Credentials dialog (round 13 #2). Empty when no global credential is set.
creds_user_input: Widget,
creds_pass_input: Widget,
// The Credentials dialog (round 13 #2): the global login above plus one
// (firmware name, user field, pass field) row per registry firmware.
fwcreds_dialog: Widget,
fwcreds_rows: Vec<(String, Widget, Widget)>,
// Background access (lock-state) probe.
access_probe: Option<scan::AccessProbeHandle>,
// The API log viewer dialog (round 12 #12).
logview_dialog: Widget,
// Settings > Logs page (round 15 #13).
logs_dialog: Widget,
logs_text: Widget,
// Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog.
restore: Option<restore::RestoreHandle>,
restore_dialog: Widget,
pending_restore: Vec<restore::RestoreTarget>,
// Configure-pools dialog (round 14 #7, expanded round 15 #1): 3 pool rows x 4
// fields (address, account, worker, password) = 12 text controls, indexed
// row*4 + field. Plus the "+" dropdown menu state.
pools_dialog: Widget,
pool_fields: Vec<Widget>,
pool_menu_target: usize, // which field the open "+" menu edits
pool_menu_field: crate::pool_prefs::PoolField,
pool_menu_values: Vec<String>, // values behind the open menu, by item index
// 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.
ranges_dialog: Widget,
ranges_edit: Widget,
ranges_auto: Widget,
ranges_timeout: 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();
// Register the SVG-backed table-cell icons once (access padlocks + status KPI
// icons, round 12 #9/#11) before any row is rendered.
register_cell_icons();
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<&'static str>| -> (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(KPI_MIN, 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, &crate::i18n::t(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(svg) = icon {
// Icon takes the card's value colour, so each icon matches its KPI
// text (otter = paused colour, bolt = est-power colour, etc.).
let icol = vc;
let h = 20;
let ic = Widget::svg_icon(card, &svg_recolored(svg, icol), svg_width_for_height(svg, h), h);
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, cracked wine 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(SVG_RABBIT));
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber, Some(SVG_TURTLE));
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red, Some(SVG_WINE_CRACK));
let (card_paused, kpi_paused) = mk_card("Paused", ColorKind::Blue, Some(SVG_OTTER));
// Total-hashrate value renders in the default (black) text colour, not accent
// (round 12 #1); it still dims with focus like the other neutral cards.
let (card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Neutral, Some(SVG_HIVE));
let (card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral, Some(SVG_BOLT));
drop(mk_card);
// The two wide cards carry a units-bearing value (icon + e.g. "685 TH" /
// "21.3 kW"); give them a larger min width so the value never clips, and
// collapse them before the row would squeeze them below it (round 12 #2).
card_hashrate.set_min_size(KPI_WIDE_MIN, 62);
card_power.set_min_size(KPI_WIDE_MIN, 62);
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, &crate::i18n::t("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);
// Toolbar buttons; labels are localized and tracked for live re-labelling
// when the language changes (round 15 #13).
let mut l10n_labels: Vec<(Widget, &'static str)> = Vec::new();
l10n_labels.push((ranges_btn, "Scan ranges"));
let mut tbtn = |label: &'static str, id: i32| -> Widget {
let b = Widget::button(panel, &crate::i18n::t(label), id);
ctl.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
l10n_labels.push((b, label));
b
};
let presets_btn = tbtn("Presets", ID_PRESETS);
let filter_btn = tbtn("Filter", ID_FILTER);
let columns_btn = tbtn("Columns", ID_COLUMNS);
let export_btn = tbtn("Export", ID_EXPORT);
// The old Credentials button is now a Settings menu (round 15 #13).
let creds_btn = tbtn("Settings", ID_SETTINGS);
root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
// Track the KPI captions for live re-localization (index 5, the hashrate
// caption, is dynamic per-algorithm so it is refreshed by refresh_kpis).
let kpi_keys = ["Total", "Hashing", "Slow", "Not hashing", "Paused", "", "Est. power"];
for (i, key) in kpi_keys.iter().enumerate() {
if !key.is_empty() {
if let Some(card) = kpi_cards.get(i) {
l10n_labels.push((card.2, key));
}
}
}
// 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);
// Table-zoom slider in the bottom-right of the status bar (round 14 #3).
wx_rs::status_zoom_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(), scan::load_scan_timeout())),
scanning: true,
scan_total: 0,
target_ips: HashSet::new(),
refresh: None,
playing: true,
auto_secs: scan::load_auto_secs(),
scan_timeout_secs: scan::load_scan_timeout(),
countdown: 0,
selected_ips: HashSet::new(),
pal,
kpi_cards,
l10n_labels,
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(),
op_status: std::collections::HashMap::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_user_input: frame,
creds_pass_input: frame,
fwcreds_dialog: frame,
fwcreds_rows: Vec::new(),
access_probe: None,
logview_dialog: frame,
logs_dialog: frame,
logs_text: frame,
restore: None,
restore_dialog: frame,
pending_restore: Vec::new(),
pools_dialog: frame,
pool_fields: Vec::new(),
pool_menu_target: 0,
pool_menu_field: crate::pool_prefs::PoolField::Address,
pool_menu_values: Vec::new(),
presets: crate::presets::load_presets(),
presets_dialog: frame,
presets_choice: frame,
presets_name_input: frame,
ranges_dialog: frame,
ranges_edit: frame,
ranges_auto: frame,
ranges_timeout: 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 occupies its min width + BORDER_ALL*2 (8px); the row itself is
// inset by the root border (~12px). Collapse the two wide cards below the
// width where all seven fit at their mins, so the wide cards' units-bearing
// value never gets squeezed/clipped (round 12 #2) -- they drop out cleanly
// instead.
let need_all = 5 * (KPI_MIN + 8) + 2 * (KPI_WIDE_MIN + 8) + 12;
let want_collapsed = width < need_all;
if want_collapsed != self.kpi_collapsed {
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();
}
// A nested wxPanel does not re-run its own sizer when the parent resizes
// it, so the value/label centring spacers keep the slot sizes they were
// given at the previous width. Re-layout each card here so the value
// (which may carry a units suffix like "kW"/"PH") stays centred and its
// full text is allocated -- otherwise the suffix reads as clipped when
// the row is squeezed (round 12 #2).
for (card, _, _, _) in &self.kpi_cards {
card.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 = crate::i18n::t(c.title());
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::Health | 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();
// Re-apply the table zoom so a non-100% zoom survives this rebuild
// (round 14 #3); the fresh columns come back at their 100% widths.
wx_rs::table_zoom_reapply();
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).
// Widest fan / hashboard counts across the visible fleet, so the Health
// column can pad shorter miners with gaps and keep every component icon
// in a fixed slot (round 15 #5).
let (max_fans, max_boards) = self.view_idx.iter().fold((0usize, 0usize), |(f, b), &ri| {
let r = &self.rows[ri];
(f.max(r.fan_healths().len()), b.max(r.board_healths().len()))
});
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)
}
// Health column: one coloured icon per component (round 13 #3).
// While an operation runs on this miner, its Health cell shows
// the progress text instead of the component icons (round 14 #4).
Column::Health => match self.op_status.get(&r.ip) {
Some(op) => encode_segments(&[(Some(self.pal.amber), op.clone())]),
None => encode_component_health(&self.pal, r, max_fans, max_boards),
},
// 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 => {
// The status reads as its KPI icon (round 12 #11), drawn
// in the status colour so it matches the dashboard card.
encode_status_icon(&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"));
}
// The Health icons carry a per-ICON hover tooltip (round 15 #15):
// hovering a specific fan/board shows just that component's state
// (and any error attributed to it). While an operation runs, the
// cell is text, so use a plain cell tooltip instead.
if matches!(c, Column::Health) {
if self.op_status.contains_key(&r.ip) {
t.dvlc_set_icon_tooltips(disp, ci, &[]);
t.dvlc_set_cell_tooltip(disp, ci, &r.health_summary());
} else {
t.dvlc_set_cell_tooltip(disp, ci, "");
let tips = r.health_tooltips(max_fans, max_boards);
t.dvlc_set_icon_tooltips(disp, ci, &tips);
}
}
}
}
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);
}
// Run the locate-light fade timer only while a visible row's light is
// actually flashing (round 12 #6), so the table isn't repainted on a timer
// when there is nothing to animate.
let any_flashing = self
.view_idx
.iter()
.any(|&ri| self.rows[ri].light_flashing == Some(true));
wx_rs::set_light_pulse(any_flashing);
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 access/lock-state check (credentialed digest GET; uses the saved
// scan credentials).
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
// Fetch and scan this miner's log over its firmware API (round 12 #12).
menu.menu_append(ID_CTX_VIEW_LOG, "View log (API)...");
// Restore aftermarket firmware to stock (round 12 #8a): offered only when
// the selection includes a revertible aftermarket firmware.
if self.selected_rows().iter().any(|r| firmware_is_restorable(&r.firmware)) {
menu.menu_append_separator();
menu.menu_append(ID_CTX_RESTORE_STOCK, "Restore to stock firmware...");
}
// 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}"));
}
if caps.pools {
menu.menu_append(ID_CTX_POOLS, &format!("Configure pools...{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()
}
/// Mark each of `ips` as having an in-flight operation labelled `label`
/// (round 14 #4), so its Health cell shows the progress text instead of the
/// component icons, and repaint those cells.
fn set_op_status(&mut self, ips: &[String], label: &str) {
for ip in ips {
self.op_status.insert(ip.clone(), label.to_string());
}
self.fill_rows();
}
/// Clear one miner's in-flight operation label. Repaint is left to the caller
/// (usually a single fill_rows after draining a batch of results).
fn clear_op_status(&mut self, ip: &str) {
self.op_status.remove(ip);
}
/// Build (but do not show) the Configure-pools dialog (round 15 #1): three
/// pool rows, each with address + account + worker + password boxes and a "+"
/// dropdown next to each. Address/account are required per used row; the
/// worker expands per miner from placeholders. Returns None when nothing is
/// selected or a flash holds the exclusive lock.
fn build_pools_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.selected_rows().is_empty() {
return None;
}
let n = self.selected_ip_list().len();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Configure pools");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
&format!("Set up to 3 pools on {n} selected miner(s). Leave a row blank to skip it; address + account are required for a used row. Use \"+\" for presets; worker placeholders (e.g. {{ip4}}, {{serial}}) expand per miner and insert at the cursor."),
),
0,
sf::BORDER_ALL,
8,
);
// Column headers.
let head = Widget::box_sizer(false);
let hl = |t: &str, w: i32| {
let l = Widget::static_text(dlg, t);
l.set_min_size(w, -1);
l
};
head.add(hl("", 46), 0, sf::BORDER_LEFT, 6);
head.add(hl("Address", 210), 0, sf::BORDER_LEFT, 6);
head.add(hl("Account", 150), 0, sf::BORDER_LEFT, 6);
head.add(hl("Worker", 150), 0, sf::BORDER_LEFT, 6);
head.add(hl("Password", 110), 0, sf::BORDER_LEFT, 6);
root.add_sizer(head, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
let mut fields: Vec<Widget> = Vec::with_capacity(12);
// widths per field type (address, account, worker, password).
let widths = [180, 120, 120, 80];
for row in 0..3usize {
let rsizer = Widget::box_sizer(false);
let lbl = Widget::static_text(dlg, &format!("Pool {}", row + 1));
lbl.set_min_size(46, -1);
rsizer.add(lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT, 6);
for field in 0..4usize {
let input = Widget::text_ctrl(dlg, false);
input.set_min_size(widths[field], -1);
rsizer.add(input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT, 6);
let plus = Widget::button(dlg, "+", ID_POOL_PLUS_BASE + (row * 4 + field) as i32);
plus.set_min_size(26, -1);
rsizer.add(plus, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
fields.push(input);
}
root.add_sizer(rsizer, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 4);
}
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Apply", ID_POOLS_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_POOLS_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(760, 260);
dlg.fit(dlg);
self.pools_dialog = dlg;
self.pool_fields = fields;
Some(dlg)
}
/// The `PoolField` kind of a 0..4 field index within a pool row.
fn pool_field_kind(field: usize) -> crate::pool_prefs::PoolField {
use crate::pool_prefs::PoolField;
match field {
0 => PoolField::Address,
1 => PoolField::Account,
2 => PoolField::Worker,
_ => PoolField::Password,
}
}
/// A pool "+" button was clicked: build its dropdown (presets + saved + "add
/// current") and queue it to pop up (round 15 #1).
fn open_pool_dropdown(&mut self, target: usize) {
if target >= self.pool_fields.len() {
return;
}
let field = Self::pool_field_kind(target % 4);
let entries = crate::pool_prefs::dropdown_entries(field);
let menu = Widget::menu_new();
self.pool_menu_values.clear();
for (i, (label, value)) in entries.into_iter().enumerate() {
menu.menu_append(ID_POOL_MENU_BASE + i as i32, &label);
self.pool_menu_values.push(value);
}
menu.menu_append_separator();
menu.menu_append(ID_POOL_MENU_ADD, "Add this box's value to the list");
self.pool_menu_target = target;
self.pool_menu_field = field;
self.pending_popup = Some((self.pools_dialog, menu));
}
/// A pool dropdown item was chosen (round 15 #1). Worker values insert at the
/// cursor (so several placeholders can be combined); other fields replace.
fn choose_pool_dropdown(&mut self, id: i32) {
use crate::pool_prefs::PoolField;
let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() else {
return;
};
if id == ID_POOL_MENU_ADD {
let val = input.get_value();
if crate::pool_prefs::add_saved(self.pool_menu_field, &val) {
wx_rs::set_status_text("added to the dropdown list");
}
return;
}
let idx = (id - ID_POOL_MENU_BASE) as usize;
let Some(value) = self.pool_menu_values.get(idx).cloned() else {
return;
};
if self.pool_menu_field == PoolField::Worker {
input.write_text(&value); // insert at cursor
} else {
input.set_value(&value);
}
}
/// Read the 3 pool rows, expand each row's worker per selected miner, and
/// start the background pool-config action (round 15 #1). Rows missing an
/// address or account are skipped; a miner with no usable rows is skipped.
fn apply_pools(&mut self) {
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
// Collect the raw rows: (address, account, worker_template, password).
let mut rows: Vec<(String, String, String, String)> = Vec::new();
for row in 0..3usize {
let get = |f: usize| self.pool_fields.get(row * 4 + f).map(|w| w.get_value()).unwrap_or_default();
let addr = get(0).trim().to_string();
let account = get(1).trim().to_string();
let worker_tpl = get(2);
let password = {
let p = get(3).trim().to_string();
if p.is_empty() { "x".to_string() } else { p }
};
// A row is used only when it has both an address and an account.
if !addr.is_empty() && addr != "stratum+tcp://" && !account.is_empty() {
rows.push((addr, account, worker_tpl, password));
}
}
if rows.is_empty() {
wx_rs::set_status_text("enter at least one pool (address + account)");
return;
}
let targets: Vec<scan::PoolTarget> = self
.selected_rows()
.iter()
.map(|r| {
let pools = rows
.iter()
.map(|(addr, account, worker_tpl, password)| {
let worker = r.expand_worker_template(worker_tpl);
let worker = worker.trim();
let username = if worker.is_empty() {
account.clone()
} else {
format!("{account}.{worker}")
};
scan::PoolEntry { url: addr.clone(), username, password: password.clone() }
})
.collect();
scan::PoolTarget { ip: r.ip.clone(), pools }
})
.collect();
if targets.is_empty() {
self.pools_dialog.close(0);
return;
}
let ips: Vec<String> = targets.iter().map(|t| t.ip.clone()).collect();
if let Some(old) = self.action.take() {
old.stop();
}
self.pools_dialog.close(1);
self.action_targets = ips.clone();
crate::logs::log(format!("configure pools on {} miner(s)", ips.len()));
self.set_op_status(&ips, "setting pools…");
self.action = Some(scan::start_pools_action(targets));
}
/// 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();
}
// Progress shows in each miner's Health cell (round 15 #8), not the scan
// line; the bottom-right indicator still surfaces failures at the end.
crate::logs::log(format!("apply {} to {} miner(s)", action.label(), ips.len()));
self.action_targets = ips.clone();
self.set_op_status(&ips, &action.progress_label());
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();
}
/// 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();
}
// Show "refreshing…" in each miner's Health cell while it re-probes (#4);
// the bottom-left scan line is left untouched (round 15 #8).
self.set_op_status(&ips, "refreshing…");
self.refresh = Some(scan::start_refresh(ips));
}
/// Fetch the selected miner's log over its firmware API and show it in a
/// viewer with a regex summary at the top (round 12 #12). The fetch is a
/// short blocking network call (a manual, single-miner action). Returns the
/// dialog to show, or None after reporting why no log could be read.
fn build_log_view_dialog(&mut self) -> Option<Widget> {
let rows = self.selected_rows();
let r = rows.first()?;
let (ip, brand, firmware) = (r.ip.clone(), r.brand.clone(), r.firmware.clone());
// VNish unlock password + Antminer web login: a per-firmware override
// (round 12 #13) wins, else the shipped default / saved global creds.
let vnish_pass = credentials::load_firmware_credentials()
.get("VNish")
.map(|(_, p)| p.clone())
.filter(|p| !p.is_empty())
.unwrap_or_else(|| credentials::firmware_default_for("VNish").1);
let vnish_pass = if vnish_pass.is_empty() { "admin".to_string() } else { vnish_pass };
let (am_user, am_pass) =
credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
wx_rs::set_status_text(&format!("fetching log from {ip}..."));
let scan = match crate::log_scan::scan_log(&ip, &brand, &firmware, &vnish_pass, &am_user, &am_pass) {
Ok(s) => s,
Err(e) => {
self.set_error_indicator(&format!("log: {e}"));
wx_rs::set_status_text(&format!("log fetch failed for {ip}: {e}"));
return None;
}
};
self.clear_indicator();
wx_rs::set_status_text(&format!("{} miners", self.rows.len()));
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Miner log (API) -- {ip}"));
let root = Widget::box_sizer(true);
let summary = if scan.summary.is_empty() {
"(no summary)".to_string()
} else {
scan.summary.join("\n")
};
root.add(Widget::static_text(dlg, &summary), 0, sf::BORDER_ALL, 8);
let text = Widget::text_ctrl(dlg, true);
text.set_min_size(760, 420);
text.set_value(&scan.text);
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Close", ID_LOGVIEW_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(800, 540);
dlg.fit(dlg);
self.logview_dialog = dlg;
Some(dlg)
}
/// Confirmation before restoring aftermarket firmware to stock (round 12 #8a,
/// simplified in round 15 #11 to a plain confirm): shows exactly which miners
/// (IP + firmware) will be reverted. DESTRUCTIVE + reboots.
fn build_restore_confirm_dialog(&mut self) -> Option<Widget> {
let targets: Vec<restore::RestoreTarget> = self
.selected_rows()
.iter()
.filter(|r| firmware_is_restorable(&r.firmware))
.map(|r| restore::RestoreTarget { ip: r.ip.clone(), firmware: r.firmware.clone() })
.collect();
if targets.is_empty() {
wx_rs::set_status_text("select a VNish / LuxOS / Braiins miner to restore");
return None;
}
let n = targets.len();
let list = targets
.iter()
.map(|t| format!(" {} ({})", t.ip, t.firmware))
.collect::<Vec<_>>()
.join("\n");
self.pending_restore = targets;
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Restore to stock firmware");
let root = Widget::box_sizer(true);
// Simple confirmation (round 15 #11): the list of miners + a one-line
// question, no typed keyword and no long warning tidbit.
let msg = format!("Restore these {n} miner(s) to stock firmware?\n\n{list}");
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, "Restore to stock", ID_RESTORE_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_RESTORE_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, 180);
dlg.fit(dlg);
self.restore_dialog = dlg;
Some(dlg)
}
/// Apply the restore confirmation (round 15 #11: a plain confirm, no typed
/// keyword). Resolves the per-firmware credentials (VNish password from the
/// round 12 #13 defaults; Braiins SSH login from the saved SSH creds).
fn apply_restore_confirm(&mut self) {
let targets = std::mem::take(&mut self.pending_restore);
if targets.is_empty() {
self.restore_dialog.close(0);
return;
}
let vnish_pass = credentials::load_firmware_credentials()
.get("VNish")
.map(|(_, p)| p.clone())
.filter(|p| !p.is_empty())
.unwrap_or_else(|| credentials::firmware_default_for("VNish").1);
let vnish_pass = if vnish_pass.is_empty() { "admin".to_string() } else { vnish_pass };
let (ssh_user, ssh_pass) = credentials::load_ssh_credentials().unwrap_or_default();
let ips: Vec<String> = targets.iter().map(|t| t.ip.clone()).collect();
self.restore_dialog.close(1);
crate::logs::log(format!("restore {} miner(s) to stock", ips.len()));
self.set_op_status(&ips, "restoring…");
self.restore = Some(restore::start_restore(targets, vnish_pass, ssh_user, ssh_pass));
}
/// Drain restore-to-stock results into the status bar.
fn drain_restore(&mut self) {
let Some(h) = &self.restore else { return };
let mut done = false;
let mut oks = 0usize;
let mut fails: Vec<String> = Vec::new();
let mut op_clear: Vec<String> = Vec::new();
while let Ok(msg) = h.rx.try_recv() {
match msg {
restore::RestoreMsg::Started { .. } => {}
restore::RestoreMsg::Result { ip, ok, detail } => {
op_clear.push(ip.clone());
if ok {
oks += 1;
} else {
fails.push(format!("{ip}: {detail}"));
}
}
restore::RestoreMsg::Done { .. } => done = true,
}
}
for ip in &op_clear {
self.op_status.remove(ip);
}
if done {
self.restore = None;
self.op_status.retain(|_, v| v != "restoring…");
}
if !op_clear.is_empty() || done {
self.fill_rows();
}
// Only failures surface (bottom-right indicator); the bottom-left is
// scan-only and per-miner restore progress is in the Health column (#8).
if done && !fails.is_empty() {
self.set_error_indicator(&format!("restore: {} failed", fails.len()));
}
let _ = oks;
}
/// 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;
}
// Pass the brand (make), not the firmware family: the access probe picks
// its strategy by make (WhatsMiner :4028 token vs Antminer web digest),
// and "Stock" alone can't tell them apart (round 12 #8b).
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.map(|r| (r.ip.clone(), r.brand.clone()))
.collect();
if targets.is_empty() {
return;
}
let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
let ips: Vec<String> = targets.iter().map(|(ip, _)| ip.clone()).collect();
self.set_op_status(&ips, "checking…");
self.access_probe = Some(scan::start_access_probe(targets, creds));
}
/// 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;
let mut op_clear: Vec<String> = Vec::new();
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 }) => {
op_clear.push(ip.clone());
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;
}
}
}
for ip in &op_clear {
self.op_status.remove(ip);
}
if done {
self.op_status.retain(|_, v| v != "checking…");
}
if changed || !op_clear.is_empty() || done {
self.fill_rows();
}
if done {
self.access_probe = None;
}
// Operation progress stays out of the bottom-left scan line (round 15 #8);
// per-miner status shows in the Health column.
let _ = status;
}
/// 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> {
// Pool "+" dropdown selections (round 15 #1): the "add current" item and
// one id per dropdown entry from ID_POOL_MENU_BASE up.
if id == ID_POOL_MENU_ADD || id >= ID_POOL_MENU_BASE {
self.choose_pool_dropdown(id);
return None;
}
// Settings menu Language items (round 15 #13).
if (ID_LANG_BASE..ID_LANG_BASE + 6).contains(&id) {
self.set_language((id - ID_LANG_BASE) as usize);
return None;
}
match id {
// Settings menu items (round 15 #13).
ID_SCAN_CREDS => return Some(self.build_firmware_creds_dialog()),
ID_LOGS_OPEN => return Some(self.build_logs_dialog()),
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_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_VIEW_LOG => return self.build_log_view_dialog(),
ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(),
ID_CTX_POOLS => return self.build_pools_dialog(),
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_targets = ips.clone();
self.set_op_status(&ips, "flashing…");
self.action = Some(scan::start_firmware_flash_action(ips, image));
wx_rs::set_status_text(&msg);
}
}
/// Build (but do not show) the Credentials dialog (round 13 #2): a single
/// place for every login the scanner uses. The top row is the optional global
/// "all firmwares" login (applied to any firmware without an override); below
/// it is one row per firmware in the asic-rs registry, each prefilled from the
/// saved override or the firmware's shipped default. Editing a firmware row
/// away from its default makes it an override; setting it back clears it.
/// (Formerly a global-login dialog with the per-firmware editor behind a
/// sub-button.)
fn build_firmware_creds_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Credentials");
let root = Widget::box_sizer(true);
// Global "all firmwares" login. Never re-display the saved password in
// plaintext: leave it blank, and a blank password on Save keeps whatever
// is already stored (see apply_firmware_creds_save).
let (saved_user, saved_pass) = credentials::load_credentials().unwrap_or_default();
let g_hint = if saved_pass.is_empty() {
"All firmwares"
} else {
"All firmwares (password saved; blank keeps it)"
};
let grow = Widget::box_sizer(false);
let glabel = Widget::static_text(dlg, g_hint);
glabel.set_min_size(150, -1);
grow.add(glabel, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let user_input = Widget::text_ctrl(dlg, false);
user_input.set_min_size(150, -1);
user_input.set_value(&saved_user);
grow.add(user_input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_input = Widget::text_ctrl(dlg, false);
pass_input.set_min_size(150, -1);
grow.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add_sizer(grow, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
self.creds_user_input = user_input;
self.creds_pass_input = pass_input;
// Column headers.
let head = Widget::box_sizer(false);
let h_fw = Widget::static_text(dlg, "Firmware");
h_fw.set_min_size(150, -1);
head.add(h_fw, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let h_user = Widget::static_text(dlg, "Username");
h_user.set_min_size(150, -1);
head.add(h_user, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
head.add(Widget::static_text(dlg, "Password"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add_sizer(head, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
let saved = credentials::load_firmware_credentials();
let mut rows: Vec<(String, Widget, Widget)> = Vec::new();
for fw in asic_rs::factory::default_firmware_registry() {
let name = fw.to_string();
let (def_user, def_pass) = credentials::firmware_default_for(&name);
let (user, pass) = saved
.get(&name)
.cloned()
.unwrap_or((def_user, def_pass));
let row = Widget::box_sizer(false);
let label = Widget::static_text(dlg, &name);
label.set_min_size(150, -1);
row.add(label, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let user_ctrl = Widget::text_ctrl(dlg, false);
user_ctrl.set_min_size(150, -1);
user_ctrl.set_value(&user);
row.add(user_ctrl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_ctrl = Widget::text_ctrl(dlg, false);
pass_ctrl.set_min_size(150, -1);
pass_ctrl.set_value(&pass);
row.add(pass_ctrl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add_sizer(row, 0, sf::EXPAND | sf::BORDER_TOP, 4);
rows.push((name, user_ctrl, pass_ctrl));
}
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Save", ID_FWCREDS_SAVE), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Reset to defaults", ID_FWCREDS_RESET), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_FWCREDS_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(520, 200);
dlg.fit(dlg);
self.fwcreds_dialog = dlg;
self.fwcreds_rows = rows;
dlg
}
/// Persist the Credentials dialog (round 13 #2): the global "all firmwares"
/// login (top row) plus the per-firmware overrides. A firmware row that
/// differs from its shipped default becomes an override; a row equal to the
/// default clears it.
fn apply_firmware_creds_save(&mut self) {
// Global login first. A blank password means "keep the saved password"
// (the field is never pre-filled in plaintext); a blank user AND password
// clears the global login entirely.
let g_user = self.creds_user_input.get_value();
let mut g_pass = self.creds_pass_input.get_value();
if g_pass.is_empty() {
if let Some((_, saved_pass)) = credentials::load_credentials() {
g_pass = saved_pass;
}
}
let global_result = if g_user.is_empty() && g_pass.is_empty() {
credentials::clear_credentials()
} else {
credentials::save_credentials(&g_user, &g_pass)
};
if let Err(e) = global_result {
wx_rs::set_status_text(&format!("failed to save global login: {e}"));
return;
}
// Per-firmware overrides.
let mut map: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
let user = user_ctrl.get_value();
let pass = pass_ctrl.get_value();
let default = credentials::firmware_default_for(name);
if (user.clone(), pass.clone()) != default {
map.insert(name.clone(), (user, pass));
}
}
match credentials::save_firmware_credentials(&map) {
Ok(()) => {
self.fwcreds_dialog.close(1);
let n = map.len();
wx_rs::set_status_text(&format!(
"credentials saved ({n} firmware override{})",
if n == 1 { "" } else { "s" }
));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save credentials: {e}")),
}
}
/// Reset every firmware row to its shipped default and clear the global login,
/// dropping all saved overrides.
fn apply_firmware_creds_reset(&mut self) {
self.creds_user_input.set_value("");
self.creds_pass_input.set_value("");
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
let (user, pass) = credentials::firmware_default_for(name);
user_ctrl.set_value(&user);
pass_ctrl.set_value(&pass);
}
let per_fw = credentials::clear_firmware_credentials();
let global = credentials::clear_credentials();
match per_fw.and(global) {
Ok(()) => wx_rs::set_status_text("credentials reset to defaults"),
Err(e) => wx_rs::set_status_text(&format!("failed to reset 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;
// 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). The follow-up refresh
// overwrites each miner's Health op-status ("restarting…" ->
// "refreshing…"); with no refresh we clear it back to icons (#4).
let targets = std::mem::take(&mut self.action_targets);
if !was_flash && !targets.is_empty() {
self.start_refresh(targets);
} else {
for ip in &targets {
self.op_status.remove(ip);
}
self.fill_rows();
}
}
// Apply the captured indicator now the `h` borrow is gone. Failures still
// surface in the bottom-right indicator; the bottom-left stays scan-only
// and per-miner progress is in the Health column (round 15 #8).
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),
}
}
let _ = status;
}
/// Drain a running per-IP refresh's results into the rows it touches 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;
// IPs whose per-miner refresh completed this tick: clear their Health
// op-status back to icons (round 14 #4).
let mut op_clear: Vec<String> = Vec::new();
loop {
match h.rx.try_recv() {
Ok(scan::RefreshMsg::Started { total }) => {
status = Some(format!("refreshing 0/{total} miner(s)..."));
}
Ok(scan::RefreshMsg::Row(row)) => {
op_clear.push(row.ip.clone());
row.upsert_into(&mut self.rows);
changed = true;
}
Ok(scan::RefreshMsg::Failed { ip, detail }) => {
op_clear.push(ip.clone());
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;
}
}
}
for ip in &op_clear {
self.op_status.remove(ip);
}
if finished {
self.refresh = None;
// Any stragglers still marked "refreshing…" revert to icons.
self.op_status.retain(|_, v| v != "refreshing…");
}
// Refresh progress stays in the Health column, not the scan line (#8).
let _ = status;
if changed || !op_clear.is_empty() || finished {
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();
crate::logs::log(format!("scan complete: {} miner(s) found", self.rows.len()));
// 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_access_probe();
self.drain_restore();
// The bottom-left status is for the scan only (round 15 #8): per-miner
// operation progress lives in the Health column, so operations no longer
// hold or overwrite this line -- only an active scan does.
if self.scanning {
return; // status already shows scan progress
}
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.scan_timeout_secs));
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 if col == Column::Health {
// The Health header cycles overall health, then each component facet
// (power, fans, hashboards), each asc then desc, then unsorted, so the
// fleet can be ordered by whichever component matters (round 13 #3).
match self.view.sort {
Some((Column::Health, true)) => Some((Column::Health, false)),
Some((Column::Health, false)) => Some((Column::HealthPower, true)),
Some((Column::HealthPower, true)) => Some((Column::HealthPower, false)),
Some((Column::HealthPower, false)) => Some((Column::HealthFans, true)),
Some((Column::HealthFans, true)) => Some((Column::HealthFans, false)),
Some((Column::HealthFans, false)) => Some((Column::HealthBoards, true)),
Some((Column::HealthBoards, true)) => Some((Column::HealthBoards, false)),
Some((Column::HealthBoards, false)) => None,
_ => Some((Column::Health, 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 = crate::i18n::t(c.title());
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" })
}
// Health facet sorts are pseudo-columns shown on the Health header
// (round 13 #3): a short tag names the active component (Pwr/Fan/
// Brd) beside the chevron, since a native header can't carry an SVG.
Some((Column::HealthPower, asc)) if *c == Column::Health => {
title.push_str(if asc { " Pwr ^" } else { " Pwr v" })
}
Some((Column::HealthFans, asc)) if *c == Column::Health => {
title.push_str(if asc { " Fan ^" } else { " Fan v" })
}
Some((Column::HealthBoards, asc)) if *c == Column::Health => {
title.push_str(if asc { " Brd ^" } else { " Brd 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);
// The range-format help moved from an inline block to a tooltip on the
// text box (round 15 #10).
let edit = Widget::text_ctrl(dlg, true);
edit.set_value(&scan::load_ranges().join("\n"));
edit.set_tool_tip(
"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(edit, 1, sf::EXPAND | sf::BORDER_ALL, 6);
// Auto-rescan interval (seconds; 0 = off) and per-miner scan timeout.
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_edit.set_min_size(60, -1);
auto_row.add(auto_edit, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
// Per-miner scan timeout (round 14 #2): how long a responding miner is
// given to identify + return data before the scan gives up on it.
auto_row.add_stretch(1);
let to_lbl = Widget::static_text(dlg, "Timeout (s):");
auto_row.add(to_lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let to_edit = Widget::text_ctrl(dlg, false);
to_edit.set_value(&self.scan_timeout_secs.to_string());
to_edit.set_min_size(60, -1);
auto_row.add(to_edit, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(auto_row, 0, sf::EXPAND | 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;
self.ranges_timeout = to_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);
}
// Save the per-miner scan timeout (round 14 #2), clamped to >= 1s.
if let Ok(secs) = self.ranges_timeout.get_value().trim().parse::<u64>() {
self.scan_timeout_secs = secs.max(1);
let _ = scan::save_scan_timeout(self.scan_timeout_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.
/// Export the full scan data to a CSV the user picks (round 15 #14). Every
/// scanned data point is exported, one value per cell -- more complete and
/// machine-readable than the on-screen table.
fn apply_export(&mut self) {
if self.rows.is_empty() {
wx_rs::set_status_text("nothing to export yet -- run a scan first");
return;
}
let Some(path) = Widget::save_file_dialog(
Widget::main_frame(),
"Export scan data",
"alkane-export.csv",
"CSV files (*.csv)|*.csv|All files (*.*)|*.*",
) else {
return; // cancelled
};
let csv = crate::export::rows_to_csv(&self.rows);
match std::fs::write(&path, csv) {
Ok(()) => {
crate::logs::log(format!("exported {} miner(s) to {path}", self.rows.len()));
wx_rs::set_status_text(&format!("exported {} miner(s) to {path}", self.rows.len()))
}
Err(e) => self.set_error_indicator(&format!("export failed: {e}")),
}
}
/// Build + queue the Settings popup menu (round 15 #13): Credentials, a
/// Language submenu, and the Logs page.
fn open_settings_menu(&mut self) {
let menu = Widget::menu_new();
menu.menu_append(ID_SCAN_CREDS, &crate::i18n::t("Credentials"));
menu.menu_append_separator();
let lang_menu = Widget::menu_new();
let cur = crate::i18n::current();
for (i, l) in crate::i18n::Lang::all().iter().enumerate() {
// A bullet marks the active language.
let mark = if *l == cur { "\u{2022} " } else { " " };
lang_menu.menu_append(ID_LANG_BASE + i as i32, &format!("{mark}{}", l.label()));
}
menu.menu_append_submenu(&crate::i18n::t("Language"), lang_menu);
menu.menu_append_separator();
menu.menu_append(ID_LOGS_OPEN, &crate::i18n::t("Logs"));
self.pending_popup = Some((Widget::main_frame(), menu));
}
/// Apply a language change (round 15 #13): re-label the tracked toolbar/KPI
/// widgets and re-title the columns; dialogs pick up the language when opened.
fn set_language(&mut self, idx: usize) {
let Some(l) = crate::i18n::Lang::all().get(idx).copied() else { return };
crate::i18n::set(l);
crate::logs::log(format!("language set to {}", l.label()));
for (w, key) in &self.l10n_labels {
w.set_label(&crate::i18n::t(key));
}
self.rebuild_table();
self.refresh_kpis();
}
/// Build (but do not show) the Logs page (round 15 #13): the in-app activity
/// log with Refresh / Clear / Close.
fn build_logs_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &crate::i18n::t("Logs"));
let root = Widget::box_sizer(true);
let text = Widget::text_ctrl(dlg, true);
text.set_value(&crate::logs::dump());
text.set_min_size(620, 360);
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 6);
let btns = Widget::box_sizer(false);
btns.add(Widget::button(dlg, "Refresh", ID_LOGS_REFRESH), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Clear", ID_LOGS_CLEAR), 0, sf::BORDER_ALL, 6);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Close", ID_LOGS_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(660, 420);
dlg.fit(dlg);
self.logs_dialog = dlg;
self.logs_text = text;
dlg
}
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);
// Short, two-line hint so it doesn't force the dialog wide (round 13 #1).
let hint = Widget::static_text(
dlg,
"Check to show a column; drag rows to reorder (IP stays first).\nDrag or Shift/Ctrl-click to select several; Ctrl+A selects all.",
);
root.add(hint, 0, sf::BORDER_ALL, 6);
// Sort the rows in the picker (round 13 #1): Alphabetical by title, or
// grouped into Categories. These reorder the picker only; nothing applies
// until OK.
let sortrow = Widget::box_sizer(false);
sortrow.add(
Widget::static_text(dlg, "Sort:"),
0,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
6,
);
sortrow.add(Widget::button(dlg, "Alphabetical", ID_COLS_ALPHA), 0, sf::BORDER_RIGHT, 6);
sortrow.add(Widget::button(dlg, "Categories", ID_COLS_CATEGORIES), 0, sf::BORDER_RIGHT, 6);
root.add_sizer(sortrow, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_BOTTOM, 4);
// 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);
// Keep the picker compact: the row column is 190px, so ~340px is enough
// (round 13 #1). fit() sizes to content but never below this floor.
dlg.set_min_size(360, 480);
dlg.fit(dlg);
self.columns_dialog = dlg;
self.columns_list = list;
dlg
}
/// Reorder the column picker's rows (round 13 #1) by title (Alphabetical) or
/// by category group, preserving each row's checked state. Applies to the
/// picker only; the view changes on OK.
fn apply_columns_sort(&self, by_category: bool) {
let base = Self::selectable_columns();
let titles: Vec<&str> = base.iter().map(|c| c.title()).collect();
let mut pairs: Vec<(usize, bool)> = self
.columns_list
.reorder_get_order()
.iter()
.map(|&e| if e < 0 { ((!e) as usize, false) } else { (e as usize, true) })
.collect();
if by_category {
// Category rank, then registry order within the group (idx order).
pairs.sort_by_key(|&(idx, _)| {
let (rank, _) = base.get(idx).map(|c| c.category()).unwrap_or((u8::MAX, ""));
(rank, idx)
});
} else {
pairs.sort_by(|&(a, _), &(b, _)| {
let ta = base.get(a).map(|c| c.title()).unwrap_or("");
let tb = base.get(b).map(|c| c.title()).unwrap_or("");
ta.to_lowercase().cmp(&tb.to_lowercase())
});
}
let order: Vec<i32> = pairs
.iter()
.map(|&(idx, checked)| if checked { idx as i32 } else { !(idx as i32) })
.collect();
self.columns_list.reorder_set_order(&order, &titles);
}
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). A sort-only
// pseudo-column (relative hashrate, a Health facet) maps to its display
// column for this check so it survives as long as that column is shown.
if let Some((c, _)) = self.view.sort {
let home = Self::sort_home_col(c);
if home != Column::Ip && !self.view.visible.contains(&home) {
self.view.sort = None;
}
}
self.columns_dialog.close(1);
self.rebuild_table();
}
/// Map a sort-only pseudo-column to the visible column that hosts its sort
/// (round 11 #16 / round 13 #3); every other column maps to itself.
fn sort_home_col(c: Column) -> Column {
match c {
Column::HashrateRel => Column::Hashrate,
Column::HealthPower | Column::HealthFans | Column::HealthBoards => Column::Health,
other => other,
}
}
/// 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_EXPORT => self.apply_export(),
ID_SETTINGS => self.open_settings_menu(),
ID_LOGS_REFRESH => self.logs_text.set_value(&crate::logs::dump()),
ID_LOGS_CLEAR => {
crate::logs::clear();
self.logs_text.set_value("");
}
ID_LOGS_CLOSE => self.logs_dialog.close(1),
ID_COLUMNS => return Some(self.build_columns_dialog()),
ID_COLUMNS_OK => self.apply_columns(),
ID_COLUMNS_CANCEL => self.columns_dialog.close(0),
ID_COLS_ALPHA => self.apply_columns_sort(false),
ID_COLS_CATEGORIES => self.apply_columns_sort(true),
ID_PRESETS => return Some(self.build_presets_dialog()),
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_firmware_creds_dialog()),
ID_FWCREDS_SAVE => self.apply_firmware_creds_save(),
ID_FWCREDS_RESET => self.apply_firmware_creds_reset(),
ID_FWCREDS_CANCEL => self.fwcreds_dialog.close(0),
ID_LOGVIEW_CLOSE => self.logview_dialog.close(1),
ID_RESTORE_OK => self.apply_restore_confirm(),
ID_RESTORE_CANCEL => {
self.pending_restore.clear();
self.restore_dialog.close(0);
}
ID_POOLS_OK => self.apply_pools(),
ID_POOLS_CANCEL => self.pools_dialog.close(0),
// Pool-field "+" dropdown buttons (round 15 #1).
id if (ID_POOL_PLUS_BASE..ID_POOL_PLUS_BASE + 12).contains(&id) => {
self.open_pool_dropdown((id - ID_POOL_PLUS_BASE) as usize);
}
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::Health | Column::Hashboards | Column::Locked | Column::Light | Column::Status) {
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::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);
let health_col = cols.iter().position(|c| *c == Column::Health);
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:?}"));
}
// Health column (round 13 #3): the power (bolt) and control-board (brain)
// icons are always emitted, plus a chip icon per hashboard for a mining
// miner; verify the sentinels are present.
if let (Some(hc), Some(row)) = (health_col, find("10.255.1.166")) {
let raw = t.dvlc_get_cell(row, hc).unwrap_or_default();
check("Health column renders the power + control-board + chip sentinels",
raw.contains('\u{000C}') && raw.contains('\u{000E}') && raw.contains('\u{0010}'),
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, &[])), "");
}
}