Files
alkane-toolkit/crates/alkane-gui/src/ui.rs
T
noahandClaude Opus 4.8 6e785275da
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 12m59s
feat(gui): two-choice restore, dialogs-during-scan, creds-from-settings
Restore-to-stock dialog overhaul (issues #46, #47, #48, #51): a two-source
restore -- the board's on-board stock backup (checkbox, auto-detected via the
merged alkane-flash onboard_stock_backup_present and greyed out with
set_enabled when absent) or a Bitmain stock firmware file picked with a Browse
button (OTA .tar.gz or SD .zip, any X17-series model). The alkane root login
comes from Settings (no per-dialog password field); on-board restore uses the
new stock_ops::start_restore_onboard over DSH's restore_from_onboard_backup.

Install dialog: password field removed too (#46); the login comes from Settings.

Dialogs during scan (#43): install/uninstall dialogs open and can be prepared
while a scan runs (new flash_busy gate); the scan is stopped only when the
operation actually starts (stop_scan_for_op) so the two never touch a board at
once.

Bug report (#50): the always-present "Open issue" button is gone; filing turns
it into a clickable "View issue #N" link.

wx-rs: add set_enabled (grey out a control); captured as patch 0013. Merges
DSH's alkane-flash on-board backup/restore method (sealed in stock_method.rs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-13 13:53:28 -06:00

6875 lines
289 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::alkane_detect;
use crate::credentials;
use crate::model::*;
use crate::restore;
use crate::scan::{self, ScanMsg};
use crate::stock_ops::{self, AfwSource, StockMsg};
use alkane_artifacts::fetch::{self, ReleaseInfo, ReleaseSource};
use asic_rs::core::data::firmware::FirmwareImage;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use wx_rs::{sizer_flags as sf, Widget, WxEvent, WxEventKind};
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;
// Bug report / feature request dialog (toolbar, between Export and Settings).
pub const ID_BUG_REPORT: i32 = 111;
const ID_REPORT_SEND: i32 = 240;
const ID_REPORT_CLOSE: i32 = 241;
const ID_REPORT_OPEN: i32 = 242;
const ID_REPORT_KIND: i32 = 243;
const ID_LANG_BASE: i32 = 790; // one id per language (790 + Lang index); reserves 790..790+Lang::all().len()
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;
// Export column-picker dialog (round 19 #6).
const ID_EXPORT_OK: i32 = 207;
const ID_EXPORT_CANCEL: i32 = 208;
const ID_EXPORT_ALL: i32 = 209;
const ID_EXPORT_NONE: i32 = 211;
// 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_HASHRATE: i32 = 740; // Set hashrate target (round 17 C)
const ID_CTX_PRESET: i32 = 741; // Set firmware profile/preset (round 18 / G3)
const ID_CTX_RESTART: i32 = 729;
// Round 17 B: timezone / change-password / factory-reset config actions.
const ID_CTX_TIMEZONE: i32 = 737;
const ID_CTX_PASSWORD: i32 = 738;
const ID_CTX_FACTORY_RESET: i32 = 739;
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;
// Alkane-OS self-contained install/uninstall (stock_ops.rs): put our first image
// onto a board on stock, and return an alkane board to stock, both via the
// toolkit's own compiled-in network-only engine. Typed-FLASH confirmation.
const ID_CTX_INSTALL_ALKANE: i32 = 770;
const ID_CTX_UNINSTALL_ALKANE: i32 = 771;
const ID_CTX_UPDATE_ALKANE: i32 = 772;
const ID_INSTALL_OK: i32 = 1006;
const ID_INSTALL_CANCEL: i32 = 1007;
const ID_INSTALL_RELEASE_CHOICE: i32 = 1008;
// Browse for a local .afw to install instead of a scanned Gitea release.
const ID_INSTALL_BROWSE: i32 = 1011;
// Reload the release picker from the repo typed in the install dialog.
const ID_INSTALL_RELOAD: i32 = 1012;
// Toolbar toggle between the fleet table and the live activity-log view.
const ID_LOG_TOGGLE: i32 = 1013;
const ID_UNINSTALL_OK: i32 = 1009;
const ID_UNINSTALL_CANCEL: i32 = 1010;
// Browse for a stock firmware file in the uninstall/restore dialog.
const ID_UNINSTALL_BROWSE: i32 = 1014;
// Pool-preset manager dialog (round 18 #8b): edit the whole saved list at once.
// NB: 790-795 belong to the language menu (ID_LANG_BASE + Lang index), so these
// live in a separate high block to avoid an id collision (round 18 #12).
const ID_POOL_PRESETS_SAVE: i32 = 1001;
const ID_POOL_PRESETS_CANCEL: i32 = 1002;
// Firmware profile/preset selector dialog (round 18 / roadmap G3).
const ID_FWPRESET_OK: i32 = 1003;
const ID_FWPRESET_CANCEL: i32 = 1004;
const ID_FWPRESET_CHOICE: i32 = 1005;
// 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 new..." -> opens the preset-manager window (round 18 #8b)
const ID_POOL_MENU_BASE: i32 = 820; // one id per dropdown entry (820 + index)
// Value-prompt dialog for power-limit / tuning-percent / timezone / password.
const ID_ACTION_OK: i32 = 740;
const ID_ACTION_CANCEL: i32 = 741;
/// Which value the shared text/number prompt is collecting (round 17 B).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PromptKind {
Power,
HashRateTarget,
Tuning,
Timezone,
Password,
}
// 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;
// Auto-size every column at once (round 19 #4).
const ID_HDR_AUTOSIZE_ALL: i32 = 767;
// 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;
/// The scan/drain timer fires this often (ms). A fast tick drains the scan channel
/// several times a second so the progress counter climbs smoothly instead of
/// jumping ~1%/s; the once-per-second scheduler work runs every `TICKS_PER_SEC`.
const TICK_MS: i32 = 200;
const TICKS_PER_SEC: u64 = 1000 / TICK_MS as u64;
// 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),
/// Backgrounds coloured text is drawn on (window, zebra row, KPI card).
/// `text()` keeps every computed text colour readable on all of them.
text_bgs: Vec<(u8, u8, u8)>,
}
/// WCAG relative luminance of an sRGB colour.
fn wcag_luminance(c: (u8, u8, u8)) -> f64 {
let ch = |v: u8| {
let v = v as f64 / 255.0;
if v <= 0.03928 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * ch(c.0) + 0.7152 * ch(c.1) + 0.0722 * ch(c.2)
}
/// WCAG contrast ratio of two colours (1.0 to 21.0).
fn contrast_ratio(a: (u8, u8, u8), b: (u8, u8, u8)) -> f64 {
let (la, lb) = (wcag_luminance(a), wcag_luminance(b));
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}
/// Minimum contrast for text: WCAG AA for normal-size text.
const MIN_TEXT_CONTRAST: f64 = 4.5;
/// Minimum contrast for icons and other graphics (WCAG non-text contrast).
const MIN_ICON_CONTRAST: f64 = 3.0;
/// `c`, darkened (on light backgrounds) or lightened (on dark ones) just
/// enough to reach MIN_TEXT_CONTRAST against every background in `bgs`,
/// keeping its hue. Colours that already pass are returned unchanged.
fn readable(c: (u8, u8, u8), bgs: &[(u8, u8, u8)]) -> (u8, u8, u8) {
readable_at(c, bgs, MIN_TEXT_CONTRAST)
}
/// `readable` with an explicit minimum ratio (MIN_ICON_CONTRAST for icons).
fn readable_at(c: (u8, u8, u8), bgs: &[(u8, u8, u8)], min: f64) -> (u8, u8, u8) {
let passes = |c| bgs.iter().all(|&bg| contrast_ratio(c, bg) >= min);
if bgs.is_empty() || passes(c) {
return c;
}
let mean = bgs.iter().map(|&bg| wcag_luminance(bg)).sum::<f64>() / bgs.len() as f64;
let target = if mean > 0.18 {
(0, 0, 0)
} else {
(255, 255, 255)
};
for step in 1..=50 {
let d = tint_toward(c, target, step as f64 / 50.0);
if passes(d) {
return d;
}
}
target
}
impl Palette {
/// A text colour adjusted to stay readable on this theme's backgrounds.
fn text(&self, c: (u8, u8, u8)) -> (u8, u8, u8) {
readable(c, &self.text_bgs)
}
}
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/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);
pal.text(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" => (223, 62, 102), // pinkish-red (Bixbit logo)
"epic" | "umc os" | "umcos" | "umc" => (70, 160, 225), // ePIC PowerPlay / UMC OS: light blue
"hive" | "hiveos" | "hiveon" => (228, 112, 24), // Hiveon: darker logo 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) {
pal.text(tint_toward(
pal.accent,
pal.red,
((temp_c - 40.0) / 50.0).clamp(0.0, 1.0),
))
}
/// Build the segment-encoded cell for a combined actual/expected column
/// (Hashrate/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<Segment> = Vec::with_capacity(temps.len() * 2 - 1);
for (i, &t) in temps.iter().enumerate() {
if i > 0 {
segs.push((None, " / ".to_string()));
}
// A 0.0 slot means "this board reported no temperature"; show a dash in its
// position so the remaining boards stay aligned (round 18 #12).
if t > 0.0 {
segs.push((Some(temp_color(pal, t)), format!("{t:.0}")));
} else {
segs.push((None, "-".to_string()));
}
}
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_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}";
// 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))
}
/// 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())])
}
/// An indicative percent for an install/restore phase line, so the Health cell
/// can show a progress bar instead of a static "installing...". Phase-based (the
/// engine streams named phases, not a true byte count), monotonic within a run.
fn stock_progress_pct(msg: &str) -> u8 {
let m = msg.to_ascii_lowercase();
if m.contains("acquir") || m.contains("using local") {
15
} else if m.contains("verify") {
35
} else if m.contains("install") || m.contains("restor") || m.contains("writ") {
70
} else {
50
}
}
/// A fixed-width ASCII progress bar, e.g. "[######----]", for a 0..=100 percent.
fn ascii_bar(pct: u8) -> String {
let width = 10usize;
let filled = (pct as usize * width / 100).min(width);
format!("[{}{}]", "#".repeat(filled), "-".repeat(width - filled))
}
/// A read-only flash-plan summary for a local `.afw`: its tier and which regions
/// it overwrites (U-Boot / Kernel / Userspace), from the bundle's own manifest.
/// Shown in the install dialog when a file is picked so the operator sees exactly
/// what the flash touches before starting.
fn afw_plan_text(path: &str, expect_board: &str) -> String {
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
// Verify against the install target's board (review #6): a file for another
// board then surfaces as an error here instead of showing a plausible plan
// that start_install would later reject.
let opts = VerifyOptions {
allow_unsigned: true,
expect_board: Some(expect_board.to_string()),
};
match verify_afw(std::path::Path::new(path), &opts) {
Ok(v) => {
let p = v.manifest.flash_plan();
let mark = |b: bool| if b { "[x]" } else { "[ ]" };
format!(
"Flash plan: tier {} (board {}). Overwrites:\n {} U-Boot{}\n {} Kernel\n {} Userspace (rootfs)",
p.tier,
v.manifest.board,
mark(p.writes_uboot),
if p.writes_uboot {
""
} else {
" -- preserved"
},
mark(p.writes_kernel),
mark(p.writes_userspace),
)
}
Err(e) => format!("Could not read flash plan from this file: {e}"),
}
}
/// 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 {
use crate::model::CompHealth;
let mut segs: Vec<Segment> = Vec::new();
// On a paused/stopped miner, a component that is off *because* the miner is
// halted is expected, not a fault, so it reads blue (paused) instead of red.
// But this only applies where "not working" is a consequence of the pause:
// - Hashboards: idle (not hashing) is exactly what pausing does -> blue when
// paused (any detected board; an undetected one stays grey). Round 19 #19.
// - Fans: blue ONLY when actually stopped (0 RPM -> Down); a fan still
// spinning stays green/amber -- pausing doesn't necessarily stop the fans.
// - Control board + PSU: still running / powered, so they keep their true
// health (green when fine) even while paused -- never forced blue.
let paused = r.paused;
let board_col = |h: CompHealth| {
if paused && h != CompHealth::Unreachable {
pal.accent
} else {
health_color(pal, h)
}
};
let fan_col = |h: CompHealth| {
if paused && h == CompHealth::Down {
pal.accent
} else {
health_color(pal, h)
}
};
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(fan_col(*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(board_col(*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)
}
/// 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,
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::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;
let mut p = 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)
},
text_bgs: Vec::new(),
};
// Every coloured text must read on the window, the zebra rows and the
// KPI cards in both themes; tune the fixed hues to those backgrounds.
p.text_bgs = vec![win, p.zebra, p.card_bg];
p.label = p.text(p.label);
p.green = p.text(p.green);
p.amber = p.text(p.amber);
p.red = p.text(p.red);
p.accent = p.text(p.accent);
p
}
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>,
// Set when a scan streamed new rows this drain; flushed by tick() at most once
// per second (or immediately once the scan ends) so the full table refill runs
// ~1 Hz during a scan instead of every fast tick (round 18 #12).
rows_dirty: bool,
// The columns the wxDataViewCtrl was actually built with, in creation order.
// fill_rows/header_click/reorder index the widget through table_columns() and
// assume it stays in lockstep; with auto-hide-empty on, a scan can change which
// columns are non-empty, so fill_rows watches for a mismatch and rebuilds
// rather than render against stale columns (round 18 #12).
built_columns: Vec<crate::model::Column>,
table_parent: Widget,
// Live log view: a multiline control that fills the table area when toggled
// on, showing the toolkit activity log. The toggle button flips its label.
log_view: Widget,
log_toggle_btn: Widget,
showing_log: bool,
log_shown_len: usize,
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,
// True when the user explicitly Stopped the scan (as opposed to Paused the
// auto-rescan loop). Distinguishes the idle status line "Scan Stopped" from
// "Scan Paused"; cleared when a scan starts (round 19 #17).
scan_stopped: bool,
auto_secs: u64,
// Per-miner scan timeout in seconds (round 14 #2).
scan_timeout_secs: u64,
countdown: u64,
/// Counts fast timer ticks; the once-per-second scheduler runs every
/// `TICKS_PER_SEC` of these (the drains run every tick for smooth progress).
tick_accum: 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_kind: PromptKind,
action_total: usize,
action_done: usize,
// IPs the current config action targets, re-probed after it completes so the
// table reflects the change (e.g. the identify light toggling).
action_targets: Vec<String>,
// A new password from an in-flight ChangePassword action, applied to the saved
// credentials once the action succeeds so the toolkit keeps reaching the miners
// it just changed (round 18 #12).
pending_password_update: Option<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>,
// IPs of the install currently in flight, so a successful install can arm a
// post-install alkane verification for exactly those boards.
install_targets: HashSet<String>,
// Ticks (1 s each) until the next post-install alkane re-probe, so boards are
// verified on a fixed cadence even when auto-scan is off (review #2).
verify_cooldown: u16,
// After a successful install a board reboots into alkane; the next scan can
// still catch it mid-reboot answering as stock. Each awaited IP maps to the
// number of scan rounds left to confirm alkane before giving up; while an IP
// waits, a non-alkane row for it is suppressed so the table never flickers to
// stock (the operator sees "verifying alkane..." instead). Issue: post-install
// the row re-scanned as stock before finally showing alkane.
installed_awaiting: HashMap<String, u8>,
// 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,
ssh_user_input: Widget,
ssh_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>,
// In-flight background log fetch (round 18 #12): the miner IP plus a channel
// the worker thread sends the fetched log (or an error) on, so the API log
// fetch never blocks the UI thread. Drained in tick(); builds the viewer when
// it lands.
logfetch: Option<(
String,
std::sync::mpsc::Receiver<Result<crate::log_scan::LogScan, String>>,
)>,
// The API log viewer dialog (round 12 #12).
logview_dialog: Widget,
// Settings > Logs page (round 15 #13).
logs_dialog: Widget,
logs_text: Widget,
// Bug report dialog (bug_report.rs): its controls, the send in flight and
// the last filed issue's link.
report_dialog: Widget,
report_kind: Widget,
report_text: Widget,
report_log: Widget,
report_status: Widget,
// After a report is filed this button becomes the clickable "issue #N" link;
// hidden until then (issue #50: no always-present Open-issue button).
report_open_btn: Widget,
report_rx: Option<std::sync::mpsc::Receiver<Result<crate::bug_report::Filed, String>>>,
report_url: Option<String>,
// Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog.
restore: Option<restore::RestoreHandle>,
restore_dialog: Widget,
pending_restore: Vec<restore::RestoreTarget>,
// Alkane-OS self-contained install/uninstall (stock_ops.rs): one background job
// (either direction) + the two typed-confirm dialogs and the state captured
// when a dialog opens (the scanned release list, target IPs, target board).
stock_op: Option<stock_ops::StockHandle>,
install_dialog: Widget,
install_release_choice: Widget,
install_unsigned_check: Widget,
install_releases: Vec<ReleaseInfo>,
install_ips: Vec<String>,
install_board: String,
// True when the open install dialog is an in-place Update (an already-alkane
// board) rather than a from-stock install: the worker then refuses a
// bootloader-writing (tier-3) bundle so "BOOT.bin is never written" holds
// (review #1).
install_is_update: bool,
// A local .afw picked with the Browse button, used in place of a Gitea
// release when set; the read-only label beside the button shows it.
install_local_path: Option<String>,
install_local_label: Widget,
// A read-only flash-plan checklist (tier + which regions are overwritten),
// filled from a picked local .afw's manifest.
install_plan_label: Widget,
// The release repo (owner/repo) the picker scans; defaults to
// blueflare/alkane-os, editable + reloadable to any compatible repo.
install_repo_input: Widget,
uninstall_dialog: Widget,
uninstall_firmware_input: Widget,
// Restore-to-stock source: the board's on-board stock backup (checkbox,
// greyed when absent) vs the firmware file below.
uninstall_onboard_check: Widget,
uninstall_onboard_available: bool,
uninstall_ips: Vec<String>,
// 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
// The pool-preset manager dialog (round 18 #8b): a multiline editable list of
// the saved values for one field, reached from the "+" menu's "Manage saved".
pool_presets_dialog: Widget,
pool_presets_input: Widget,
pool_presets_field: crate::pool_prefs::PoolField,
// Firmware profile/preset selector (round 18 / roadmap G3): a Choice of the
// selected miner's presets, the names behind each entry, and the target IPs
// captured when the dialog opened.
fw_preset_dialog: Widget,
fw_preset_choice: Widget,
fw_preset_names: Vec<String>,
fw_preset_ips: Vec<String>,
// 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,
/// Scan-concurrency (in-flight probes) input in the ranges dialog (round 19 #25).
ranges_concurrency: Widget,
columns_dialog: Widget,
columns_list: Widget,
/// The columns-dialog "hide empty columns" checkbox, read at Apply.
columns_hide_empty_cb: Widget,
/// Export column-picker dialog + its checklist (round 19 #6).
export_dialog: Widget,
export_list: 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));
// (mk_card's borrow of kpi_cards ends here at its last use, freeing kpi_cards
// for the App below.)
// 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.
// The icon colours are kept to at least 3:1 against this theme's button
// face (the fixed hues alone were about 2:1 on light buttons). Native
// buttons do not all paint the system button-face colour (macOS draws
// #ebebeb on a white window), so also check the window colour and a shade
// 20 steps toward the opposite end.
let win = wx_rs::system_color(0);
let shade = if luminance(win) < 128.0 { 20 } else { -20 };
let face = [wx_rs::system_color(3), win, nudge(win, shade)];
let icon = |c| readable_at(c, &face, MIN_ICON_CONTRAST);
let play_btn = Widget::media_button(panel, ID_PLAY, 0, icon((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, icon((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, icon((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);
let _report_btn = tbtn("Bug report", ID_BUG_REPORT);
// The old Credentials button is now a Settings menu (round 15 #13).
let _creds_btn = tbtn("Settings", ID_SETTINGS);
// Toggle between the fleet table and the live activity log.
let log_toggle_btn = tbtn("Log", ID_LOG_TOGGLE);
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;
// Live activity-log view: fills the table area when toggled on (hidden until
// then). Added before the table in the sizer; whichever is shown takes the
// space while the other is hidden to zero.
let log_view = Widget::text_ctrl(panel, true);
root.add(log_view, 1, sf::EXPAND | sf::BORDER_ALL, 4);
log_view.show(false);
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,
rows_dirty: false,
built_columns: Vec::new(),
table_parent,
log_view,
log_toggle_btn,
showing_log: false,
log_shown_len: 0,
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,
scan_stopped: false,
auto_secs: scan::load_auto_secs(),
scan_timeout_secs: scan::load_scan_timeout(),
countdown: 0,
tick_accum: 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_kind: PromptKind::Power,
action_total: 0,
action_done: 0,
action_targets: Vec::new(),
pending_password_update: None,
op_status: std::collections::HashMap::new(),
install_targets: HashSet::new(),
verify_cooldown: 0,
installed_awaiting: 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,
ssh_user_input: frame,
ssh_pass_input: frame,
fwcreds_dialog: frame,
fwcreds_rows: Vec::new(),
access_probe: None,
logfetch: None,
logview_dialog: frame,
logs_dialog: frame,
logs_text: frame,
report_dialog: frame,
report_kind: frame,
report_text: frame,
report_log: frame,
report_status: frame,
report_open_btn: frame,
report_rx: None,
report_url: None,
restore: None,
restore_dialog: frame,
pending_restore: Vec::new(),
stock_op: None,
install_dialog: frame,
install_release_choice: frame,
install_unsigned_check: frame,
install_releases: Vec::new(),
install_ips: Vec::new(),
install_board: stock_ops::DEFAULT_BOARD.to_string(),
install_is_update: false,
install_local_path: None,
install_local_label: frame,
install_plan_label: frame,
install_repo_input: frame,
uninstall_dialog: frame,
uninstall_firmware_input: frame,
uninstall_onboard_check: frame,
uninstall_onboard_available: false,
uninstall_ips: 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(),
pool_presets_dialog: frame,
pool_presets_input: frame,
pool_presets_field: crate::pool_prefs::PoolField::Address,
fw_preset_dialog: frame,
fw_preset_choice: frame,
fw_preset_names: Vec::new(),
fw_preset_ips: 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,
ranges_concurrency: frame,
columns_dialog: frame,
columns_list: frame,
columns_hide_empty_cb: frame,
export_dialog: frame,
export_list: 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, TICK_MS);
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"),
_ => {}
}
// Data/text columns are right-aligned (round 19 #21). IP and the
// icon columns (Health/Access/Light) stay left-aligned so their
// fixed-width icon slots anchor at a consistent left edge and line up
// across rows (round 19 Health-column follow-up).
let align = if matches!(
c,
Column::Ip | Column::Health | Column::Locked | Column::Light
) {
wx_rs::ALIGN_LEFT
} else {
wx_rs::ALIGN_RIGHT
};
if matches!(
c,
Column::Hashrate
| Column::Health
| Column::TotalChips
| Column::ChipTemp
| Column::Locked
| Column::Light
| Column::Error
| Column::Status
| Column::Firmware
) {
// These columns show two-tone / multi-tone text (actual vs.
// expected) via a custom renderer that parses the segment-encoded
// cell value fill_rows writes.
t.dvlc_append_colored_col(&title, c.width(), !fixed, align);
} else {
t.dvlc_append_text_col(&title, c.width(), !fixed, align);
}
}
// 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);
// Keep the table hidden if the log view is currently showing (a rebuild
// would otherwise re-reveal it).
if self.showing_log {
t.show(false);
}
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();
// Record exactly which columns the widget now holds, so fill_rows can
// detect an auto-hide-empty set change and rebuild rather than render
// against stale columns (round 18 #12).
self.built_columns = self.table_columns();
self.fill_rows();
}
pub fn fill_rows(&mut self) {
let Some(t) = self.table else { return };
// Compute the shown columns once and reuse it everywhere below (with
// auto-hide-empty on, table_columns() scans every cell of every row, so it
// must not be called per section of this function -- round 18 #12).
let cols = self.table_columns();
// If the set of shown columns has changed since the widget was built (only
// possible with auto-hide-empty on, when a scan makes a column non-empty),
// the widget's columns are stale: rendering now would misalign cells and
// header clicks. Rebuild instead -- deferred, because rebuild_table
// destroys this control (round 18 #12).
if cols != self.built_columns {
wx_rs::call_after(DEFER_TABLE);
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);
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 => {
// A reported 0 shows "0.00T" (not a dash); the dash is only for
// an unreadable reading (hashrate_known == false).
let actual = format_hashrate_actual(r.hashrate_ths, r.hashrate_known);
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),
},
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)
}
// 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).map(|fc| self.pal.text(fc)),
),
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);
}
}
}
}
// Columns keep their configured default widths (scaled by the table zoom
// via table_zoom_reapply). A previous build re-ran a content-fit autosize
// on every rebuild, but on GTK reading a column's width immediately after
// SetWidth(AUTOSIZE) returns a value from before the native measurement
// lands, so a rebuild (language change, hide/show, reorder) collapsed every
// column to the floor (round 19 #3/#24). Autosize is now on-demand only
// (the header menu's "Auto-size" items), where the columns are realised so
// the measurement is valid.
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, algo_unit) = if k.hashrate_by_algo.is_empty() {
("SHA-256".to_string(), 0.0, "H")
} else {
let i = self.hashrate_algo_idx % k.hashrate_by_algo.len();
let (a, t) = &k.hashrate_by_algo[i];
// Equihash miners (Z15/Zcash) are counted in Sol/s, not H/s (round 18 #7).
let unit = if a.eq_ignore_ascii_case("equihash") {
"Sol"
} else {
"H"
};
(pretty_algo(a), *t, unit)
};
self.kpi_hashrate
.set_label(&format_si(algo_ths * 1e12, algo_unit));
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 or a stock install/restore 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.stock_op.is_some() {
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 {
// A single state-based toggle (round 18 #9): if any selected miner's
// locate light is on, offer to stop; otherwise offer to flash.
let any_on = selected.iter().any(|r| r.light_flashing == Some(true));
if any_on {
menu.menu_append(ID_CTX_LIGHT_OFF, &format!("Stop flashing lights{sfx}"));
} else {
menu.menu_append(ID_CTX_LIGHT_ON, &format!("Flash lights{sfx}"));
}
}
// State-aware (round 19 #20): only offer Pause when at least one
// selected miner is actually running, and Resume only when at least
// one is paused, so a paused miner never shows "Pause" and a running
// one never shows "Resume". On a mixed selection both can appear.
if caps.pause && selected.iter().any(|r| !r.paused) {
menu.menu_append(ID_CTX_PAUSE, &format!("Pause mining{sfx}"));
}
if caps.resume && selected.iter().any(|r| r.paused) {
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 target...{sfx}"));
}
if caps.hashrate_target {
menu.menu_append(ID_CTX_HASHRATE, &format!("Set hashrate target...{sfx}"));
}
if caps.supports_presets {
menu.menu_append(ID_CTX_PRESET, &format!("Set profile...{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}"));
}
if caps.timezone {
menu.menu_append(ID_CTX_TIMEZONE, &format!("Set timezone...{sfx}"));
}
// Destructive / credential-changing actions, set apart (round 17 B).
if caps.change_password || caps.factory_reset {
menu.menu_append_separator();
if caps.change_password {
menu.menu_append(ID_CTX_PASSWORD, &format!("Change password...{sfx}"));
}
if caps.factory_reset {
menu.menu_append(ID_CTX_FACTORY_RESET, &format!("Factory reset...{sfx}"));
}
}
}
// Firmware flash is intentionally not offered for now (round 16 #6): the
// in-app flash path is disabled while it is reworked. Restore-to-stock +
// the vendor installers cover the current workflow. (ID_CTX_FLASH and the
// flash dialog remain in the code, just not surfaced here.)
let _ = ID_CTX_FLASH;
// Alkane OS install / update / uninstall via the toolkit's own
// self-contained, network-only engine. Each is offered only when it
// applies to every selected board:
// - Install: a supported board (alkane-os has an image for its control
// board) that is not running Alkane OS yet;
// - Update: a supported board already running Alkane OS (updated in
// place);
// - Uninstall: a board running Alkane OS (restored to stock).
// A mixed stock/Alkane selection gets neither Install nor Update. The
// engine still gates on compatibility.
let supported = selected.iter().all(|r| alkane_detect::install_supported(r));
let all_alkane = selected.iter().all(|r| alkane_detect::is_alkane(r));
let none_alkane = selected.iter().all(|r| !alkane_detect::is_alkane(r));
let install = supported && none_alkane;
let update = supported && all_alkane;
let uninstall = all_alkane;
if install || update || uninstall {
menu.menu_append_separator();
}
if install {
menu.menu_append(ID_CTX_INSTALL_ALKANE, "Install alkane OS...");
}
if update {
menu.menu_append(ID_CTX_UPDATE_ALKANE, "Update alkane OS...");
}
if uninstall {
menu.menu_append(
ID_CTX_UNINSTALL_ALKANE,
"Uninstall alkane OS (restore to stock)...",
);
}
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();
}
/// 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 _ = n;
let root = Widget::box_sizer(true);
// Column headers (round 16 #5: no intro tidbit; the "+" presets + worker
// placeholders are self-explanatory in the menus).
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
};
// Each column on screen is the text field PLUS its 34px "+" button, so each
// header must span field_width + 34 to line up with the boxes below it
// (round 18 #8c). The Pool-label column is 46 to match the row label.
const PLUS_W: i32 = 34;
let widths = [170, 110, 110, 70]; // address, account, worker, password
head.add(hl("", 46), 0, sf::BORDER_LEFT, 6);
head.add(hl("Address", widths[0] + PLUS_W), 0, sf::BORDER_LEFT, 6);
head.add(hl("Account", widths[1] + PLUS_W), 0, sf::BORDER_LEFT, 6);
head.add(hl("Worker", widths[2] + PLUS_W), 0, sf::BORDER_LEFT, 6);
head.add(hl("Password", widths[3] + PLUS_W), 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);
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, &w) in widths.iter().enumerate() {
let input = Widget::text_ctrl(dlg, false);
input.set_min_size(w, -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(PLUS_W, -1); // wide enough that the "+" glyph isn't clipped
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);
// Wide enough for the label + all four field+button columns so the "+"
// buttons on the right (Password) are never clipped (round 18 #8a).
dlg.set_min_size(700, 220);
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();
// "Add new..." opens the preset-manager window: an editable list of all the
// saved values for this field, so the user can add, edit and remove them in
// one place (round 18 #8b -- replaces the old add-one / remove-submenu pair).
menu.menu_append(ID_POOL_MENU_ADD, "Add new...");
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.
/// ("Add new..." is handled in on_menu_item, which opens the preset manager.)
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;
};
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);
}
}
/// Build (but do not show) the pool-preset manager (round 18 #8b): a multiline
/// editable list of the saved values for the field whose "+" menu is open. The
/// current box value (if non-empty and not already saved or a built-in preset)
/// is seeded as the last line, so "Add new..." pre-fills what the user typed.
fn build_pool_presets_dialog(&mut self) -> Widget {
use crate::pool_prefs::PoolField;
let field = self.pool_menu_field;
let field_name = match field {
PoolField::Address => "address",
PoolField::Account => "account",
PoolField::Worker => "worker",
PoolField::Password => "password",
};
let mut lines = crate::pool_prefs::load_saved(field);
if let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() {
let cur = input.get_value().trim().to_string();
if !cur.is_empty()
&& !lines.iter().any(|l| l == &cur)
&& !field.presets().iter().any(|p| *p == cur)
{
lines.push(cur);
}
}
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Saved {field_name} values"));
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
"One value per line. These appear in the + menu below the built-in\npresets. Edit freely, then Save.",
),
0,
sf::BORDER_ALL,
8,
);
let input = Widget::text_ctrl(dlg, true);
input.set_value(&lines.join("\n"));
input.set_min_size(360, 220);
root.add(input, 1, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(
Widget::button(dlg, "Save", ID_POOL_PRESETS_SAVE),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, "Cancel", ID_POOL_PRESETS_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(400, 340);
dlg.fit(dlg);
self.pool_presets_dialog = dlg;
self.pool_presets_input = input;
self.pool_presets_field = field;
dlg
}
/// Save the edited pool-preset list back to disk (round 18 #8b). Blank lines,
/// duplicates and built-in presets are dropped by pool_prefs::save_all.
fn apply_pool_presets(&mut self) {
let text = self.pool_presets_input.get_value();
let values: Vec<String> = text.lines().map(|l| l.trim().to_string()).collect();
match crate::pool_prefs::save_all(self.pool_presets_field, &values) {
Ok(n) => {
self.pool_presets_dialog.close(1);
wx_rs::set_status_text(&format!("saved {n} value(s)"));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save: {e}")),
}
}
/// 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;
}
// This path sets self.action directly, so it needs start_action's full
// exclusivity guard: don't write pools during a restore or a live scan
// (round 18 #12).
if self.restore.is_some() || self.stock_op.is_some() {
wx_rs::set_status_text(
"a stock install/restore is in progress -- wait for it to finish",
);
return;
}
if self.scanning {
wx_rs::set_status_text("scan 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();
// Clear the superseded action's in-flight status so its Health cells
// don't stay frozen on the old label (round 18 #12).
let stale = std::mem::take(&mut self.action_targets);
for ip in stale {
self.op_status.remove(&ip);
}
}
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;
}
// A restore-to-stock is reverting + rebooting miners; a config action mid-
// revert could hit a unit in an undefined state (round 18 #12).
if self.restore.is_some() || self.stock_op.is_some() {
wx_rs::set_status_text(
"a stock install/restore is in progress -- wait for it to finish",
);
return;
}
// A scan is opening its own connections to these same miners; a mutating
// action racing the scan's probe traffic can be dropped or interleaved, so
// hold it until the scan finishes (round 18 #12 -- matches the flash/restore
// invariant).
if self.scanning {
wx_rs::set_status_text("scan in progress -- wait for it to finish");
return;
}
if let Some(old) = self.action.take() {
old.stop();
// The superseded action's drain will never run again, so clear its
// miners' in-flight status or their Health cells stay frozen on the old
// "...ing" label forever (round 18 #12).
let stale = std::mem::take(&mut self.action_targets);
for ip in stale {
self.op_status.remove(&ip);
}
}
// 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();
// Remember a password change so we can update our own saved credentials
// once it succeeds -- otherwise the toolkit keeps using the old password
// and locks itself out of the miners it just changed (round 18 #12).
self.pending_password_update = match &action {
scan::ConfigAction::ChangePassword(p) => Some(p.clone()),
_ => None,
};
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));
}
/// Start fetching the selected miner's log over its firmware API on a
/// background thread (round 18 #12: the fetch is a multi-second network call
/// and must never block the wx event loop). The viewer is shown when the
/// result lands, in `drain_logfetch`.
fn start_log_fetch(&mut self) {
if self.logfetch.is_some() {
wx_rs::set_status_text("a log fetch is already in progress");
return;
}
let rows = self.selected_rows();
let Some(r) = rows.first() else { return };
let (ip, brand) = (r.ip.clone(), r.brand.clone());
// asic-rs read_logs() authenticates through configured_factory() (the saved
// scan credentials), so no per-firmware creds are threaded here (round 19
// #11-16). WhatsMiner's fault-code fallback is unauthenticated.
let timeout = self.scan_timeout_secs;
wx_rs::set_status_text(&format!("fetching log from {ip}..."));
let (tx, rx) = std::sync::mpsc::channel();
let ip_thread = ip.clone();
let spawned = std::thread::Builder::new()
.name("log-fetch".into())
.spawn(move || {
let res = crate::log_scan::scan_log(&ip_thread, &brand, timeout);
let _ = tx.send(res);
});
if spawned.is_err() {
wx_rs::set_status_text("could not start the log fetch");
return;
}
self.logfetch = Some((ip, rx));
}
/// Poll the in-flight log fetch; when it finishes, build the viewer dialog to
/// show (or report the error). Returns the dialog for `dispatch` to show
/// modally once the App borrow is released (round 18 #12).
fn drain_logfetch(&mut self) -> Option<Widget> {
let (ip, result) = {
let (ip, rx) = self.logfetch.as_ref()?;
match rx.try_recv() {
Ok(res) => (ip.clone(), res),
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
let ip = ip.clone();
self.logfetch = None;
wx_rs::set_status_text(&format!("log fetch aborted for {ip}"));
return None;
}
}
};
self.logfetch = None;
let scan = match result {
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()));
Some(self.build_log_dialog(&ip, &scan))
}
/// Build (but do not show) the log viewer for an already-fetched log.
fn build_log_dialog(&mut self, ip: &str, scan: &crate::log_scan::LogScan) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Miner log (API) -- {ip}"));
let root = Widget::box_sizer(true);
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;
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): a one-line question + the list of
// miners. The list is a height-capped, scrollable text box (round 16 #6)
// so a selection of hundreds of miners doesn't make the dialog unusably
// tall -- it caps and scrolls instead of growing with the content.
root.add(
Widget::static_text(
dlg,
&format!("Restore these {n} miner(s) to stock firmware?"),
),
0,
sf::BORDER_ALL,
12,
);
let listbox = Widget::text_ctrl(dlg, true);
listbox.set_value(&list);
listbox.set_min_size(460, 320);
root.add(
listbox,
1,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
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(500, 300);
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) {
// Restore-to-stock is destructive and needs exclusive access to the miners;
// refuse if any scan / refresh / action / flash or another restore is
// already in flight, so two operations never hit the same unit and a
// running restore handle is never orphaned by being overwritten (round 18 #12).
if self.flashing
|| self.scanning
|| self.action.is_some()
|| self.refresh.is_some()
|| self.restore.is_some()
|| self.stock_op.is_some()
{
wx_rs::set_status_text(
"busy (scan/action/restore in progress) -- try again once it finishes",
);
self.pending_restore.clear();
self.restore_dialog.close(0);
return;
}
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 ssh_user = credentials::ssh_user_or_default(&ssh_user);
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();
loop {
match h.rx.try_recv() {
Ok(restore::RestoreMsg::Started) => {}
Ok(restore::RestoreMsg::Result { ip, ok, detail }) => {
op_clear.push(ip.clone());
if ok {
oks += 1;
} else {
fails.push(format!("{ip}: {detail}"));
}
}
Ok(restore::RestoreMsg::Done) => {
done = true;
break;
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
// The worker thread ended without a Done (e.g. it never started):
// finalise so the restore subsystem can't wedge (round 18 #12).
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
done = true;
break;
}
}
}
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;
}
/// True when any hardware-touching job is in flight. A new install/uninstall
/// must not start while a scan, config action, refresh, flash, restore, or
/// another stock op is running (they would race on the same boards).
/// True when a flash/restore-level operation is in flight (ignores an
/// in-flight scan, which an install/uninstall
/// dialog may be opened and prepared while a scan runs (issue #43). The scan
/// is stopped by `stop_scan_for_op` only when the operation actually starts.
fn flash_busy(&self) -> bool {
self.flashing
|| self.action.is_some()
|| self.refresh.is_some()
|| self.restore.is_some()
|| self.stock_op.is_some()
}
/// Cancel any in-flight scan before a flash/restore starts, so the two never
/// probe/write the same board at once (issue #43).
fn stop_scan_for_op(&mut self) {
if self.scanning || self.scan.is_some() {
self.playing = false;
self.scan_stopped = true;
self.countdown = 0;
self.scanning = false;
if let Some(old) = self.scan.take() {
old.stop();
}
wx_rs::set_status_text("scan stopped for the flash operation");
}
}
/// Build the "Install alkane OS" dialog (or, with `update`, the "Update
/// alkane OS" dialog for boards already running it): a scanned list of
/// alkane-os releases to pick from, an optional board credential, the
/// allow-unsigned (bench) toggle. The install runs over the network via the
/// toolkit's own compiled-in from-stock engine.
/// Scan `owner/repo`'s releases and fill the install picker with the ones
/// that carry an .afw compatible with the target board (newest first). Called
/// when the dialog opens and from the Reload button. Requires
/// `install_release_choice` to already exist.
fn populate_install_releases(&mut self, owner: &str, repo: &str) {
let board = self.install_board.clone();
wx_rs::set_status_text(&format!("scanning {owner}/{repo} releases..."));
let releases: Vec<ReleaseInfo> =
match fetch::list_releases(&ReleaseSource::for_repo(owner, repo)) {
Ok(list) => list
.into_iter()
.filter(|r| !r.draft && r.is_compatible_with(&board))
.collect(),
Err(e) => {
wx_rs::set_status_text(&format!("could not list {owner}/{repo} releases: {e}"));
Vec::new()
}
};
self.install_releases = releases;
let choice = self.install_release_choice;
choice.choice_clear();
if self.install_releases.is_empty() {
choice.choice_append(&format!(
"(no release with an .afw for {board} in {owner}/{repo})"
));
} else {
for (i, r) in self.install_releases.iter().enumerate() {
let tag = if r.tag.is_empty() {
r.name.as_str()
} else {
r.tag.as_str()
};
let kind = if r.prerelease { " [pre-release]" } else { "" };
let latest = if i == 0 { " (latest)" } else { "" };
let date = r.published_at.split('T').next().unwrap_or("");
choice.choice_append(&format!("{tag}{kind} {date}{latest}"));
}
choice.choice_set_selection(0);
}
wx_rs::set_status_text(&format!(
"{} release(s) for {board} in {owner}/{repo}",
self.install_releases.len()
));
}
/// Reload the install picker from the owner/repo currently typed in the
/// dialog's repo field (default blueflare/alkane-os if blank/malformed).
fn reload_install_repo(&mut self) {
let raw = self.install_repo_input.get_value();
let raw = raw.trim();
let (owner, repo) = raw.split_once('/').unwrap_or(("blueflare", "alkane-os"));
let owner = owner.trim();
let repo = repo.trim();
if owner.is_empty() || repo.is_empty() {
self.populate_install_releases("blueflare", "alkane-os");
} else {
self.populate_install_releases(owner, repo);
}
self.install_dialog.layout();
}
fn build_install_dialog(&mut self, update: bool) -> Option<Widget> {
if self.flash_busy() {
wx_rs::set_status_text("busy -- try again once the current operation finishes");
return None;
}
let ips = self.selected_ip_list();
if ips.is_empty() {
wx_rs::set_status_text("select a board to install onto");
return None;
}
// Target board family comes from the selected board(s), not a fixed
// default (review #7). Install/Update is only offered when every selected
// board is install-supported, so their board_family is consistent; fall
// back to the default only if none resolves.
let board = self
.selected_rows()
.into_iter()
.find_map(crate::alkane_detect::board_family)
.unwrap_or_else(|| stock_ops::DEFAULT_BOARD.to_string());
self.install_board = board.clone();
self.install_is_update = update;
// Releases are scanned after the picker widget exists, from the repo in
// the repo field (default blueflare/alkane-os); see
// populate_install_releases, which the Reload button also calls.
self.install_releases = Vec::new();
self.install_ips = ips.clone();
self.install_local_path = None;
let frame = Widget::main_frame();
let title = if update {
"Update alkane OS"
} else {
"Install alkane OS"
};
let dlg = Widget::dialog(frame, title);
let root = Widget::box_sizer(true);
let n = ips.len();
root.add(
Widget::static_text(
dlg,
&if update {
format!(
"Update alkane OS on {n} board(s) already running it (updated in place; BOOT.bin is never written):\n{}",
ips.join(", ")
)
} else {
format!(
"Install alkane OS onto {n} board(s) currently on stock:\n{}",
ips.join(", ")
)
},
),
0,
sf::BORDER_ALL,
12,
);
root.add(
Widget::static_text(dlg, &format!("Target board: {board}")),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
root.add(
Widget::static_text(
dlg,
if update {
"Release to update to (newest first):"
} else {
"Release to install (newest first):"
},
),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let choice = Widget::choice(dlg, ID_INSTALL_RELEASE_CHOICE);
root.add(
choice,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
self.install_release_choice = choice;
// Release repo: any Gitea owner/repo that publishes the same .afw release
// format; defaults to blueflare/alkane-os. Reload re-scans it and keeps
// only the releases compatible with this board.
root.add(
Widget::static_text(dlg, "Release repo (owner/repo), then Reload:"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let repo_row = Widget::box_sizer(false);
let repo_input = Widget::text_ctrl(dlg, false);
repo_input.set_value("blueflare/alkane-os");
repo_row.add(
repo_input,
1,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT,
6,
);
repo_row.add(Widget::button(dlg, "Reload", ID_INSTALL_RELOAD), 0, 0, 0);
self.install_repo_input = repo_input;
root.add_sizer(
repo_row,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
// Initial population from the default repo.
self.populate_install_releases("blueflare", "alkane-os");
// Or install from a local .afw the operator picks (the CLI's local-file
// install, now in the GUI). When a file is chosen it takes precedence
// over the release selected above; the label shows the current choice.
root.add(
Widget::static_text(dlg, "Or install from a local .afw file:"),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let browse_row = Widget::box_sizer(false);
browse_row.add(
Widget::button(dlg, "Browse local .afw...", ID_INSTALL_BROWSE),
0,
sf::BORDER_RIGHT,
6,
);
let local_label = Widget::static_text(dlg, "(none; using the selected release above)");
browse_row.add(local_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0);
self.install_local_label = local_label;
root.add_sizer(
browse_row,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
// Flash-plan checklist: detects the tier and which regions a picked local
// .afw overwrites (U-Boot / Kernel / Userspace).
let plan = Widget::static_text(
dlg,
"Flash plan: pick a local .afw above to see its tier and what it overwrites.",
);
root.add(plan, 0, sf::BORDER_ALL, 12);
self.install_plan_label = plan;
// No password field (issue #46): the board login comes from Settings (or
// the firmware's shipped default when unset).
// Current bench .afw files are unsigned (SHA-256 integrity, no Ed25519).
let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)");
unsigned.set_checked(true);
root.add(unsigned, 0, sf::BORDER_ALL, 12);
self.install_unsigned_check = unsigned;
// No typed-FLASH step (issue #41): the dialog, the board list and the
// Install button are the confirmation. The warning stays visible.
root.add(
Widget::static_text(
dlg,
"This reflashes the control board. Click Install to start.",
),
0,
sf::BORDER_ALL,
12,
);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(
Widget::button(dlg, "Install", ID_INSTALL_OK),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, "Cancel", ID_INSTALL_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(540, 440);
dlg.fit(dlg);
self.install_dialog = dlg;
wx_rs::set_status_text(&format!(
"{} release(s) available for {board}",
self.install_releases.len()
));
Some(dlg)
}
/// Apply the install confirmation: validate the typed keyword, resolve the
/// chosen release asset, and start the network-only from-stock install.
fn apply_install_confirm(&mut self) {
if self.flash_busy() {
wx_rs::set_status_text("busy -- try again once the current operation finishes");
self.install_dialog.close(0);
return;
}
let board = self.install_board.clone();
// Source: a local .afw the operator picked takes precedence; otherwise
// the selected Gitea release's asset for this board.
let (source, source_name) = if let Some(path) = self.install_local_path.clone() {
let name = std::path::Path::new(&path)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.clone());
(AfwSource::Local(std::path::PathBuf::from(path)), name)
} else {
let idx = self.install_release_choice.choice_get_selection();
if idx < 0 || self.install_releases.is_empty() {
self.set_error_indicator(
"pick a Gitea release or Browse for a local .afw, then start the install",
);
return;
}
let Some(release) = self.install_releases.get(idx as usize) else {
self.set_error_indicator("the selected release is no longer available; rescan");
return;
};
let Some(asset) = release.asset_for_board(&board) else {
self.set_error_indicator(&format!(
"the selected release has no .afw for {board}; pick another or Browse for a file"
));
return;
};
(
AfwSource::Release {
name: asset.name.clone(),
url: asset.url.clone(),
},
asset.name.clone(),
)
};
let allow_unsigned = self.install_unsigned_check.is_checked();
// Board login from Settings; empty -> the firmware's shipped default
// applies inside the engine (issue #46).
let password = credentials::load_ssh_credentials()
.map(|(_, p)| p)
.filter(|p| !p.is_empty());
let ips = std::mem::take(&mut self.install_ips);
if ips.is_empty() {
self.set_error_indicator("no board selected to install onto; close this and reselect");
self.install_dialog.close(0);
return;
}
self.install_dialog.close(1);
crate::logs::log(format!(
"install alkane OS onto {} board(s) from {}",
ips.len(),
source_name
));
wx_rs::set_status_text(&format!(
"installing alkane OS onto {} board(s) from {source_name}...",
ips.len()
));
self.stop_scan_for_op();
self.set_op_status(&ips, "installing...");
// Remember these targets so a successful install arms the post-install
// alkane verification (prevents the stock->alkane re-scan flicker).
self.install_targets = ips.iter().cloned().collect();
self.stock_op = Some(stock_ops::start_install(
ips,
board,
source,
allow_unsigned,
password,
self.install_is_update,
));
}
/// Build the "Uninstall alkane OS (restore to stock)" dialog: the board's
/// alkane root credential and a genuine Bitmain firmware file.
fn build_uninstall_dialog(&mut self) -> Option<Widget> {
if self.flash_busy() {
wx_rs::set_status_text("busy -- try again once the current operation finishes");
return None;
}
let ips = self.selected_ip_list();
if ips.is_empty() {
wx_rs::set_status_text("select an alkane board to restore to stock");
return None;
}
self.uninstall_ips = ips.clone();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Uninstall alkane OS (restore to stock)");
let root = Widget::box_sizer(true);
let n = ips.len();
root.add(
Widget::static_text(
dlg,
&format!(
"Restore {n} alkane board(s) to genuine stock:\n{}",
ips.join(", ")
),
),
0,
sf::BORDER_ALL,
12,
);
// Credentials come from Settings (the alkane root login), not this dialog
// (issue #46). Probe each selected board for a restorable on-board stock
// backup so the on-board option can be offered or greyed out (#48).
let cred = credentials::load_ssh_credentials()
.map(|(_, p)| p)
.filter(|p| !p.is_empty());
let onboard_ok = ips
.iter()
.all(|ip| stock_ops::onboard_backup_present(ip, cred.as_deref()));
self.uninstall_onboard_available = onboard_ok;
// Source 1: the board's own on-board stock backup (always shown; greyed
// when no backup is present) (#48).
let onboard = Widget::check_box(
dlg,
"Restore from the board's on-board stock backup (left by the install)",
);
onboard.set_checked(onboard_ok);
onboard.set_enabled(onboard_ok);
root.add(onboard, 0, sf::BORDER_ALL, 12);
self.uninstall_onboard_check = onboard;
root.add(
Widget::static_text(
dlg,
if onboard_ok {
"An on-board stock backup was detected -- this is the default."
} else {
"No on-board stock backup detected; restore from a file below."
},
),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
// Source 2: a genuine Bitmain stock firmware file (any X17-series model);
// Browse to pick it (#47).
root.add(
Widget::static_text(
dlg,
"Or restore from a Bitmain stock firmware file\n(OTA update .tar.gz or SD recovery .zip, any X17-series model):",
),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
);
let fw_row = Widget::box_sizer(false);
fw_row.add(
Widget::button(dlg, "Browse firmware file...", ID_UNINSTALL_BROWSE),
0,
sf::BORDER_RIGHT,
6,
);
let fw = Widget::text_ctrl(dlg, false);
fw_row.add(fw, 1, sf::ALIGN_CENTRE_VERTICAL, 0);
self.uninstall_firmware_input = fw;
root.add_sizer(
fw_row,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
// No typed-FLASH step (issue #41): the dialog and the Restore button are
// the confirmation.
root.add(
Widget::static_text(
dlg,
"This reflashes the board back to stock (BOOT.bin preserved). Click Restore to start.",
),
0,
sf::BORDER_ALL,
12,
);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(
Widget::button(dlg, "Restore to stock", ID_UNINSTALL_OK),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, "Cancel", ID_UNINSTALL_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(540, 440);
dlg.fit(dlg);
self.uninstall_dialog = dlg;
Some(dlg)
}
fn apply_uninstall_confirm(&mut self) {
if self.flash_busy() {
wx_rs::set_status_text("busy -- try again once the current operation finishes");
self.uninstall_dialog.close(0);
return;
}
// On-board backup restore takes precedence when its box is checked and a
// backup was detected; otherwise restore from the chosen firmware file.
let use_onboard =
self.uninstall_onboard_available && self.uninstall_onboard_check.is_checked();
let firmware = self.uninstall_firmware_input.get_value();
let firmware = firmware.trim().to_string();
if !use_onboard {
if firmware.is_empty() {
self.set_error_indicator(
"pick a stock firmware file (Browse), or check the on-board backup option",
);
return;
}
if !std::path::Path::new(&firmware).is_file() {
self.set_error_indicator(&format!("firmware file not found: {firmware}"));
return;
}
}
// Alkane root credential comes from Settings; empty -> the method's
// shipped default applies (issue #46, #51).
let password = credentials::load_ssh_credentials()
.map(|(_, p)| p)
.filter(|p| !p.is_empty());
let ips = std::mem::take(&mut self.uninstall_ips);
if ips.is_empty() {
self.uninstall_dialog.close(0);
return;
}
self.uninstall_dialog.close(1);
self.stop_scan_for_op();
self.set_op_status(&ips, "restoring...");
if use_onboard {
crate::logs::log(format!(
"restore {} alkane board(s) to stock from on-board backup",
ips.len()
));
self.stock_op = Some(stock_ops::start_restore_onboard(ips, password));
} else {
crate::logs::log(format!(
"restore {} alkane board(s) to stock from {}",
ips.len(),
firmware
));
self.stock_op = Some(stock_ops::start_restore(
ips,
std::path::PathBuf::from(firmware),
password,
));
}
}
/// Drain the alkane install/uninstall job: progress onto the status bar,
/// per-board results into the op-status, and finalisation on Done.
fn drain_stock_op(&mut self) {
let Some(h) = &self.stock_op 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();
// Successfully-installed IPs whose boards should now come up as alkane.
let mut verify_ips: Vec<String> = Vec::new();
let mut progress: Option<String> = None;
loop {
match h.rx.try_recv() {
Ok(StockMsg::Started) => {}
Ok(StockMsg::Progress(s)) => progress = Some(s),
Ok(StockMsg::Result { ip, ok, detail }) => {
if ok {
oks += 1;
if !ip.is_empty() && self.install_targets.contains(&ip) {
verify_ips.push(ip.clone());
} else if !ip.is_empty() {
op_clear.push(ip.clone());
}
} else {
if !ip.is_empty() {
op_clear.push(ip.clone());
}
fails.push(format!("{ip}: {detail}"));
}
}
Ok(StockMsg::Done) => {
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);
}
// Arm post-install alkane verification for the boards that installed OK:
// keep a "verifying" status on them and suppress stock re-scan rows until
// they answer as alkane (prevents the stock->alkane flicker).
for ip in &verify_ips {
self.installed_awaiting.insert(ip.clone(), 8);
self.op_status
.insert(ip.clone(), "installed; verifying alkane...".into());
}
if let Some(p) = progress {
wx_rs::set_status_text(&p);
// Show a progress bar in the Health cell of each in-flight board
// (issue #42: "installing" alone was not enough feedback).
let pct = stock_progress_pct(&p);
let bar = ascii_bar(pct);
let updates: Vec<(String, String)> = self
.op_status
.iter()
.filter(|(_, v)| v.starts_with("installing") || v.starts_with("restoring"))
.map(|(ip, v)| {
let verb = if v.starts_with("restoring") {
"restoring"
} else {
"installing"
};
(ip.clone(), format!("{verb} {bar} {pct}%"))
})
.collect();
for (ip, s) in updates {
self.op_status.insert(ip, s);
}
}
if done {
self.stock_op = None;
self.install_targets.clear();
// Clear any in-progress "installing/restoring [bar] NN%" statuses, but
// keep "installed; verifying alkane..." (starts with "installed").
self.op_status
.retain(|_, v| !v.starts_with("installing") && !v.starts_with("restoring"));
}
if !op_clear.is_empty() || !verify_ips.is_empty() || done {
self.fill_rows();
}
// Kick a dedicated re-probe of the just-installed boards; the row
// suppression below only accepts them once they answer as alkane.
if done && !verify_ips.is_empty() && self.refresh.is_none() && !self.scanning {
self.start_refresh(verify_ips.clone());
}
if done {
if !fails.is_empty() {
// Surface the actual reason, not just a count (issue #38: a bare
// "1 failed" left the operator unable to tell what went wrong).
for f in &fails {
crate::logs::log(format!("install/restore failed -- {f}"));
}
let first = fails.first().cloned().unwrap_or_default();
let more = if fails.len() > 1 {
format!(" (+{} more; see the log)", fails.len() - 1)
} else {
String::new()
};
self.set_error_indicator(&format!("install/restore failed -- {first}{more}"));
} else if oks > 0 {
crate::logs::log(format!("install/restore complete: {oks} board(s) ok"));
wx_rs::set_status_text(&format!(
"install/restore complete: {oks} board(s) ok -- verify liveness over the network"
));
}
}
}
/// 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();
let mut errors: 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) {
// Only a definitive answer updates the cell; an indeterminate
// probe (locked = None) must not blank a previously-known
// locked/unlocked state (round 18 #12).
if error.is_none() && locked.is_some() {
r.write_locked = locked;
changed = true;
}
}
if let Some(e) = &error {
errors.push(format!("{ip}: {e}"));
}
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;
// Probe errors (a miner the check could not run against) were being
// dropped entirely; surface them in the failure indicator (round 18 #12).
if !errors.is_empty() {
self.set_error_indicator(&format!("access check: {} failed", errors.len()));
crate::logs::log(format!("access check errors: {}", errors.join("; ")));
}
}
// 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). "Add new..." opens the preset
// manager (round 18 #8b, shown modally); the rest fill the box in place.
if id == ID_POOL_MENU_ADD {
return Some(self.build_pool_presets_dialog());
}
if 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 + crate::i18n::Lang::all().len() as i32).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_AUTOSIZE_ALL | 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 => self.start_log_fetch(),
ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(),
ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(false),
ID_CTX_UPDATE_ALKANE => return self.build_install_dialog(true),
ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_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 / restore is running (re-checked at confirm).
if self.flashing
|| self.scanning
|| self.action.is_some()
|| self.refresh.is_some()
|| self.restore.is_some()
|| self.stock_op.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 path = Widget::file_dialog(Widget::main_frame(), "Choose firmware image")?;
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(PromptKind::Power)),
ID_CTX_HASHRATE => return Some(self.build_action_prompt(PromptKind::HashRateTarget)),
ID_CTX_PRESET => return self.build_fw_preset_dialog(),
ID_CTX_TUNING => return Some(self.build_action_prompt(PromptKind::Tuning)),
ID_CTX_TIMEZONE => return Some(self.build_action_prompt(PromptKind::Timezone)),
ID_CTX_PASSWORD => return Some(self.build_action_prompt(PromptKind::Password)),
ID_CTX_FACTORY_RESET => {
return Some(self.build_confirm_dialog(scan::ConfigAction::FactoryReset))
}
_ => {}
}
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"),
scan::ConfigAction::FactoryReset => ("Factory reset", "Factory reset"),
_ => ("Apply to", "Confirm"),
};
let msg = if matches!(action, scan::ConfigAction::FactoryReset) {
format!(
"Factory reset {n} selected miner(s)? This WIPES their configuration (pools, \
tuning, network) and reboots -- a miner may return on DHCP and change IP."
)
} else {
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.
/// The tightest common tuning envelope (max of the mins .. min of the maxes)
/// across the captured-selection miners that advertise one, plus their shared
/// current-target label ("varies" if they differ), for the target prompts
/// (round 17 C). `get` picks the (min, max) pair for the target kind.
fn selected_envelope(
&self,
get: impl Fn(&MinerRow) -> (Option<f64>, Option<f64>),
) -> (Option<(f64, f64)>, Option<String>) {
let sel = self.rows.iter().filter(|r| self.action_ips.contains(&r.ip));
let mut lo: Option<f64> = None;
let mut hi: Option<f64> = None;
let mut labels: std::collections::HashSet<String> = std::collections::HashSet::new();
for r in sel {
let (mn, mx) = get(r);
if let Some(m) = mn {
lo = Some(lo.map_or(m, |v: f64| v.max(m)));
}
if let Some(m) = mx {
hi = Some(hi.map_or(m, |v: f64| v.min(m)));
}
if let Some(l) = &r.tuning_target_label {
labels.insert(l.clone());
}
}
let range = match (lo, hi) {
(Some(a), Some(b)) if a <= b => Some((a, b)),
_ => None,
};
let label = match labels.len() {
0 => None,
1 => labels.into_iter().next(),
_ => Some("varies".to_string()),
};
(range, label)
}
fn build_action_prompt(&mut self, kind: PromptKind) -> Widget {
self.action_ips = self.selected_ip_list();
self.action_kind = kind;
let n = self.action_ips.len();
let frame = Widget::main_frame();
let title = match kind {
PromptKind::Power => "Set power target",
PromptKind::HashRateTarget => "Set hashrate target",
PromptKind::Tuning => "Set tuning percent",
PromptKind::Timezone => "Set timezone",
PromptKind::Password => "Change password",
};
let dlg = Widget::dialog(frame, title);
let root = Widget::box_sizer(true);
// Append the current target and the advertised valid range to the target
// prompts (round 17 C), so the operator sees what the firmware will accept.
let target_hint = |range: Option<(f64, f64)>, cur: Option<String>, unit: &str| {
let mut s = String::new();
if let Some(c) = cur {
s.push_str(&format!("\nCurrent: {c}."));
}
if let Some((a, b)) = range {
s.push_str(&format!(" Valid range: {a:.0}-{b:.0} {unit}."));
}
s
};
let lbl = match kind {
PromptKind::Power => {
let (range, cur) =
self.selected_envelope(|r| (r.power_target_min_w, r.power_target_max_w));
format!(
"Power target in watts for {n} miner(s):{}",
target_hint(range, cur, "W")
)
}
PromptKind::HashRateTarget => {
let (range, cur) = self
.selected_envelope(|r| (r.hashrate_target_min_ths, r.hashrate_target_max_ths));
format!(
"Hashrate target in TH/s for {n} miner(s):{}",
target_hint(range, cur, "TH/s")
)
}
PromptKind::Tuning => format!("Tuning percent (0-100) for {n} miner(s):"),
PromptKind::Timezone => {
format!("IANA timezone (e.g. America/Edmonton) for {n} miner(s):")
}
PromptKind::Password => format!("New web/API password for {n} miner(s):"),
};
root.add(Widget::static_text(dlg, &lbl), 0, sf::BORDER_ALL, 8);
// The change-password prompt masks its field so the new fleet password is
// never shown in the clear (round 18 #12); the numeric/timezone prompts use
// a normal field.
let input = if matches!(kind, PromptKind::Password) {
Widget::password_ctrl(dlg)
} else {
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();
// A target must be positive, finite, and within the advertised range when
// one exists (round 17 C).
let in_range = |v: f64, range: Option<(f64, f64)>| {
v > 0.0 && v.is_finite() && range.is_none_or(|(a, b)| v >= a && v <= b)
};
let action = match self.action_kind {
PromptKind::Power => match val.trim().parse::<f64>() {
Ok(w)
if in_range(
w,
self.selected_envelope(|r| (r.power_target_min_w, r.power_target_max_w))
.0,
) =>
{
Some(scan::ConfigAction::PowerLimit(w))
}
_ => None,
},
PromptKind::HashRateTarget => match val.trim().parse::<f64>() {
Ok(t)
if in_range(
t,
self.selected_envelope(|r| {
(r.hashrate_target_min_ths, r.hashrate_target_max_ths)
})
.0,
) =>
{
Some(scan::ConfigAction::HashRateTarget(t))
}
_ => None,
},
PromptKind::Tuning => match val.trim().parse::<u8>() {
Ok(p) if p <= 100 => Some(scan::ConfigAction::TuningPercent(p)),
_ => None,
},
PromptKind::Timezone => {
let tz = val.trim();
// Validate as an IANA zone before firing so a typo doesn't hit the fleet.
if !tz.is_empty() && tz.parse::<asic_rs::core::config::timezone::Tz>().is_ok() {
Some(scan::ConfigAction::Timezone(tz.to_string()))
} else {
None
}
}
PromptKind::Password => {
let p = val.trim();
(!p.is_empty()).then(|| scan::ConfigAction::ChangePassword(p.to_string()))
}
};
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 = match self.action_kind {
PromptKind::Power => "enter a number of watts within the valid range",
PromptKind::HashRateTarget => "enter a hashrate in TH/s within the valid range",
PromptKind::Tuning => "enter a percent from 0 to 100",
PromptKind::Timezone => "enter a valid IANA zone, e.g. America/Edmonton",
PromptKind::Password => "enter a non-empty password",
};
wx_rs::set_status_text(&format!("invalid value - {hint}"));
}
}
}
/// Build (but do not show) the firmware profile/preset selector (round 18 /
/// roadmap G3). Populated live from the presets read at scan time; only the
/// profiles common (by name) to every selected preset-capable miner are
/// offered, so the chosen profile is valid on all of them. Returns None (with
/// a status hint) when there is nothing to offer.
fn build_fw_preset_dialog(&mut self) -> Option<Widget> {
let supporting: Vec<&MinerRow> = self
.selected_rows()
.into_iter()
.filter(|r| r.caps.supports_presets && !r.presets.is_empty())
.collect();
if supporting.is_empty() {
wx_rs::set_status_text("no firmware profiles available for the selection yet");
return None;
}
// Intersect the profile names across the selection so the chosen name is
// valid on every target; keep the first miner's pretty labels.
let mut common: Vec<crate::model::MinerPreset> = supporting[0].presets.clone();
for r in &supporting[1..] {
let names: std::collections::HashSet<&str> =
r.presets.iter().map(|p| p.name.as_str()).collect();
common.retain(|p| names.contains(p.name.as_str()));
}
if common.is_empty() {
wx_rs::set_status_text("selected miners share no common firmware profile");
return None;
}
self.fw_preset_ips = supporting.iter().map(|r| r.ip.clone()).collect();
self.fw_preset_names = common.iter().map(|p| p.name.clone()).collect();
let n = self.fw_preset_ips.len();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Set profile");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(dlg, &format!("Firmware profile for {n} miner(s):")),
0,
sf::BORDER_ALL,
8,
);
let choice = Widget::choice(dlg, ID_FWPRESET_CHOICE);
for p in &common {
let label = match &p.pretty {
Some(pretty) => format!("{} -- {pretty}", p.name),
None => p.name.clone(),
};
choice.choice_append(&label);
}
choice.choice_set_selection(0);
choice.set_min_size(340, -1);
root.add(
choice,
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_FWPRESET_OK),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, "Cancel", ID_FWPRESET_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, -1);
dlg.fit(dlg);
self.fw_preset_dialog = dlg;
self.fw_preset_choice = choice;
Some(dlg)
}
/// Apply the selected firmware profile to the captured targets (round 18 / G3).
fn apply_fw_preset(&mut self) {
let sel = self.fw_preset_choice.choice_get_selection();
let Some(name) = usize::try_from(sel)
.ok()
.and_then(|i| self.fw_preset_names.get(i))
.cloned()
else {
wx_rs::set_status_text("select a profile");
return;
};
let ips = std::mem::take(&mut self.fw_preset_ips);
self.fw_preset_dialog.close(1);
self.start_action(ips, scan::ConfigAction::Preset(name));
}
/// 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()
|| self.restore.is_some()
|| self.stock_op.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,
);
// Masked so a saved password is never rendered in the clear (round 18 #12).
let pass_input = Widget::password_ctrl(dlg);
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;
// SSH login for the control board (Braiins restore-to-stock). Same rule
// as the global login: the password is never shown, blank keeps it.
let (ssh_user, ssh_pass) = credentials::load_ssh_credentials().unwrap_or_default();
let s_hint = if ssh_pass.is_empty() {
"SSH (restore)"
} else {
"SSH (password saved; blank keeps it)"
};
let srow = Widget::box_sizer(false);
let slabel = Widget::static_text(dlg, s_hint);
slabel.set_min_size(150, -1);
srow.add(
slabel,
0,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
6,
);
let ssh_user_input = Widget::text_ctrl(dlg, false);
ssh_user_input.set_min_size(150, -1);
ssh_user_input.set_value(if ssh_user.is_empty() {
"root"
} else {
&ssh_user
});
srow.add(
ssh_user_input,
0,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
6,
);
let ssh_pass_input = Widget::password_ctrl(dlg);
ssh_pass_input.set_min_size(150, -1);
srow.add(
ssh_pass_input,
1,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
6,
);
root.add_sizer(
srow,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
6,
);
self.ssh_user_input = ssh_user_input;
self.ssh_pass_input = ssh_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::password_ctrl(dlg); // masked (round 18 #12)
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;
}
// SSH login: a blank password keeps the saved one; with nothing saved
// and no password entered there is nothing to store.
let s_user = credentials::ssh_user_or_default(&self.ssh_user_input.get_value());
let s_pass = self.ssh_pass_input.get_value();
let ssh_result = if !s_pass.is_empty() {
credentials::save_ssh_credentials(&s_user, &s_pass)
} else if let Some((_, saved)) = credentials::load_ssh_credentials() {
credentials::save_ssh_credentials(&s_user, &saved)
} else {
Ok(())
};
if let Err(e) = ssh_result {
wx_rs::set_status_text(&format!("failed to save SSH 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();
// A fully-blank row means "no override, use the shipped default" -- the
// natural way to clear one firmware's override. Without this, a blanked
// row was saved as an explicit ("","") override that then broke auth
// fleet-wide for that firmware (round 18 #12).
if user.trim().is_empty() && pass.trim().is_empty() {
continue;
}
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("");
self.ssh_user_input.set_value("root");
self.ssh_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();
let ssh = credentials::clear_ssh_credentials();
match per_fw.and(global).and(ssh) {
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),
))
});
// A password change succeeded on every target: update our own
// saved global credential so the toolkit keeps reaching them. On
// a partial change we leave saved creds alone (we can't tell which
// password now works for which miner) and warn (round 18 #12).
// (self.pending_password_update is a different field than self.action,
// so this disjoint borrow is fine while `h` still holds self.action.)
if let Some(newpass) = self.pending_password_update.take() {
if ok == total && total > 0 {
let user = credentials::load_credentials()
.map(|(u, _)| u)
.unwrap_or_else(|| "root".into());
match credentials::save_credentials(&user, &newpass) {
Ok(()) => crate::logs::log(
"saved credentials updated to the new password".to_string(),
),
Err(e) => crate::logs::log(format!(
"could not update saved credentials after password change: {e}"
)),
}
} else {
crate::logs::log(
"password change was partial -- saved credentials left unchanged; \
update Settings > Credentials manually so the toolkit can reach \
the changed miners"
.to_string(),
);
}
}
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)) => {
if self.installed_awaiting.contains_key(&row.ip) {
// Accept a just-installed board only once it is alkane.
if crate::alkane_detect::is_alkane(&row) {
self.installed_awaiting.remove(&row.ip);
op_clear.push(row.ip.clone());
row.upsert_into(&mut self.rows);
changed = true;
}
} else {
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...");
Self::tick_installed_awaiting(&mut self.installed_awaiting, &mut self.op_status);
}
// Refresh progress stays in the Health column, not the scan line (#8).
let _ = status;
if changed || !op_clear.is_empty() || finished {
self.fill_rows();
}
}
/// Count down each board awaiting post-install alkane confirmation. When a
/// board's rounds run out, stop suppressing its row and clear the status: the
/// install finished but the board never came up answering as alkane. Takes the
/// two maps directly (not `&mut self`) so it can run while a scan/refresh
/// handle still borrows another field of `self`.
fn tick_installed_awaiting(
awaiting: &mut HashMap<String, u8>,
op_status: &mut HashMap<String, String>,
) {
if awaiting.is_empty() {
return;
}
let mut expired = Vec::new();
for (ip, left) in awaiting.iter_mut() {
*left = left.saturating_sub(1);
if *left == 0 {
expired.push(ip.clone());
}
}
for ip in expired {
awaiting.remove(&ip);
op_status.remove(&ip);
crate::logs::log(format!(
"{ip}: installed, but did not answer as alkane within the verify window"
));
}
}
pub fn drain_scan(&mut self) {
let Some(handle) = &self.scan else { return };
let mut changed = false;
// Coalesce progress: a fast drain may pull many per-address updates; apply
// only the latest to the gauge/status once, after the loop.
let mut latest_progress: Option<(usize, usize, String)> = None;
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.scan_stopped = false;
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;
latest_progress = Some((done, total, ip));
}
Ok(ScanMsg::Row(row)) => {
// Ignore stray rows outside the current target set.
if self.target_ips.is_empty() || self.target_ips.contains(&row.ip) {
if self.installed_awaiting.contains_key(&row.ip) {
// Just installed: accept the row only once it answers as
// alkane; a stock mid-reboot answer is suppressed.
if crate::alkane_detect::is_alkane(&row) {
self.installed_awaiting.remove(&row.ip);
self.op_status.remove(&row.ip);
row.upsert_into(&mut self.rows);
changed = true;
}
} else {
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()));
Self::tick_installed_awaiting(
&mut self.installed_awaiting,
&mut self.op_status,
);
// Arm the next automatic scan (if the loop is running). While
// boards are still being verified as alkane, re-probe soon
// instead of waiting the full interval.
self.countdown = if !self.installed_awaiting.is_empty() && self.playing {
self.auto_secs.min(12)
} else 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;
}
}
}
// Apply the coalesced progress once (only while still scanning -- a Done/
// Failed in this same drain already finalised the gauge).
if self.scanning {
if let Some((done, total, ip)) = latest_progress {
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()
));
}
}
if changed {
if self.scanning {
// Still scanning: defer the whole-table refill to tick()'s ~1 Hz
// flush so streaming rows don't trigger a refill on every fast tick
// (round 18 #12).
self.rows_dirty = true;
} else {
// The scan just ended (or wasn't running): show the final state now.
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).
/// Toggle the main window between the fleet table and the live activity log.
fn toggle_log_view(&mut self) {
self.showing_log = !self.showing_log;
if self.showing_log {
if let Some(t) = self.table {
t.show(false);
}
self.log_view.show(true);
self.log_view.set_value("");
self.log_shown_len = 0;
self.refresh_log_view();
self.log_toggle_btn.set_label("Table");
} else {
self.log_view.show(false);
if let Some(t) = self.table {
t.show(true);
}
self.log_toggle_btn.set_label("Log");
}
self.table_parent.layout();
}
/// Tail the activity log into the log view: append only the lines added since
/// last shown (so the view stays scrolled to the newest entry); on a shrink
/// (log cleared) reset. Cheap no-op when nothing changed.
fn refresh_log_view(&mut self) {
let text = crate::logs::dump();
let total = if text.is_empty() {
0
} else {
text.lines().count()
};
if total > self.log_shown_len {
let new: String = text
.lines()
.skip(self.log_shown_len)
.map(|l| format!("{l}\n"))
.collect();
self.log_view.write_text(&new);
self.log_shown_len = total;
} else if total < self.log_shown_len {
self.log_view.set_value(&text);
self.log_shown_len = total;
}
}
fn tick(&mut self) -> Option<Widget> {
self.drain_scan();
if self.showing_log {
self.refresh_log_view();
}
// Keep verifying just-installed boards on a fixed cadence even when
// auto-scan is off (review #2): without this, a board could sit on
// "verifying alkane..." forever. Re-probes only when nothing else is in
// flight; each probe's Done decrements the give-up counter.
if self.installed_awaiting.is_empty() {
self.verify_cooldown = 0;
} else if self.scan.is_none() && self.refresh.is_none() && self.stock_op.is_none() {
if self.verify_cooldown == 0 {
let ips: Vec<String> = self.installed_awaiting.keys().cloned().collect();
self.start_refresh(ips.clone());
for ip in ips {
self.op_status
.insert(ip, "installed; verifying alkane...".into());
}
self.verify_cooldown = 10;
} else {
self.verify_cooldown -= 1;
}
}
self.drain_action();
self.drain_refresh();
self.drain_access_probe();
self.drain_restore();
self.drain_stock_op();
self.drain_report();
// A completed background log fetch yields a viewer dialog to show; return
// it so `dispatch` presents it modally after the App borrow is released
// (round 18 #12).
let to_show = self.drain_logfetch();
// The drains above run every fast tick (smooth scan progress); the
// auto-rescan scheduler + idle status only need ~1 Hz, so run them once
// per second.
self.tick_accum = self.tick_accum.wrapping_add(1);
// Flush a scan's batched row updates at most once per second (or right away
// once the scan has ended), so the whole-table refill runs ~1 Hz during a
// scan rather than on every fast tick (round 18 #12).
if self.rows_dirty && (!self.scanning || self.tick_accum.is_multiple_of(TICKS_PER_SEC)) {
self.rows_dirty = false;
self.fill_rows();
}
if !self.tick_accum.is_multiple_of(TICKS_PER_SEC) {
return to_show;
}
// 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 to_show; // 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 {
// Distinguish an explicit Stop from a Pause so the idle tick doesn't
// overwrite "Scan Stopped" with "paused" (round 19 #17).
let tail = if self.playing {
"auto-rescan off"
} else if self.scan_stopped {
"Scan Stopped"
} else {
"Scan Paused"
};
wx_rs::set_status_text(&format!("{} miners - {}", self.rows.len(), tail));
}
to_show
}
/// Cancel any in-flight scan, then start a fresh one over `lines`. The old
/// scan is signalled to stop and winds down cooperatively: it checks the flag
/// per address, so a handful of already-in-flight probes may still complete
/// after the new scan starts (round 18 #12). We accept that brief, bounded
/// overlap rather than block the UI by joining the old scan thread (which
/// could freeze it for up to the per-miner scan timeout); the probes target
/// live miners, so a momentary overlap is harmless.
/// Returns whether a scan actually started (false if deferred, e.g. mid-flash),
/// so callers don't overwrite the real status with a bogus "scanning..."
/// (round 18 #12).
fn begin_scan(&mut self, lines: Vec<String>) -> bool {
// 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 false;
}
// Symmetric to start_action's scan guard: don't start a scan (including an
// auto-rescan) while a config action or restore is writing to miners, so
// the two never race on the same unit (round 18 #12).
if self.action.is_some() || self.restore.is_some() || self.stock_op.is_some() {
wx_rs::set_status_text("operation in progress -- scan deferred");
return false;
}
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;
true
}
/// Start a fresh scan of the saved ranges.
fn start_new_scan(&mut self) {
if 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");
menu.menu_append(ID_HDR_AUTOSIZE_ALL, "Auto-size all columns");
// 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 col = self.header_menu_col?;
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);
}
}
// Auto-size every column to its content (round 19 #4). Done on demand
// (the columns are realised here, so the measurement is valid, unlike a
// rebuild-time autosize -- see rebuild_table). Ctrl+A selects all rows
// natively on the GtkTreeView, so this is the "resize all" companion.
ID_HDR_AUTOSIZE_ALL => {
if let Some(t) = self.table {
for pos in 0..t.dvlc_col_count() {
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 192.168.1.0/24\n range 192.168.1.3-192.168.1.234\n single 192.168.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);
// Scan concurrency (in-flight probes): higher scans faster but can starve
// per-miner telemetry; clamped to [MIN, MAX] on apply (round 19 #25).
auto_row.add_stretch(1);
let cc_lbl = Widget::static_text(dlg, "Concurrency:");
auto_row.add(cc_lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let cc_edit = Widget::text_ctrl(dlg, false);
cc_edit.set_value(&scan::load_scan_concurrency().to_string());
cc_edit.set_min_size(60, -1);
cc_edit.set_tool_tip(&format!(
"In-flight probes per scan ({}-{}). Higher is faster but can drop values on slow miners; default {}.",
scan::MIN_SCAN_CONCURRENCY, scan::MAX_SCAN_CONCURRENCY, scan::SCAN_CONCURRENCY_LIMIT
));
auto_row.add(cc_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;
self.ranges_concurrency = cc_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);
}
// Save the scan concurrency (round 19 #25), clamped in save_scan_concurrency.
if let Ok(n) = self.ranges_concurrency.get_value().trim().parse::<usize>() {
let _ = scan::save_scan_concurrency(n);
}
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.
/// Export toolbar button: open the column-picker dialog (round 19 #6), unless
/// there is nothing to export yet. Returns the dialog to show modally.
fn open_export_dialog(&mut self) -> Option<Widget> {
if self.rows.is_empty() {
wx_rs::set_status_text("nothing to export yet -- run a scan first");
return None;
}
Some(self.build_export_dialog())
}
/// A checklist of every export field (all on by default), with All/None and
/// Export/Cancel. OK -> do_export (round 19 #6).
fn build_export_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Export columns");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(dlg, "Choose the columns to export:"),
0,
sf::BORDER_ALL,
8,
);
let clb = Widget::check_list_box(dlg);
for name in crate::export::export_field_names() {
clb.clb_append(&name);
clb.clb_set_checked(clb.clb_count() - 1, true);
}
root.add(clb, 1, sf::EXPAND | sf::BORDER_ALL, 8);
let sel = Widget::box_sizer(false);
sel.add(
Widget::button(dlg, "All", ID_EXPORT_ALL),
0,
sf::BORDER_ALL,
4,
);
sel.add(
Widget::button(dlg, "None", ID_EXPORT_NONE),
0,
sf::BORDER_ALL,
4,
);
root.add_sizer(sel, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(
Widget::button(dlg, "Export", ID_EXPORT_OK),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, "Cancel", ID_EXPORT_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, 480);
dlg.fit(dlg);
self.export_dialog = dlg;
self.export_list = clb;
dlg
}
fn export_check_all(&self, checked: bool) {
let clb = self.export_list;
for i in 0..clb.clb_count() {
clb.clb_set_checked(i, checked);
}
}
/// Read the checked export fields, then save the filtered CSV. Default filename
/// carries a UTC date+time so successive exports don't collide (round 19 #5).
fn do_export(&mut self) {
let names = crate::export::export_field_names();
let clb = self.export_list;
let mut selected: HashSet<String> = HashSet::new();
for i in 0..clb.clb_count() {
if clb.clb_checked(i) {
if let Some(n) = names.get(i) {
selected.insert(n.clone());
}
}
}
self.export_dialog.close(1);
if selected.is_empty() {
wx_rs::set_status_text("no columns selected -- export cancelled");
return;
}
let default_name = format!("alkane-export-{}.csv", crate::export::timestamp_utc());
let Some(path) = Widget::save_file_dialog(
Widget::main_frame(),
"Export scan data",
&default_name,
"CSV files (*.csv)|*.csv|All files (*.*)|*.*",
) else {
return; // cancelled
};
let csv = crate::export::rows_to_csv_selected(&self.rows, &selected);
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.
/// The Bug report dialog: a type (Bug, UI change, Feature request), one text
/// box whose first line becomes the issue title, and whether to include the
/// recent activity log (scrubbed). Send files it through the report relay
/// (bug_report.rs) and shows the issue number, or the reason, in the dialog.
fn build_report_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let t = crate::i18n::t;
let dlg = Widget::dialog(frame, &t("Bug report"));
let root = Widget::box_sizer(true);
let kindrow = Widget::box_sizer(false);
kindrow.add(
Widget::static_text(dlg, &t("Type")),
0,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT,
8,
);
let kind = Widget::choice(dlg, ID_REPORT_KIND);
for k in crate::bug_report::Kind::ALL {
kind.choice_append(&t(k.label()));
}
kind.choice_set_selection(0);
kindrow.add(kind, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
root.add_sizer(kindrow, 0, sf::BORDER_ALL, 8);
root.add(
Widget::static_text(
dlg,
&t("Describe the problem or the idea. The first line becomes the title."),
),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT,
8,
);
// Word-wrap the report box so long lines wrap instead of running off the
// edge (issue #37).
let text = Widget::text_ctrl_wrapped(dlg);
text.set_min_size(560, 220);
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8);
let log = Widget::check_box(
dlg,
&t("Include the recent activity log (passwords removed)"),
);
log.set_checked(true);
root.add(log, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
root.add(
Widget::static_text(
dlg,
&t("Reports are public issues on gitea.bluefla.re. The app version and OS are included."),
),
0,
sf::BORDER_ALL,
8,
);
let status = Widget::static_text(dlg, "");
root.add(
status,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
8,
);
let btns = Widget::box_sizer(false);
// Hidden until a report is filed; then it becomes the "issue #N" link.
let open = Widget::button(dlg, "", ID_REPORT_OPEN);
open.show(false);
btns.add(open, 0, sf::BORDER_ALL, 6);
self.report_open_btn = open;
btns.add_stretch(1);
btns.add(
Widget::button(dlg, &t("Close"), ID_REPORT_CLOSE),
0,
sf::BORDER_ALL,
6,
);
btns.add(
Widget::button(dlg, &t("Send"), ID_REPORT_SEND),
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(600, 440);
dlg.fit(dlg);
self.report_dialog = dlg;
self.report_kind = kind;
self.report_text = text;
self.report_log = log;
self.report_status = status;
self.report_url = None;
dlg
}
/// Validate the Bug report dialog and send it on a worker thread.
fn send_report(&mut self) {
let t = crate::i18n::t;
if self.report_rx.is_some() {
return; // one send at a time
}
let text = self.report_text.get_value();
let text = text.trim();
if text.is_empty() {
self.report_status
.set_label(&t("Write what happened or what you would like first."));
return;
}
if text.chars().count() > crate::bug_report::MAX_TEXT_CHARS {
self.report_status.set_label(&format!(
"{} ({} / {})",
t("The text is too long"),
text.chars().count(),
crate::bug_report::MAX_TEXT_CHARS
));
return;
}
let kinds = crate::bug_report::Kind::ALL;
let kind = usize::try_from(self.report_kind.choice_get_selection())
.ok()
.and_then(|i| kinds.get(i).copied())
.unwrap_or(crate::bug_report::Kind::Bug);
let size = wx_rs::get_client_size();
let ctx = crate::bug_report::Context::current(
wx_rs::is_dark(),
crate::i18n::current().code(),
(size.width as i32, size.height as i32),
);
let log = self
.report_log
.is_checked()
.then(|| crate::bug_report::recent_log(&crate::logs::dump()));
let body = crate::bug_report::payload(kind, text, &ctx, log.as_deref());
self.report_status.set_label(&t("Sending..."));
self.report_rx = Some(crate::bug_report::send(body));
}
/// Show the Bug report result in the dialog once the send finishes.
fn drain_report(&mut self) {
let Some(rx) = &self.report_rx else { return };
let result = match rx.try_recv() {
Ok(r) => r,
Err(std::sync::mpsc::TryRecvError::Empty) => return,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err("the report was not sent".to_string())
}
};
self.report_rx = None;
let t = crate::i18n::t;
match result {
Ok(filed) => {
crate::logs::log(format!("bug report filed as issue #{}", filed.number));
self.report_status
.set_label(&t("Thank you for the report."));
self.report_text.set_value("");
self.report_kind.choice_set_selection(0);
if !filed.url.is_empty() {
self.report_url = Some(filed.url);
}
// Turn the filed issue into a clickable link (issue #50).
self.report_open_btn
.set_label(&format!("{} #{}", t("View issue"), filed.number));
self.report_open_btn.show(true);
self.report_dialog.layout();
}
Err(e) => {
crate::logs::log(format!("bug report not sent: {e}"));
self.report_status
.set_label(&format!("{} {e}", t("Not sent:")));
}
}
}
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 => return self.open_export_dialog(),
ID_EXPORT_OK => self.do_export(),
ID_EXPORT_CANCEL => self.export_dialog.close(0),
ID_EXPORT_ALL => self.export_check_all(true),
ID_EXPORT_NONE => self.export_check_all(false),
ID_SETTINGS => self.open_settings_menu(),
ID_LOG_TOGGLE => self.toggle_log_view(),
ID_BUG_REPORT => return Some(self.build_report_dialog()),
ID_REPORT_SEND => self.send_report(),
ID_REPORT_CLOSE => self.report_dialog.close(0),
ID_REPORT_OPEN => match &self.report_url {
Some(url) => {
wx_rs::launch_browser(url);
}
None => self.report_status.set_label(&crate::i18n::t(
"Send a report first; its issue opens here.",
)),
},
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_INSTALL_OK => self.apply_install_confirm(),
ID_INSTALL_RELOAD => self.reload_install_repo(),
ID_INSTALL_BROWSE => {
if let Some(path) = Widget::file_dialog(
self.install_dialog,
"Choose a local .afw to install",
) {
let name = std::path::Path::new(&path)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.clone());
self.install_local_label
.set_label(&format!("Using local file: {name}"));
let board = self.install_board.clone();
self.install_plan_label
.set_label(&afw_plan_text(&path, &board));
self.install_local_path = Some(path);
self.install_dialog.layout();
} else {
self.install_local_label
.set_label("(none; using the selected release above)");
self.install_plan_label.set_label(
"Flash plan: pick a local .afw above to see its tier and what it overwrites.",
);
self.install_local_path = None;
}
}
ID_INSTALL_CANCEL => {
self.install_ips.clear();
self.install_dialog.close(0);
}
ID_UNINSTALL_OK => self.apply_uninstall_confirm(),
ID_UNINSTALL_BROWSE => {
if let Some(path) = Widget::file_dialog(
self.uninstall_dialog,
"Choose a Bitmain stock firmware file (.tar.gz or .zip)",
) {
self.uninstall_firmware_input.set_value(&path);
// Picking a file means restoring from the file, not the
// on-board backup.
self.uninstall_onboard_check.set_checked(false);
}
}
ID_UNINSTALL_CANCEL => {
self.uninstall_ips.clear();
self.uninstall_dialog.close(0);
}
ID_POOLS_OK => self.apply_pools(),
ID_POOLS_CANCEL => self.pools_dialog.close(0),
// Pool-preset manager buttons (round 18 #8b).
ID_POOL_PRESETS_SAVE => self.apply_pool_presets(),
ID_POOL_PRESETS_CANCEL => self.pool_presets_dialog.close(0),
// Firmware profile/preset selector buttons (round 18 / G3).
ID_FWPRESET_OK => self.apply_fw_preset(),
ID_FWPRESET_CANCEL => self.fw_preset_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;
self.scan_stopped = false;
if !self.scanning {
self.start_new_scan();
}
}
ID_PAUSE => {
// Stop the auto-rescan loop (a scan in flight finishes).
self.playing = false;
self.scan_stopped = false;
wx_rs::set_status_text(&format!(
"{} miners - Scan 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.scan_stopped = true;
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 - Scan 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 => return 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.rebuild_table();
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::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::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
// (padlock), not text -- verify they are present.
let access_col = cols.iter().position(|c| *c == Column::Locked);
let health_col = cols.iter().position(|c| *c == Column::Health);
// 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::*;
#[test]
fn progress_bar_fills_proportionally() {
assert_eq!(ascii_bar(0), "[----------]");
assert_eq!(ascii_bar(50), "[#####-----]");
assert_eq!(ascii_bar(100), "[##########]");
assert_eq!(ascii_bar(70), "[#######---]");
// Over-100 is clamped, never panics.
assert_eq!(ascii_bar(200), "[##########]");
}
#[test]
fn stock_phase_percents_are_monotonic() {
let acq = stock_progress_pct("acquiring .afw...");
let ver = stock_progress_pct("verifying .afw...");
let inst = stock_progress_pct("installing zynq-7010 onto 10.0.0.5 (from stock)...");
assert!(acq < ver && ver < inst, "{acq} < {ver} < {inst}");
assert_eq!(stock_progress_pct("using local t.afw..."), acq);
assert_eq!(stock_progress_pct("restoring 10.0.0.5 to stock..."), inst);
}
/// 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),
text_bgs: Vec::new(),
}
}
#[test]
fn readable_reaches_aa_contrast_on_every_background() {
let light = [(255, 255, 255), (245, 245, 245)];
let dark = [(30, 30, 30), (41, 41, 41), (44, 44, 44)];
for fw in [
"braiins", "luxos", "vnish", "bixbit", "epic", "hiveon", "alkane",
] {
let c = firmware_color(fw).unwrap();
for bgs in [&light[..], &dark[..]] {
let r = readable(c, bgs);
for &bg in bgs {
assert!(
contrast_ratio(r, bg) >= MIN_TEXT_CONTRAST,
"{fw} {r:?} on {bg:?}"
);
}
}
}
// Already-readable colours are left alone; hue survives the nudge.
assert_eq!(readable((0, 0, 0), &light), (0, 0, 0));
let gold = readable((185, 150, 20), &light);
assert!(gold.0 > gold.1 && gold.1 > gold.2, "still gold: {gold:?}");
assert!((contrast_ratio((255, 255, 255), (0, 0, 0)) - 21.0).abs() < 0.01);
}
#[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 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");
}
}