diff --git a/crates/alkane-gui/src/fixtures.rs b/crates/alkane-gui/src/fixtures.rs new file mode 100644 index 00000000..f14f962f --- /dev/null +++ b/crates/alkane-gui/src/fixtures.rs @@ -0,0 +1,106 @@ +//! Bench-fleet fixtures: the expected hardware output of the 9 boards on +//! 10.255.1.0/24 (see ../../../HANDOFF.md section 7 and the parent project's +//! [removed]). These are the reference values the workflow tests compare +//! the application's actual output against, and the rows the offline +//! `ALKANE_FAKE_SCAN` demo mode renders. +//! +//! Hashrate/power/temp are representative per-model figures (the bench boards +//! are not always energised); the point of the fixtures is a fixed, known input +//! set so the transforms (formatting, KPI aggregation, sort, filter, the "slow" +//! band) can be checked deterministically. Update these if the bench inventory +//! changes. + +use crate::model::{is_slow, MinerRow}; + +/// One fixture board, pre-transform. `expected` of 0.0 means "band unknown". +struct Board { + ip: &'static str, + model: &'static str, + firmware: &'static str, + hashrate: f64, + expected: f64, + power: f64, + temp: f64, + fan: f64, + worker: &'static str, + mining: bool, +} + +impl Board { + fn into_row(self) -> MinerRow { + let slow = is_slow(self.mining, self.hashrate, self.expected); + // A few extra metrics so the demo/offline mode shows non-empty values + // for some of the additional columns. + let last_octet: u8 = self.ip.rsplit('.').next().and_then(|s| s.parse().ok()).unwrap_or(0); + let (boards, chips, efficiency) = if self.mining { + (Some(3u32), Some(210u32), if self.hashrate > 0.0 { self.power / self.hashrate } else { 0.0 }) + } else { + (None, None, 0.0) + }; + MinerRow { + ip: self.ip.to_string(), + selected: false, + model: self.model.to_string(), + firmware: self.firmware.to_string(), + hashrate_ths: self.hashrate, + expected_ths: self.expected, + efficiency, + power_w: self.power, + chip_temp_c: self.temp, + fan_rpm: self.fan, + worker: self.worker.to_string(), + is_mining: self.mining, + slow, + mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)), + hostname: format!("miner-{last_octet}"), + hashboards: boards, + expected_hashboards: Some(3), + total_chips: chips, + psu_fan_rpm: if self.mining { self.fan * 0.9 } else { 0.0 }, + uptime_secs: if self.mining { 3600 * 24 * 2 + 3600 * 5 } else { 0 }, + light_flashing: Some(false), + pool_url: if self.worker.is_empty() { String::new() } else { "stratum+tcp://pool.blueflare:3333".to_string() }, + operating_state: if self.mining { "mining".to_string() } else { "idle".to_string() }, + ..Default::default() + } + } +} + +/// The 9 bench boards. Two are idle (S17 stock, WardenOS dev), one is slow +/// (S21 Pro aml stock at ~30% of expected); the other six hash normally. +/// +/// Derived totals (used by the workflow tests): +/// total = 9, hashing = 6, slow = 1, not hashing = 2, +/// total hashrate = 685.0 TH/s, total power = 21300 W. +pub fn bench_fleet() -> Vec { + let boards = [ + Board { ip: "10.255.1.112", model: "Antminer S17", firmware: "Stock", + hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0, + worker: "", mining: false }, + Board { ip: "10.255.1.166", model: "Antminer S19", firmware: "[removed] 1.2", + hashrate: 95.0, expected: 96.0, power: 3250.0, temp: 65.0, fan: 4200.0, + worker: "blueflare.s19", mining: true }, + Board { ip: "10.255.1.152", model: "Antminer S19j Pro", firmware: "[removed] 1.2", + hashrate: 100.0, expected: 104.0, power: 3100.0, temp: 62.0, fan: 3900.0, + worker: "blueflare.s19jpro", mining: true }, + Board { ip: "10.255.1.167", model: "Antminer S19k Pro", firmware: "[removed] 1.2", + hashrate: 120.0, expected: 128.0, power: 3300.0, temp: 68.0, fan: 4500.0, + worker: "blueflare.s19kpro", mining: true }, + Board { ip: "10.255.1.149", model: "Antminer S21 Pro", firmware: "Stock", + hashrate: 60.0, expected: 200.0, power: 1500.0, temp: 55.0, fan: 3000.0, + worker: "blueflare.s21pro", mining: true }, // slow: 60/200 = 30% + Board { ip: "10.255.1.126", model: "WhatsMiner M30S", firmware: "WMOS H3", + hashrate: 92.0, expected: 96.0, power: 3400.0, temp: 70.0, fan: 4800.0, + worker: "blueflare.h3", mining: true }, + Board { ip: "10.255.1.131", model: "WhatsMiner M30S+", firmware: "WMOS H616", + hashrate: 100.0, expected: 100.0, power: 3450.0, temp: 71.0, fan: 4900.0, + worker: "blueflare.h616", mining: true }, + Board { ip: "10.255.1.148", model: "WhatsMiner M50", firmware: "WMOS CB4", + hashrate: 118.0, expected: 122.0, power: 3300.0, temp: 66.0, fan: 4600.0, + worker: "blueflare.m50", mining: true }, + Board { ip: "10.255.1.115", model: "Antminer S19", firmware: "WardenOS dev", + hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0, + worker: "", mining: false }, + ]; + boards.into_iter().map(Board::into_row).collect() +} diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 43e7d910..5b25f36f 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -1,6 +1,7 @@ //! alkane-toolkit — primary view (docs/UI-SPEC.md). //! Pure-Rust wxWidgets app on the vendored, patched wx-rs. +mod fixtures; mod model; mod scan; mod ui; @@ -8,8 +9,17 @@ mod ui; use wx_rs; fn main() { + // Headless workflow self-test: render the bench-fleet fixtures through the + // real widgets and check the table + KPIs against the expected hardware + // output. Run under a virtual display (see scripts/ui-selftest.sh). + if std::env::var_os("ALKANE_SELFTEST").is_some() { + std::process::exit(run_selftest()); + } + // Bootstrap the wx app + main frame (upstream bridge). wx_rs::init_app("alkane-toolkit", 1280, 800); + // Follow the system light/dark appearance. + wx_rs::set_appearance_system(); // Build the UI-SPEC primary view into the frame. let frame = wx_rs::Widget::main_frame(); @@ -23,3 +33,18 @@ fn main() { // a 1 s timer drains it on the main thread. wx_rs::run_app(); } + +fn run_selftest() -> i32 { + // Force offline: never touch the network during the self-test. + std::env::set_var(scan::FAKE_SCAN_ENV, "1"); + wx_rs::init_app("alkane-toolkit", 1280, 800); + let frame = wx_rs::Widget::main_frame(); + let mut app = ui::build(frame); + let ok = app.run_fixture_selftest(); + println!("SELFTEST {}", if ok { "PASS" } else { "FAIL" }); + if ok { + 0 + } else { + 1 + } +} diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 8459e50a..61716f67 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -2,19 +2,106 @@ use std::collections::{HashMap, HashSet}; +/// A miner counts as "slow" when it is mining but running below this fraction +/// of its model's expected hashrate (UI-SPEC "Slow" band). A missing expected +/// hashrate (0.0) means the band is unknown, so the miner is never "slow". +pub const SLOW_THRESHOLD: f64 = 0.8; + +/// The single source of truth for the "slow" classification, shared by the +/// live scan (`scan::to_row`) and the fixtures/tests, so the expected-vs-actual +/// comparison exercises the same rule the app uses. +pub fn is_slow(is_mining: bool, hashrate_ths: f64, expected_ths: f64) -> bool { + is_mining && expected_ths > 0.0 && hashrate_ths < SLOW_THRESHOLD * expected_ths +} + +/// Format a value in its base unit with an SI prefix chosen so the number stays +/// compact: the prefix puts the mantissa in [1, 1000), then it is shown with 1 +/// decimal below 100 and no decimal from 100 up (so 21300 W -> "21.3 kW", +/// 685e12 H/s -> "685 TH/s", 6.8e12 -> "6.8 TH/s"). Zero renders as "0 ". +pub fn format_si(value_base: f64, unit: &str) -> String { + if !value_base.is_finite() || value_base <= 0.0 { + return format!("0 {unit}"); + } + const PREFIXES: [&str; 8] = ["", "k", "M", "G", "T", "P", "E", "Z"]; + let mut v = value_base; + let mut i = 0usize; + while v >= 1000.0 && i < PREFIXES.len() - 1 { + v /= 1000.0; + i += 1; + } + let num = if v >= 100.0 { + format!("{v:.0}") + } else { + format!("{v:.1}") + }; + format!("{num} {}{unit}", PREFIXES[i]) +} + +/// Compact human duration (e.g. "3d 4h", "5h 12m", "42m", "18s"). +pub fn format_uptime(secs: u64) -> String { + if secs == 0 { + return String::new(); + } + let d = secs / 86_400; + let h = (secs % 86_400) / 3600; + let m = (secs % 3600) / 60; + let s = secs % 60; + if d > 0 { + format!("{d}d {h}h") + } else if h > 0 { + format!("{h}h {m}m") + } else if m > 0 { + format!("{m}m") + } else { + format!("{s}s") + } +} + +/// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the +/// scalar fields the table can display. Absent metrics are `None` / empty / +/// 0.0 and render as a blank cell. #[derive(Debug, Clone, Default)] pub struct MinerRow { pub ip: String, pub selected: bool, + // identity pub model: String, + pub mac: String, + pub hostname: String, + pub serial: String, pub firmware: String, + pub api_version: String, + pub control_board: String, + // performance pub hashrate_ths: f64, - #[allow(dead_code)] // used by the "slow" band view in later milestones pub expected_ths: f64, + #[allow(dead_code)] // retained for the "slow" band; not shown as its own column + pub efficiency: f64, pub power_w: f64, + pub tuning_percent: Option, + // thermal / cooling pub chip_temp_c: f64, + pub fluid_temp_c: f64, + pub outlet_temp_c: f64, pub fan_rpm: f64, + pub psu_fan_rpm: f64, + pub fan_count: Option, + pub expected_fans: Option, + // hardware counts + pub total_chips: Option, + pub expected_chips: Option, + pub hashboards: Option, + pub expected_hashboards: Option, + // pool pub worker: String, + pub pool_url: String, + // shares + pub best_share: Option, + pub session_best_share: Option, + // state + pub uptime_secs: u64, + pub light_flashing: Option, + pub operating_state: String, pub is_mining: bool, pub slow: bool, } @@ -43,7 +130,8 @@ impl MinerRow { } } -/// Model columns. Sel and Ip are fixed (checkbox + always-on IP column). +/// Model columns. Sel and Ip are fixed (checkbox + always-on IP column); the +/// rest map 1:1 to a scannable metric and can be shown/hidden/reordered. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Column { Sel, @@ -56,9 +144,34 @@ pub enum Column { Worker, Model, Status, + ExpectedHashrate, + Efficiency, + FluidTemp, + OutletTemp, + PsuFan, + FanCount, + ExpectedFans, + TotalChips, + ExpectedChips, + Hashboards, + ExpectedHashboards, + Mac, + Hostname, + Serial, + ApiVersion, + ControlBoard, + Uptime, + Light, + OperatingState, + BestShare, + SessionBestShare, + TuningPercent, + PoolUrl, } -pub const ALL_COLUMNS: [Column; 10] = [ +/// Every column, in registry order. Sel + Ip first, then the default-visible +/// set (UI-SPEC order), then all remaining metrics. +pub const ALL_COLUMNS: [Column; 33] = [ Column::Sel, Column::Ip, Column::Hashrate, @@ -69,6 +182,41 @@ pub const ALL_COLUMNS: [Column; 10] = [ Column::Worker, Column::Model, Column::Status, + Column::ExpectedHashrate, + Column::Efficiency, + Column::FluidTemp, + Column::OutletTemp, + Column::PsuFan, + Column::FanCount, + Column::ExpectedFans, + Column::TotalChips, + Column::ExpectedChips, + Column::Hashboards, + Column::ExpectedHashboards, + Column::Mac, + Column::Hostname, + Column::Serial, + Column::ApiVersion, + Column::ControlBoard, + Column::Uptime, + Column::Light, + Column::OperatingState, + Column::BestShare, + Column::SessionBestShare, + Column::TuningPercent, + Column::PoolUrl, +]; + +/// The columns shown by default (UI-SPEC), after Sel + Ip. +pub const DEFAULT_VISIBLE: [Column; 8] = [ + Column::Hashrate, + Column::Power, + Column::ChipTemp, + Column::Cooling, + Column::Firmware, + Column::Worker, + Column::Model, + Column::Status, ]; impl Column { @@ -76,84 +224,200 @@ impl Column { match self { Column::Sel => "", Column::Ip => "IP", - Column::Hashrate => "Hashrate (TH/s)", - Column::Power => "Power (W)", - Column::ChipTemp => "Chip temp (C)", - Column::Cooling => "Cooling (RPM)", + Column::Hashrate => "Hashrate", + Column::Power => "Power", + Column::ChipTemp => "Chip temp", + Column::Cooling => "Fan (RPM)", Column::Firmware => "Firmware", Column::Worker => "Pool worker", Column::Model => "Model", Column::Status => "Status", + Column::ExpectedHashrate => "Expected HR", + Column::Efficiency => "Efficiency (J/TH)", + Column::FluidTemp => "Fluid temp", + Column::OutletTemp => "Outlet temp", + Column::PsuFan => "PSU fan (RPM)", + Column::FanCount => "Fans", + Column::ExpectedFans => "Fans (exp)", + Column::TotalChips => "Chips", + Column::ExpectedChips => "Chips (exp)", + Column::Hashboards => "Boards", + Column::ExpectedHashboards => "Boards (exp)", + Column::Mac => "MAC", + Column::Hostname => "Hostname", + Column::Serial => "Serial", + Column::ApiVersion => "API ver", + Column::ControlBoard => "Control board", + Column::Uptime => "Uptime", + Column::Light => "Fault light", + Column::OperatingState => "State", + Column::BestShare => "Best share", + Column::SessionBestShare => "Session best", + Column::TuningPercent => "Tuning %", + Column::PoolUrl => "Pool URL", } } pub fn width(self) -> i32 { match self { - Column::Sel => 30, - Column::Ip => 120, - Column::Hashrate => 110, + Column::Sel => 28, + Column::Ip => 130, + Column::Hashrate | Column::ExpectedHashrate => 110, Column::Power => 90, - Column::ChipTemp => 100, - Column::Cooling => 100, - Column::Firmware => 180, - Column::Worker => 160, - Column::Model => 140, - Column::Status => 100, + Column::ChipTemp | Column::FluidTemp | Column::OutletTemp => 95, + Column::Cooling | Column::PsuFan => 100, + Column::Firmware => 160, + Column::Worker => 150, + Column::Model => 150, + Column::Status => 95, + Column::Efficiency => 120, + Column::FanCount | Column::TotalChips | Column::Hashboards => 70, + Column::ExpectedFans + | Column::ExpectedChips + | Column::ExpectedHashboards + | Column::TuningPercent => 90, + Column::Mac | Column::Hostname | Column::Serial => 150, + Column::ApiVersion | Column::Light => 90, + Column::ControlBoard => 130, + Column::Uptime => 100, + Column::OperatingState => 100, + Column::BestShare | Column::SessionBestShare => 110, + Column::PoolUrl => 220, } } - /// Sort key (numeric columns compare as f64; others as lowercase strings). + /// Whether the column holds a continuous numeric value. Such columns sort + /// numerically and are excluded from the Excel-style value filter (a + /// per-value checklist only makes sense for categorical data). + pub fn is_numeric(self) -> bool { + matches!( + self, + Column::Hashrate + | Column::ExpectedHashrate + | Column::Power + | Column::Efficiency + | Column::ChipTemp + | Column::FluidTemp + | Column::OutletTemp + | Column::Cooling + | Column::PsuFan + | Column::FanCount + | Column::ExpectedFans + | Column::TotalChips + | Column::ExpectedChips + | Column::Hashboards + | Column::ExpectedHashboards + | Column::Uptime + | Column::BestShare + | Column::SessionBestShare + | Column::TuningPercent + ) + } + + /// Sort key. Numeric columns compare by their underlying number (absent = + /// -inf so blanks sort to the bottom of a descending sort); others compare + /// as lowercase strings. pub fn sort_key(&self, r: &MinerRow) -> SortKey { + let none = f64::NEG_INFINITY; match self { Column::Sel => SortKey::Num(if r.selected { 1.0 } else { 0.0 }), - Column::Ip => SortKey::Str(r.ip.clone()), Column::Hashrate => SortKey::Num(r.hashrate_ths), + Column::ExpectedHashrate => SortKey::Num(r.expected_ths), Column::Power => SortKey::Num(r.power_w), + Column::Efficiency => SortKey::Num(if r.efficiency > 0.0 { r.efficiency } else { none }), Column::ChipTemp => SortKey::Num(r.chip_temp_c), + Column::FluidTemp => SortKey::Num(r.fluid_temp_c), + Column::OutletTemp => SortKey::Num(r.outlet_temp_c), Column::Cooling => SortKey::Num(r.fan_rpm), - Column::Firmware => SortKey::Str(r.firmware.to_lowercase()), - Column::Worker => SortKey::Str(r.worker.to_lowercase()), - Column::Model => SortKey::Str(r.model.to_lowercase()), - Column::Status => SortKey::Str(r.status().to_string()), + Column::PsuFan => SortKey::Num(r.psu_fan_rpm), + Column::FanCount => SortKey::Num(r.fan_count.map(|v| v as f64).unwrap_or(none)), + Column::ExpectedFans => SortKey::Num(r.expected_fans.map(|v| v as f64).unwrap_or(none)), + Column::TotalChips => SortKey::Num(r.total_chips.map(|v| v as f64).unwrap_or(none)), + Column::ExpectedChips => SortKey::Num(r.expected_chips.map(|v| v as f64).unwrap_or(none)), + Column::Hashboards => SortKey::Num(r.hashboards.map(|v| v as f64).unwrap_or(none)), + Column::ExpectedHashboards => { + SortKey::Num(r.expected_hashboards.map(|v| v as f64).unwrap_or(none)) + } + Column::Uptime => SortKey::Num(if r.uptime_secs > 0 { r.uptime_secs as f64 } else { none }), + Column::BestShare => SortKey::Num(r.best_share.unwrap_or(none)), + Column::SessionBestShare => SortKey::Num(r.session_best_share.unwrap_or(none)), + Column::TuningPercent => { + SortKey::Num(r.tuning_percent.map(|v| v as f64).unwrap_or(none)) + } + _ => SortKey::Str(self.cell(r).to_lowercase()), } } pub fn cell(&self, r: &MinerRow) -> String { + let num = |v: f64, dp: usize, suffix: &str| -> String { + if v > 0.0 { + match dp { + 0 => format!("{v:.0}{suffix}"), + _ => format!("{v:.1}{suffix}"), + } + } else { + String::new() + } + }; + let count = |v: Option| -> String { v.map(|n| n.to_string()).unwrap_or_default() }; match self { Column::Sel => String::new(), Column::Ip => r.ip.clone(), Column::Hashrate => { if r.hashrate_ths > 0.0 { - format!("{:.1}", r.hashrate_ths) + format_si(r.hashrate_ths * 1e12, "H/s") + } else { + String::new() + } + } + Column::ExpectedHashrate => { + if r.expected_ths > 0.0 { + format_si(r.expected_ths * 1e12, "H/s") } else { String::new() } } Column::Power => { if r.power_w > 0.0 { - format!("{:.0}", r.power_w) - } else { - String::new() - } - } - Column::ChipTemp => { - if r.chip_temp_c > 0.0 { - format!("{:.1}", r.chip_temp_c) - } else { - String::new() - } - } - Column::Cooling => { - if r.fan_rpm > 0.0 { - format!("{:.0}", r.fan_rpm) + format_si(r.power_w, "W") } else { String::new() } } + Column::Efficiency => num(r.efficiency, 1, ""), + Column::ChipTemp => num(r.chip_temp_c, 1, " C"), + Column::FluidTemp => num(r.fluid_temp_c, 1, " C"), + Column::OutletTemp => num(r.outlet_temp_c, 1, " C"), + Column::Cooling => num(r.fan_rpm, 0, ""), + Column::PsuFan => num(r.psu_fan_rpm, 0, ""), + Column::FanCount => count(r.fan_count), + Column::ExpectedFans => count(r.expected_fans), + Column::TotalChips => count(r.total_chips), + Column::ExpectedChips => count(r.expected_chips), + Column::Hashboards => count(r.hashboards), + Column::ExpectedHashboards => count(r.expected_hashboards), Column::Firmware => r.firmware.clone(), Column::Worker => r.worker.clone(), + Column::PoolUrl => r.pool_url.clone(), Column::Model => r.model.clone(), + Column::Mac => r.mac.clone(), + Column::Hostname => r.hostname.clone(), + Column::Serial => r.serial.clone(), + Column::ApiVersion => r.api_version.clone(), + Column::ControlBoard => r.control_board.clone(), Column::Status => r.status().to_string(), + Column::Uptime => format_uptime(r.uptime_secs), + Column::Light => match r.light_flashing { + Some(true) => "on".to_string(), + Some(false) => "off".to_string(), + None => String::new(), + }, + Column::OperatingState => r.operating_state.clone(), + Column::BestShare => r.best_share.map(|v| format_si(v, "")).unwrap_or_default(), + Column::SessionBestShare => { + r.session_best_share.map(|v| format_si(v, "")).unwrap_or_default() + } + Column::TuningPercent => r.tuning_percent.map(|v| format!("{v}%")).unwrap_or_default(), } } } @@ -175,21 +439,11 @@ pub struct ViewState { impl Default for ViewState { fn default() -> Self { - // UI-SPEC default order: checkbox, IP, hashrate, power, chip temp, - // cooling, firmware, pool worker, then the rest. - let order = vec![ - Column::Sel, - Column::Ip, - Column::Hashrate, - Column::Power, - Column::ChipTemp, - Column::Cooling, - Column::Firmware, - Column::Worker, - Column::Model, - Column::Status, - ]; - let visible: HashSet = order.iter().copied().collect(); + // Registry order for `order`; only Sel + Ip + DEFAULT_VISIBLE are shown. + let order: Vec = ALL_COLUMNS.to_vec(); + let mut visible: HashSet = DEFAULT_VISIBLE.iter().copied().collect(); + visible.insert(Column::Sel); + visible.insert(Column::Ip); ViewState { order, visible, sort: None, filters: HashMap::new() } } } @@ -207,46 +461,36 @@ impl ViewState { c == Column::Sel || c == Column::Ip } - /// Rows that pass every active filter (AND across, OR within). + /// Apply a drag-reorder of the visible columns. `new_visible` is the visible + /// columns in their new display order; it must be a permutation of the + /// currently-visible set with Sel still first. The new order is spliced back + /// into `order`, leaving hidden columns in their existing slots, so a + /// reorder while some column is hidden never drops or duplicates a column. + pub fn apply_visible_reorder(&mut self, new_visible: &[Column]) { + let disp = self.display_columns(); + if new_visible.len() != disp.len() || new_visible.first() != Some(&Column::Sel) { + return; + } + let want: HashSet = disp.iter().copied().collect(); + let got: HashSet = new_visible.iter().copied().collect(); + if want != got { + return; // not a permutation of the visible columns: ignore + } + let mut next = new_visible.iter().copied(); + self.order = self + .order + .iter() + .map(|&c| if want.contains(&c) { next.next().unwrap_or(c) } else { c }) + .collect(); + } + + /// Rows that pass every active filter (AND across columns, OR within one). pub fn passes_filters(&self, r: &MinerRow) -> bool { self.filters.iter().all(|(col, allowed)| { - let v = match col { - Column::Sel => return true, - Column::Ip => r.ip.clone(), - Column::Hashrate => { - if r.hashrate_ths > 0.0 { - format!("{:.1}", r.hashrate_ths) - } else { - String::new() - } - } - Column::Power => { - if r.power_w > 0.0 { - format!("{:.0}", r.power_w) - } else { - String::new() - } - } - Column::ChipTemp => { - if r.chip_temp_c > 0.0 { - format!("{:.1}", r.chip_temp_c) - } else { - String::new() - } - } - Column::Cooling => { - if r.fan_rpm > 0.0 { - format!("{:.0}", r.fan_rpm) - } else { - String::new() - } - } - Column::Firmware => r.firmware.clone(), - Column::Worker => r.worker.clone(), - Column::Model => r.model.clone(), - Column::Status => r.status().to_string(), - }; - allowed.contains(&v) + if *col == Column::Sel { + return true; + } + allowed.contains(&col.cell(r)) }) } @@ -297,3 +541,177 @@ pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis { } k } + +#[cfg(test)] +mod tests { + //! Offline workflow tests: feed the bench-fleet fixtures (the expected + //! hardware output) through the app's transforms and assert the produced + //! result. These need no display and run under plain `cargo test`. + use super::*; + use crate::fixtures::bench_fleet; + + fn full_view() -> (Vec, ViewState, Vec) { + let rows = bench_fleet(); + let view = ViewState::default(); + let idx = view.view(&rows); + (rows, view, idx) + } + + #[test] + fn kpis_match_expected_hardware_output() { + let (rows, _v, idx) = full_view(); + let k = compute_kpis(&rows, &idx); + assert_eq!(k.total, 9, "total miners"); + assert_eq!(k.hashing, 6, "hashing"); + assert_eq!(k.slow, 1, "slow"); + assert_eq!(k.not_hashing, 2, "not hashing"); + assert!((k.total_hashrate_ths - 685.0).abs() < 1e-9, "hashrate {}", k.total_hashrate_ths); + assert!((k.total_power_w - 21300.0).abs() < 1e-9, "power {}", k.total_power_w); + assert_eq!(k.total, k.hashing + k.slow + k.not_hashing); + } + + #[test] + fn slow_band_classification() { + assert!(is_slow(true, 60.0, 200.0)); + assert!(!is_slow(true, 90.0, 100.0)); + assert!(!is_slow(true, 80.0, 100.0)); + assert!(!is_slow(false, 0.0, 200.0)); + assert!(!is_slow(true, 1.0, 0.0)); + } + + #[test] + fn si_formatting() { + assert_eq!(format_si(21300.0, "W"), "21.3 kW"); + assert_eq!(format_si(685e12, "H/s"), "685 TH/s"); + assert_eq!(format_si(95e12, "H/s"), "95.0 TH/s"); + assert_eq!(format_si(6.8e12, "H/s"), "6.8 TH/s"); + assert_eq!(format_si(3250.0, "W"), "3.2 kW"); + assert_eq!(format_si(0.0, "W"), "0 W"); + } + + #[test] + fn cell_formatting_blanks_zeroes() { + let rows = bench_fleet(); + let s17 = rows.iter().find(|r| r.ip == "10.255.1.112").unwrap(); + assert_eq!(Column::Hashrate.cell(s17), ""); + assert_eq!(Column::Power.cell(s17), ""); + assert_eq!(Column::ChipTemp.cell(s17), ""); + assert_eq!(Column::Status.cell(s17), "not hashing"); + + let s21 = rows.iter().find(|r| r.ip == "10.255.1.149").unwrap(); + assert_eq!(Column::Hashrate.cell(s21), "60.0 TH/s"); + assert_eq!(Column::Power.cell(s21), "1.5 kW"); + assert_eq!(Column::Status.cell(s21), "slow"); + } + + #[test] + fn default_view_is_insertion_order() { + let (rows, _v, idx) = full_view(); + let ips: Vec<&str> = idx.iter().map(|&i| rows[i].ip.as_str()).collect(); + assert_eq!(ips[0], "10.255.1.112"); + assert_eq!(ips.len(), 9); + } + + #[test] + fn sort_by_hashrate() { + let rows = bench_fleet(); + let mut view = ViewState::default(); + view.sort = Some((Column::Hashrate, false)); + let idx = view.view(&rows); + assert_eq!(rows[idx[0]].ip, "10.255.1.167"); + assert!(rows[idx[0]].hashrate_ths >= rows[idx[1]].hashrate_ths); + view.sort = Some((Column::Hashrate, true)); + let idx = view.view(&rows); + assert_eq!(rows[idx[0]].hashrate_ths, 0.0); + } + + #[test] + fn filter_by_status_slow() { + let rows = bench_fleet(); + let mut view = ViewState::default(); + let mut allowed = HashSet::new(); + allowed.insert("slow".to_string()); + view.filters.insert(Column::Status, allowed); + let idx = view.view(&rows); + assert_eq!(idx.len(), 1); + assert_eq!(rows[idx[0]].ip, "10.255.1.149"); + } + + #[test] + fn default_visible_is_the_ui_spec_set() { + let view = ViewState::default(); + let disp = view.display_columns(); + // Sel, Ip, then the 8 default columns in order. + assert_eq!(disp[0], Column::Sel); + assert_eq!(disp[1], Column::Ip); + assert_eq!(&disp[2..], &DEFAULT_VISIBLE[..]); + // hidden-by-default metrics are still selectable (present in order). + assert!(view.order.contains(&Column::Mac)); + assert!(view.order.contains(&Column::Uptime)); + assert!(!view.visible.contains(&Column::Mac)); + } + + #[test] + fn hiding_a_column_shifts_display_columns() { + let mut view = ViewState::default(); + let before = view.display_columns(); + assert!(before.contains(&Column::Power)); + view.visible.remove(&Column::Power); + let after = view.display_columns(); + assert!(!after.contains(&Column::Power)); + assert_eq!(after[0], Column::Sel); + assert_eq!(after[1], Column::Ip); + assert_eq!(after.len(), before.len() - 1); + let hr = after.iter().position(|c| *c == Column::Hashrate).unwrap(); + assert_eq!(after[hr + 1], Column::ChipTemp); + } + + #[test] + fn showing_a_hidden_metric_adds_a_column() { + let mut view = ViewState::default(); + assert!(!view.display_columns().contains(&Column::Uptime)); + view.visible.insert(Column::Uptime); + assert!(view.display_columns().contains(&Column::Uptime)); + } + + #[test] + fn reorder_with_hidden_column_keeps_all_columns() { + let mut view = ViewState::default(); + view.visible.remove(&Column::Power); + let mut vis = view.display_columns(); + vis.swap(2, 3); // swap Hashrate and ChipTemp + view.apply_visible_reorder(&vis); + assert!(view.order.contains(&Column::Power), "hidden column dropped!"); + assert_eq!(view.order.len(), ALL_COLUMNS.len()); + let set: HashSet = view.order.iter().copied().collect(); + assert_eq!(set.len(), ALL_COLUMNS.len()); + let disp = view.display_columns(); + let hr = disp.iter().position(|c| *c == Column::Hashrate).unwrap(); + let ct = disp.iter().position(|c| *c == Column::ChipTemp).unwrap(); + assert!(ct < hr, "reorder not applied"); + assert_eq!(view.order[0], Column::Sel); + assert_eq!(view.order[1], Column::Ip); + } + + #[test] + fn reorder_rejects_non_permutation() { + let mut view = ViewState::default(); + let before = view.order.clone(); + view.apply_visible_reorder(&[Column::Ip, Column::Sel, Column::Hashrate]); + assert_eq!(view.order, before); + } + + #[test] + fn selection_survives_upsert() { + let mut rows = bench_fleet(); + rows[1].selected = true; + let ip = rows[1].ip.clone(); + let mut update = bench_fleet()[1].clone(); + update.hashrate_ths = 12.3; + let new = update.upsert_into(&mut rows); + assert!(!new, "same IP is an update, not an insert"); + let r = rows.iter().find(|r| r.ip == ip).unwrap(); + assert!(r.selected, "selection preserved across upsert"); + assert_eq!(r.hashrate_ths, 12.3, "data updated"); + } +} diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 0fcd1ed6..4cd46de2 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -5,13 +5,22 @@ use crate::model::MinerRow; use asic_rs::MinerFactory; use asic_rs::core::traits::miner::Miner; use futures_util::StreamExt; +use std::collections::HashSet; use std::net::Ipv4Addr; use std::path::PathBuf; use std::sync::mpsc::{channel, Receiver}; pub enum ScanMsg { + /// A new scan started: `total` addresses to probe, and the exact set of + /// target IPs (as strings) so the UI can drop miners no longer in range. + Started { total: usize, targets: HashSet }, + /// Progress update: `done` of `total` addresses probed. + Progress { done: usize, total: usize }, + /// A miner was identified. Row(MinerRow), - SubnetDone(String), + /// The scan finished (label is informational). + Done(String), + /// The scan could not run. Failed(String), } @@ -63,9 +72,181 @@ pub fn parse_cidr(s: &str) -> Option<(Ipv4Addr, u8)> { } } -/// Spawn the scan thread. One tokio runtime thread; subnets scanned in order. -pub fn start_scan(subnets: Vec) -> Receiver { +/// Upper bound on how many addresses a single line (or the whole target set) +/// may expand to, so a stray `10.0.0.0/8` can't allocate gigabytes / freeze the +/// app. A million addresses is already far more than any real miner LAN. +pub const MAX_ADDRS: u64 = 1_000_000; + +/// Parse one scan-range line into its address list. Accepts: +/// - CIDR: `10.253.1.0/24` +/// - single IP: `10.253.1.5` +/// - full range: `10.253.1.3-10.253.1.234` (inclusive) +/// - short range: `10.253.1.3-234` (end = same /24, last octet) +pub fn parse_line(line: &str) -> Result, String> { + let line = line.trim(); + if line.is_empty() { + return Ok(Vec::new()); + } + if let Some((_a, _p)) = line.split_once('/') { + let (addr, prefix) = parse_cidr(line).ok_or_else(|| format!("bad CIDR: {line}"))?; + let base = u32::from(addr) & prefix_mask(prefix); + let count = 1u64 << (32 - prefix as u32); + if count > MAX_ADDRS { + return Err(format!("CIDR too large (> {MAX_ADDRS} addresses): {line}")); + } + return Ok((0..count).map(|i| Ipv4Addr::from(base + i as u32)).collect()); + } + if let Some((start_s, end_s)) = line.split_once('-') { + let start: Ipv4Addr = start_s + .trim() + .parse() + .map_err(|_| format!("bad start address: {start_s}"))?; + let end_s = end_s.trim(); + // full end address, or a bare last-octet sharing the start's /24 + let end: Ipv4Addr = if end_s.contains('.') { + end_s.parse().map_err(|_| format!("bad end address: {end_s}"))? + } else { + let o: u8 = end_s.parse().map_err(|_| format!("bad range end: {end_s}"))?; + let s = start.octets(); + Ipv4Addr::new(s[0], s[1], s[2], o) + }; + let (s, e) = (u32::from(start), u32::from(end)); + if s > e { + return Err(format!("range start after end: {line}")); + } + if (e - s) as u64 >= MAX_ADDRS { + return Err(format!("range too large (> {MAX_ADDRS} addresses): {line}")); + } + return Ok((s..=e).map(Ipv4Addr::from).collect()); + } + // single address + let addr: Ipv4Addr = line.parse().map_err(|_| format!("bad address: {line}"))?; + Ok(vec![addr]) +} + +fn prefix_mask(prefix: u8) -> u32 { + if prefix == 0 { + 0 + } else { + u32::MAX << (32 - prefix as u32) + } +} + +/// Parse and de-duplicate all scan-range lines into a sorted target list. +pub fn parse_targets(lines: &[String]) -> Result, String> { + let mut set = std::collections::BTreeSet::new(); + for line in lines { + for ip in parse_line(line)? { + set.insert(u32::from(ip)); + } + if set.len() as u64 > MAX_ADDRS { + return Err(format!("too many addresses across ranges (> {MAX_ADDRS})")); + } + } + Ok(set.into_iter().map(Ipv4Addr::from).collect()) +} + +/// Validate scan-range lines; returns an error message if any line is bad or +/// the set is empty. +pub fn validate_ranges(lines: &[String]) -> Result<(), String> { + let ips = parse_targets(lines)?; + if ips.is_empty() { + return Err("no addresses in the given ranges".into()); + } + Ok(()) +} + +/// Aggregate a sorted, de-duplicated address list into the minimal set of CIDR +/// blocks that cover exactly those addresses (used to load the asic-rs factory). +fn targets_to_cidrs(ips: &[Ipv4Addr]) -> Vec<(Ipv4Addr, u8)> { + let mut out = Vec::new(); + let vals: Vec = ips.iter().map(|ip| u32::from(*ip)).collect(); + let mut i = 0usize; + while i < vals.len() { + // extend a contiguous run [start, end] + let start = vals[i]; + let mut end = start; + while i + 1 < vals.len() && vals[i + 1] == end + 1 { + end = vals[i + 1]; + i += 1; + } + out.extend(range_to_cidrs(start, end)); + i += 1; + } + out +} + +/// Cover the inclusive [start, end] u32 range with aligned CIDR blocks. +fn range_to_cidrs(start: u32, end: u32) -> Vec<(Ipv4Addr, u8)> { + let mut cidrs = Vec::new(); + let mut cur = start as u64; + let end = end as u64; + while cur <= end { + let align = if cur == 0 { 32 } else { (cur as u32).trailing_zeros() }; + let mut bits = align.min(32); + let remaining = end - cur + 1; + while bits > 0 && (1u64 << bits) > remaining { + bits -= 1; + } + cidrs.push((Ipv4Addr::from(cur as u32), (32 - bits) as u8)); + cur += 1u64 << bits; + } + cidrs +} + +/// Env var that swaps the live network scan for the built-in bench-fleet +/// fixtures. Set it to render/test the UI offline and deterministically. +pub const FAKE_SCAN_ENV: &str = "ALKANE_FAKE_SCAN"; + +/// True when the app should feed fixtures instead of scanning the network. +pub fn fake_scan_enabled() -> bool { + std::env::var_os(FAKE_SCAN_ENV).is_some() +} + +/// Spawn the scan thread. It parses the range lines into an exact target set, +/// tells the UI which addresses are in range (so out-of-range miners can be +/// dropped), then streams identified miners plus progress updates. In fake-scan +/// mode it streams the bench-fleet fixtures instead, needing no network. +pub fn start_scan(lines: Vec) -> Receiver { let (tx, rx) = channel(); + + if fake_scan_enabled() { + std::thread::Builder::new() + .name("fake-scan".into()) + .spawn(move || { + let rows = crate::fixtures::bench_fleet(); + let targets: HashSet = rows.iter().map(|r| r.ip.clone()).collect(); + let total = rows.len(); + let _ = tx.send(ScanMsg::Started { total, targets }); + for (i, row) in rows.into_iter().enumerate() { + if tx.send(ScanMsg::Row(row)).is_err() { + return; + } + let _ = tx.send(ScanMsg::Progress { done: i + 1, total }); + } + let _ = tx.send(ScanMsg::Done("fixtures".into())); + }) + .expect("spawn fake-scan thread"); + return rx; + } + + // Resolve the target addresses up front so we can report total + membership. + let targets = match parse_targets(&lines) { + Ok(t) if !t.is_empty() => t, + Ok(_) => { + let _ = tx.send(ScanMsg::Failed("no addresses in the given ranges".into())); + return rx; + } + Err(e) => { + let _ = tx.send(ScanMsg::Failed(e)); + return rx; + } + }; + let total = targets.len(); + let target_set: HashSet = targets.iter().map(|ip| ip.to_string()).collect(); + let _ = tx.send(ScanMsg::Started { total, targets: target_set }); + let cidrs = targets_to_cidrs(&targets); + std::thread::Builder::new() .name("asic-rs-scan".into()) .spawn(move || { @@ -77,32 +258,40 @@ pub fn start_scan(subnets: Vec) -> Receiver { } }; rt.block_on(async move { - for subnet in subnets { - let factory = match MinerFactory::from_subnet(&subnet) { + let mut factory = MinerFactory::new(); + for (ip, prefix) in &cidrs { + factory = match factory.with_subnet(&format!("{ip}/{prefix}")) { Ok(f) => f, Err(e) => { - let _ = tx.send(ScanMsg::Failed(format!("{subnet}: {e}"))); - continue; + let _ = tx.send(ScanMsg::Failed(format!("{ip}/{prefix}: {e}"))); + return; } }; - let mut stream = factory.scan_stream(); - while let Some(miner) = stream.next().await { + } + // scan_stream_with_ip yields one item per probed address, so we + // get accurate progress plus the responders. + let mut stream = factory.scan_stream_with_ip(); + let mut done = 0usize; + let step = (total / 100).max(1); // throttle progress messages + while let Some((_ip, miner)) = stream.next().await { + done += 1; + if let Some(miner) = miner { let row = to_row(&*miner).await; if tx.send(ScanMsg::Row(row)).is_err() { return; // UI gone } } - let _ = tx.send(ScanMsg::SubnetDone(subnet.clone())); + if done % step == 0 || done == total { + let _ = tx.send(ScanMsg::Progress { done, total }); + } } + let _ = tx.send(ScanMsg::Done(format!("{total} addresses"))); }); }) .expect("spawn scan thread"); rx } -/// "Slow" = mining but below 80% of the model's expected hashrate. -const SLOW_THRESHOLD: f64 = 0.8; - async fn to_row(miner: &dyn Miner) -> MinerRow { let data = miner.get_data().await; let hashrate_ths = data @@ -134,6 +323,15 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { .or_else(|| data.pools.iter().flat_map(|g| g.pools.iter()).next()) .and_then(|p| p.user.clone()) .unwrap_or_default(); + let active_pool = data + .pools + .iter() + .flat_map(|g| g.pools.iter()) + .find(|p| p.active == Some(true)) + .or_else(|| data.pools.iter().flat_map(|g| g.pools.iter()).next()); + let pool_url = active_pool + .and_then(|p| p.url.as_ref().map(|u| u.to_string())) + .unwrap_or_default(); let firmware = match (&data.device_info.firmware, &data.firmware_version) { (fw, Some(v)) if !fw.is_empty() => format!("{fw} {v}"), (fw, Some(v)) => format!("{fw}{v}"), @@ -144,22 +342,146 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { } else { format!("{} {}", data.device_info.make, data.device_info.model) }; + let fluid_temp_c = data.fluid_temperature.as_ref().map(|t| t.as_celsius()).unwrap_or(0.0); + let outlet_temp_c = data + .outlet_fluid_temperature + .as_ref() + .map(|t| t.as_celsius()) + .unwrap_or(0.0); + let psu_fan_rpm = data + .psu_fans + .iter() + .filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm())) + .fold(0.0f64, f64::max); let is_mining = data.is_mining; - let slow = is_mining && expected_ths > 0.0 && hashrate_ths < SLOW_THRESHOLD * expected_ths; + let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths); MinerRow { ip: data.ip.to_string(), selected: false, model, + mac: data.mac.map(|m| m.to_string()).unwrap_or_default(), + hostname: data.hostname.clone().unwrap_or_default(), + serial: data.serial_number.clone().unwrap_or_default(), firmware, + api_version: data.api_version.clone().unwrap_or_default(), + control_board: data.control_board_version.as_ref().map(|c| c.to_string()).unwrap_or_default(), hashrate_ths, expected_ths, + efficiency: data.efficiency.unwrap_or(0.0), power_w, + tuning_percent: data.tuning_percent, chip_temp_c, + fluid_temp_c, + outlet_temp_c, fan_rpm, + psu_fan_rpm, + fan_count: (!data.fans.is_empty()).then_some(data.fans.len() as u32), + expected_fans: data.expected_fans.map(|v| v as u32), + total_chips: data.total_chips.map(|v| v as u32), + expected_chips: data.expected_chips.map(|v| v as u32), + hashboards: (!data.hashboards.is_empty()).then_some(data.hashboards.len() as u32), + expected_hashboards: data.expected_hashboards.map(|v| v as u32), worker, + pool_url, + best_share: data.best_share, + session_best_share: data.session_best_share, + uptime_secs: data.uptime.map(|d| d.as_secs()).unwrap_or(0), + light_flashing: data.light_flashing, + operating_state: data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default(), is_mining, slow, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_cidr_line() { + let ips = parse_line("10.253.1.0/30").unwrap(); + assert_eq!(ips.len(), 4); + assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 0)); + assert_eq!(ips[3], Ipv4Addr::new(10, 253, 1, 3)); + } + + #[test] + fn parse_single_ip() { + let ips = parse_line("10.253.1.5").unwrap(); + assert_eq!(ips, vec![Ipv4Addr::new(10, 253, 1, 5)]); + } + + #[test] + fn parse_full_range() { + let ips = parse_line("10.253.1.3-10.253.1.234").unwrap(); + assert_eq!(ips.len(), 232); + assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 3)); + assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 1, 234)); + } + + #[test] + fn parse_short_range() { + let ips = parse_line("10.253.1.3-234").unwrap(); + assert_eq!(ips.len(), 232); + assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 1, 234)); + } + + #[test] + fn parse_cross_octet_range() { + let ips = parse_line("10.253.1.250-10.253.2.5").unwrap(); + assert_eq!(ips.len(), 12); // .250..=.255 (6) + 2.0..=2.5 (6) + assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 250)); + assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 2, 5)); + } + + #[test] + fn parse_rejects_reversed_range() { + assert!(parse_line("10.0.0.10-10.0.0.1").is_err()); + assert!(parse_line("not-an-ip").is_err()); + } + + #[test] + fn parse_rejects_oversized_cidr_and_range() { + // a /8 (16.7M) and /0 must be rejected, not allocated + assert!(parse_line("10.0.0.0/8").is_err()); + assert!(parse_line("0.0.0.0/0").is_err()); + // a large full range too + assert!(parse_line("10.0.0.0-10.99.0.0").is_err()); + // a /16 (65k) is fine + assert!(parse_line("10.1.0.0/16").is_ok()); + } + + #[test] + fn targets_dedup_and_sort() { + let lines = vec!["10.0.0.5".to_string(), "10.0.0.1-10.0.0.3".to_string(), "10.0.0.2".to_string()]; + let t = parse_targets(&lines).unwrap(); + assert_eq!(t, vec![ + Ipv4Addr::new(10, 0, 0, 1), + Ipv4Addr::new(10, 0, 0, 2), + Ipv4Addr::new(10, 0, 0, 3), + Ipv4Addr::new(10, 0, 0, 5), + ]); + } + + #[test] + fn cidr_aggregation_round_trips() { + // a /24 must aggregate back to exactly one /24 block + let ips = parse_line("10.9.8.0/24").unwrap(); + let cidrs = targets_to_cidrs(&ips); + assert_eq!(cidrs, vec![(Ipv4Addr::new(10, 9, 8, 0), 24)]); + + // an arbitrary range's blocks must cover exactly the same address set + let ips = parse_line("10.0.0.3-10.0.0.20").unwrap(); + let cidrs = targets_to_cidrs(&ips); + let mut covered = Vec::new(); + for (base, prefix) in cidrs { + let n = 1u32 << (32 - prefix as u32); + let b = u32::from(base); + covered.extend((0..n).map(|i| Ipv4Addr::from(b + i))); + } + covered.sort(); + assert_eq!(covered, ips); + } +} diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 03420a69..b10da366 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -16,16 +16,52 @@ const ID_RANGES_APPLY: i32 = 201; const ID_RANGES_CANCEL: i32 = 202; const ID_COLUMNS_OK: i32 = 203; const ID_COLUMNS_CANCEL: i32 = 204; +const ID_COLUMNS_ALL: i32 = 207; +const ID_COLUMNS_NONE: i32 = 208; +const ID_COLUMNS_RESET: i32 = 209; const ID_FILTER_OK: i32 = 205; const ID_FILTER_CANCEL: i32 = 206; +const ID_FILTER_RESET: i32 = 210; +// Per-column "All"/"None" buttons in the filter panel are ID_FILTER_ALL_BASE + +// column index (and the None equivalent). 100 columns of headroom each. +const ID_FILTER_ALL_BASE: i32 = 300; +const ID_FILTER_NONE_BASE: i32 = 500; const TIMER_SCAN: i32 = 1; -#[derive(PartialEq, Clone, Copy)] -enum DialogKind { - None, - Ranges, - Columns, - Filter, +/// Theme-aware palette for the KPI cards. Health is encoded in colour so a red +/// "Not hashing" or amber "Slow" draws the eye immediately. +struct Palette { + card_bg: (u8, u8, u8), + label: (u8, u8, u8), + neutral: (u8, u8, u8), + green: (u8, u8, u8), + amber: (u8, u8, u8), + red: (u8, u8, u8), + accent: (u8, u8, u8), +} + +fn palette(dark: bool) -> Palette { + if dark { + Palette { + card_bg: (44, 46, 51), + label: (150, 156, 164), + neutral: (228, 230, 234), + green: (74, 222, 128), + amber: (245, 190, 66), + red: (245, 110, 100), + accent: (108, 168, 250), + } + } else { + Palette { + card_bg: (255, 255, 255), + label: (108, 114, 122), + neutral: (28, 32, 38), + green: (33, 140, 80), + amber: (176, 120, 10), + red: (198, 55, 45), + accent: (40, 100, 170), + } + } } pub struct App { @@ -39,12 +75,14 @@ pub struct App { kpi_hashrate: Widget, kpi_power: Widget, ranges_btn: Widget, - status_lbl: Widget, + progress: Widget, pub table: Option, table_parent: Widget, + root_sizer: Widget, pub scan_rx: Option>, pub scanning: bool, - open_dialog: DialogKind, + scan_total: usize, + target_ips: HashSet, ranges_dialog: Widget, ranges_edit: Widget, columns_dialog: Widget, @@ -54,43 +92,63 @@ pub struct App { } pub fn build(frame: Widget) -> App { + let dark = wx_rs::is_dark(); + let pal = palette(dark); let panel = Widget::panel(frame); let root = Widget::box_sizer(true); - // KPI row (top left, 6 KPIs) + // KPI header: a row of equal-width cards, each a big value over a small + // label. Health KPIs are colour-coded (green/amber/red); hashrate uses the + // accent colour so totals stand apart from counts. let kpi_row = Widget::box_sizer(false); - let mk_kpi = |label: &str| { - let w = Widget::static_text(panel, label); - w.set_bold(); - kpi_row.add(w, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); - w + let mk_card = |label: &str, value_color: (u8, u8, u8)| -> Widget { + let card = Widget::panel(panel); + card.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2); + let cs = Widget::box_sizer(true); + let value = Widget::static_text(card, "0"); + value.set_font_size(19); + value.set_bold(); + value.set_fg(value_color.0, value_color.1, value_color.2); + value.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2); + let lbl = Widget::static_text(card, label); + lbl.set_font_size(9); + lbl.set_fg(pal.label.0, pal.label.1, pal.label.2); + lbl.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2); + cs.add(value, 0, sf::BORDER_LEFT | sf::BORDER_TOP | sf::BORDER_RIGHT, 12); + cs.add(lbl, 0, sf::BORDER_LEFT | sf::BORDER_BOTTOM | sf::BORDER_RIGHT, 12); + cs.set_sizer_on(card); + kpi_row.add(card, 1, sf::EXPAND | sf::BORDER_ALL, 4); + value }; - let kpi_total = mk_kpi("Total: 0"); - let kpi_hashing = mk_kpi("Hashing: 0"); - let kpi_slow = mk_kpi("Slow: 0"); - let kpi_not = mk_kpi("Not hashing: 0"); - let kpi_hashrate = mk_kpi("Total hashrate: 0 TH/s"); - let kpi_power = mk_kpi("Est. power: 0 W"); - root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 4); + let kpi_total = mk_card("Total", pal.neutral); + let kpi_hashing = mk_card("Hashing", pal.green); + let kpi_slow = mk_card("Slow", pal.amber); + let kpi_not = mk_card("Not hashing", pal.red); + let kpi_hashrate = mk_card("Hashrate", pal.accent); + let kpi_power = mk_card("Est. power", pal.neutral); + root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6); - // Controls row: scan-ranges box (middle-left), filter, columns, rescan + // Controls row: scan-ranges button on the left; Filter / Columns / Rescan + // pushed to the right. let ctl = Widget::box_sizer(false); let ranges_btn = Widget::button(panel, "Scan ranges", ID_RANGES); ctl.add(ranges_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4); - ctl.add_spacer(8); + ctl.add_stretch(1); let filter_btn = Widget::button(panel, "Filter", ID_FILTER); ctl.add(filter_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4); let columns_btn = Widget::button(panel, "Columns", ID_COLUMNS); ctl.add(columns_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4); let rescan_btn = Widget::button(panel, "Rescan", ID_RESCAN); ctl.add(rescan_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4); - let status_lbl = Widget::static_text(panel, "starting scan..."); - ctl.add(status_lbl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4); - root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_ALL, 2); + root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4); - // Table fills the rest; created in rebuild_table + // Scan-progress bar across the top of the table (hidden when idle). + let progress = Widget::gauge(panel, 1); + root.add(progress, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); + progress.show(false); + + // The table is created in rebuild_table and added to `root` there. let table_parent = panel; - root.add_stretch(1); root.set_sizer_on(panel); let frame_sizer = Widget::box_sizer(true); @@ -98,6 +156,10 @@ pub fn build(frame: Widget) -> App { frame_sizer.set_sizer_on(frame); frame.set_min_size(1200, 720); + // A status bar carries scan state (was an inline label). + wx_rs::create_status_bar(); + wx_rs::set_status_text("starting scan..."); + let ranges = scan::load_ranges(); let mut app = App { rows: Vec::new(), @@ -110,12 +172,14 @@ pub fn build(frame: Widget) -> App { kpi_hashrate, kpi_power, ranges_btn, - status_lbl, + progress, table: None, table_parent, + root_sizer: root, scan_rx: Some(scan::start_scan(ranges.clone())), scanning: true, - open_dialog: DialogKind::None, + scan_total: 0, + target_ips: HashSet::new(), ranges_dialog: frame, ranges_edit: frame, columns_dialog: frame, @@ -131,18 +195,36 @@ pub fn build(frame: Widget) -> App { impl App { pub fn rebuild_table(&mut self) { + // Detach the old table from the sizer before destroying it, so the + // sizer never holds a dangling item, then drop it. if let Some(t) = self.table.take() { + self.root_sizer.detach(t); t.destroy(); } let t = Widget::dvlc(self.table_parent); // creation order == display order: Sel toggle column first (fixed), - // then Ip (fixed), then the reorderable statistics columns. - t.dvlc_append_toggle_col(30); + // then Ip (fixed), then the reorderable statistics columns. The active + // sort column carries an ASCII direction marker in its header ("^" asc, + // "v" desc) -- wx's native SetSortOrder re-sorts the store lexically and + // would fight our numeric sort, so we mark the header text instead. + t.dvlc_append_toggle_col(28); for c in self.view.display_columns().iter().skip(1) { let fixed = self.view.is_fixed(*c); - t.dvlc_append_text_col(c.title(), c.width(), !fixed); + let mut title = c.title().to_string(); + match self.view.sort { + Some((sc, true)) if sc == *c => title.push_str(" ^"), + Some((sc, false)) if sc == *c => title.push_str(" v"), + _ => {} + } + t.dvlc_append_text_col(&title, c.width(), !fixed); } + // Add the table to the root sizer (proportion 1 => fills the area under + // the KPI + controls rows) and re-run the panel's layout so it is + // positioned, not left floating at (0,0). This was the "table in the + // top-left corner" bug: the control was created but never sized. + self.root_sizer.add(t, 1, sf::EXPAND | sf::BORDER_ALL, 4); self.table = Some(t); + self.table_parent.layout(); self.fill_rows(); } @@ -153,7 +235,15 @@ impl App { let cols = self.view.display_columns(); for &ri in &self.view_idx { let r = &self.rows[ri]; - let cells: Vec = cols.iter().map(|c| c.cell(r)).collect(); + // The toggle column carries the checked state ("1"/"0") so a refresh + // preserves selection; other columns carry their text. + let cells: Vec = cols + .iter() + .map(|c| match c { + Column::Sel => if r.selected { "1".to_string() } else { "0".to_string() }, + _ => c.cell(r), + }) + .collect(); let refs: Vec<&str> = cells.iter().map(|s| s.as_str()).collect(); t.dvlc_append_row(&refs); } @@ -162,12 +252,12 @@ impl App { pub fn refresh_kpis(&self) { let k = compute_kpis(&self.rows, &self.view_idx); - self.kpi_total.set_label(&format!("Total: {}", k.total)); - self.kpi_hashing.set_label(&format!("Hashing: {}", k.hashing)); - self.kpi_slow.set_label(&format!("Slow: {}", k.slow)); - self.kpi_not.set_label(&format!("Not hashing: {}", k.not_hashing)); - self.kpi_hashrate.set_label(&format!("Total hashrate: {:.1} TH/s", k.total_hashrate_ths)); - self.kpi_power.set_label(&format!("Est. power: {:.0} W", k.total_power_w)); + self.kpi_total.set_label(&k.total.to_string()); + self.kpi_hashing.set_label(&k.hashing.to_string()); + self.kpi_slow.set_label(&k.slow.to_string()); + self.kpi_not.set_label(&k.not_hashing.to_string()); + self.kpi_hashrate.set_label(&format_si(k.total_hashrate_ths * 1e12, "H/s")); + self.kpi_power.set_label(&format_si(k.total_power_w, "W")); } pub fn drain_scan(&mut self) { @@ -175,16 +265,47 @@ impl App { let mut changed = false; loop { match rx.try_recv() { - Ok(ScanMsg::Row(row)) => { - changed |= row.clone().upsert_into(&mut self.rows); + Ok(ScanMsg::Started { total, targets }) => { + // Drop miners no longer in the target range. + let before = self.rows.len(); + self.rows.retain(|r| targets.contains(&r.ip)); + changed |= self.rows.len() != before; + self.target_ips = targets; + self.scan_total = total; + self.scanning = true; + self.progress.gauge_set_range(total.max(1) as i32); + self.progress.gauge_set_value(0); + self.progress.show(true); + self.table_parent.layout(); + wx_rs::set_status_text(&format!("scanning {total} addresses...")); } - Ok(ScanMsg::SubnetDone(s)) => { - self.status_lbl.set_label(&format!("scan done: {s}")); + Ok(ScanMsg::Progress { done, total }) => { + self.scan_total = total; + self.progress.gauge_set_value(done.min(total) as i32); + wx_rs::set_status_text(&format!( + "scanning {done}/{total} - {} found", + self.rows.len() + )); + } + Ok(ScanMsg::Row(row)) => { + // Ignore stray rows outside the current target set. + if self.target_ips.is_empty() || self.target_ips.contains(&row.ip) { + row.upsert_into(&mut self.rows); + changed = true; + } + } + Ok(ScanMsg::Done(s)) => { self.scanning = false; + self.progress.gauge_set_value(self.scan_total.max(1) as i32); + self.progress.show(false); + self.table_parent.layout(); + wx_rs::set_status_text(&format!("scan complete: {} found in {s}", self.rows.len())); } Ok(ScanMsg::Failed(e)) => { - self.status_lbl.set_label(&format!("scan failed: {e}")); self.scanning = false; + self.progress.show(false); + self.table_parent.layout(); + wx_rs::set_status_text(&format!("scan failed: {e}")); } Err(_) => break, } @@ -205,38 +326,85 @@ impl App { } } - fn header_click(&mut self, creation_idx: usize) { - if creation_idx == 0 || creation_idx >= self.view.order.len() { - return; // toggle column not sortable + /// 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)); + } + } } - let col = self.view.order[creation_idx]; + } + + fn header_click(&mut self, creation_idx: usize) { + // Columns are appended to the table in display order (toggle col first, + // then each visible column). Map the clicked creation index back to a + // model column through display_columns(), not view.order, so hidden + // columns don't shift the mapping. + let cols = self.view.display_columns(); + if creation_idx == 0 || creation_idx >= cols.len() { + return; // toggle column (idx 0) is not sortable + } + let col = cols[creation_idx]; self.view.sort = match self.view.sort { Some((c, true)) if c == col => Some((col, false)), Some((c, false)) if c == col => None, _ => Some((col, true)), }; + // Update the header marker in place + re-sort rows. Avoids destroying and + // recreating the whole control on every sort click (janky on big fleets). + self.update_headers(); self.fill_rows(); } + /// Refresh each column header's ASCII sort marker ("^" asc, "v" desc) in + /// place, without recreating the table. + fn update_headers(&self) { + let Some(t) = self.table else { return }; + for (i, c) in self.view.display_columns().iter().enumerate() { + if i == 0 { + continue; // toggle column has no title + } + let mut title = c.title().to_string(); + match self.view.sort { + Some((sc, true)) if sc == *c => title.push_str(" ^"), + Some((sc, false)) if sc == *c => title.push_str(" v"), + _ => {} + } + t.dvlc_set_col_title(i, &title); + } + } + fn column_reordered(&mut self) { let Some(t) = self.table else { return }; + // The table only holds the VISIBLE columns; a creation index maps to a + // model column via display_columns(). Read the new visible order from + // the drag result and hand it to the model, which splices it back into + // the full column order while leaving hidden columns in place. + let disp = self.view.display_columns(); let n = t.dvlc_col_count(); - let mut new_order = Vec::with_capacity(n); + let mut new_visible = Vec::with_capacity(n); for pos in 0..n { let creation = t.dvlc_col_at_pos(pos).unwrap_or(pos); - let col = self.view.order.get(creation).copied().unwrap_or(Column::Sel); - new_order.push(col); - } - if new_order.first() == Some(&Column::Sel) { - self.view.order = new_order; + if let Some(&c) = disp.get(creation) { + new_visible.push(c); + } } + self.view.apply_visible_reorder(&new_visible); } - fn open_ranges_dialog(&mut self) { + /// Build (but do not show) the ranges editor. The caller shows it modally + /// *after* releasing the App borrow; see `dispatch`. + fn build_ranges_dialog(&mut self) -> Widget { let frame = Widget::main_frame(); let dlg = Widget::dialog(frame, "Edit IP scanning ranges"); let root = Widget::box_sizer(true); - let hint = Widget::static_text(dlg, "One CIDR per line (e.g. 10.255.1.0/24):"); + let hint = Widget::static_text( + dlg, + "One range per line:\n CIDR 10.255.1.0/24\n range 10.253.1.3-10.253.1.234\n single 10.253.1.5", + ); root.add(hint, 0, sf::BORDER_ALL, 6); let edit = Widget::text_ctrl(dlg, true); edit.set_value(&scan::load_ranges().join("\n")); @@ -246,14 +414,14 @@ impl App { 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::ALIGN_CENTRE_VERTICAL, 0); + // `root` is a vertical sizer: only border flags are valid here. Using + // ALIGN_CENTRE_VERTICAL trips a wxWidgets consistency assert whose + // handler pumps a nested event loop -> re-entrant dispatch -> crash. + root.add_sizer(btns, 0, sf::BORDER_ALL, 6); root.set_sizer_on(dlg); self.ranges_dialog = dlg; self.ranges_edit = edit; - self.open_dialog = DialogKind::Ranges; - dlg.show_modal(); - self.open_dialog = DialogKind::None; - dlg.destroy(); + dlg } fn apply_ranges(&mut self) { @@ -265,61 +433,86 @@ impl App { .map(String::from) .collect(); if lines.is_empty() { - self.status_lbl.set_label("no ranges given"); + wx_rs::set_status_text("no ranges given"); self.ranges_dialog.close(0); return; } - if lines.iter().any(|l| scan::parse_cidr(l).is_none()) { - self.status_lbl.set_label("invalid CIDR in ranges"); + if let Err(e) = scan::validate_ranges(&lines) { + wx_rs::set_status_text(&format!("invalid range: {e}")); return; // keep dialog open } let _ = scan::save_ranges(&lines); self.scan_rx = Some(scan::start_scan(lines.clone())); self.scanning = true; - self.status_lbl.set_label("scanning..."); + wx_rs::set_status_text("scanning..."); self.ranges_btn.set_label(&format!("Scan ranges: {}", lines.join(", "))); self.ranges_dialog.close(1); } - fn open_columns_dialog(&mut self) { + /// The columns available to show/hide: every metric except the fixed + /// Sel + Ip columns, in registry order (matches the check-list order). + fn selectable_columns() -> Vec { + ALL_COLUMNS + .iter() + .copied() + .filter(|c| *c != Column::Sel && *c != Column::Ip) + .collect() + } + + /// Build (but do not show) the columns chooser. Every scannable metric is + /// listed, so any of them can be shown. + fn build_columns_dialog(&mut self) -> Widget { let frame = Widget::main_frame(); let dlg = Widget::dialog(frame, "Choose columns"); let root = Widget::box_sizer(true); + let hint = Widget::static_text(dlg, "Show any scannable metric (IP is always shown):"); + root.add(hint, 0, sf::BORDER_ALL, 6); let list = Widget::check_list_box(dlg); - for c in ALL_COLUMNS { - if c == Column::Sel || c == Column::Ip { - continue; // fixed columns - } + for c in Self::selectable_columns() { list.clb_append(c.title()); list.clb_set_checked(list.clb_count() - 1, self.view.visible.contains(&c)); } root.add(list, 1, sf::EXPAND | sf::BORDER_ALL, 6); + // quick actions + let quick = Widget::box_sizer(false); + quick.add(Widget::button(dlg, "All", ID_COLUMNS_ALL), 0, sf::BORDER_ALL, 4); + quick.add(Widget::button(dlg, "None", ID_COLUMNS_NONE), 0, sf::BORDER_ALL, 4); + quick.add(Widget::button(dlg, "Defaults", ID_COLUMNS_RESET), 0, sf::BORDER_ALL, 4); + root.add_sizer(quick, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 4); let btns = Widget::box_sizer(false); btns.add(Widget::button(dlg, "OK", ID_COLUMNS_OK), 0, sf::BORDER_ALL, 6); btns.add(Widget::button(dlg, "Cancel", ID_COLUMNS_CANCEL), 0, sf::BORDER_ALL, 6); - root.add_sizer(btns, 0, sf::ALIGN_CENTRE_VERTICAL, 0); + root.add_sizer(btns, 0, sf::BORDER_ALL, 6); root.set_sizer_on(dlg); self.columns_dialog = dlg; self.columns_list = list; - self.open_dialog = DialogKind::Columns; - dlg.show_modal(); - self.open_dialog = DialogKind::None; - dlg.destroy(); + dlg + } + + /// Check or uncheck every item in the columns list (visual only). + fn columns_check_all(&self, checked: bool) { + let list = self.columns_list; + for i in 0..list.clb_count() { + list.clb_set_checked(i, checked); + } + } + + /// Reset the columns list to the default-visible set (visual only). + fn columns_reset_defaults(&self) { + let list = self.columns_list; + for (i, c) in Self::selectable_columns().iter().enumerate() { + list.clb_set_checked(i, DEFAULT_VISIBLE.contains(c)); + } } fn apply_columns(&mut self) { let list = self.columns_list; - let mut i = 0usize; - for c in ALL_COLUMNS { - if c == Column::Sel || c == Column::Ip { - continue; - } + for (i, c) in Self::selectable_columns().iter().enumerate() { if list.clb_checked(i) { - self.view.visible.insert(c); + self.view.visible.insert(*c); } else { - self.view.visible.remove(&c); + self.view.visible.remove(c); } - i += 1; } // keep sort column visible-ish: drop sort if hidden if let Some((c, _)) = self.view.sort { @@ -331,56 +524,79 @@ impl App { self.rebuild_table(); } - fn open_filter_dialog(&mut self) { + /// Build (but do not show) the Excel-style filter panel. Every visible + /// column with more than one distinct value gets a per-column value + /// checklist with All / None controls; filters AND across columns and OR + /// within a column. Blank cells show as "(blank)". + fn build_filter_dialog(&mut self) -> Widget { let frame = Widget::main_frame(); let dlg = Widget::dialog(frame, "Filter"); let root = Widget::box_sizer(true); + let content = Widget::box_sizer(false); // side-by-side column filters let mut lists = Vec::new(); for c in self.view.display_columns() { - if c == Column::Sel { + // Value checklists only make sense for categorical columns; skip the + // checkbox column and continuous numeric metrics. + if c == Column::Sel || c.is_numeric() { continue; } - let mut values: Vec = self - .rows - .iter() - .map(|r| c.cell(r)) - .collect(); + let mut values: Vec = self.rows.iter().map(|r| c.cell(r)).collect(); values.sort(); values.dedup(); if values.len() < 2 { continue; } + let idx = lists.len() as i32; + let colbox = Widget::box_sizer(true); + let head = Widget::box_sizer(false); let lbl = Widget::static_text(dlg, c.title()); lbl.set_bold(); - root.add(lbl, 0, sf::BORDER_ALL, 4); + head.add(lbl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2); + head.add(Widget::button(dlg, "All", ID_FILTER_ALL_BASE + idx), 0, sf::BORDER_ALL, 1); + head.add(Widget::button(dlg, "None", ID_FILTER_NONE_BASE + idx), 0, sf::BORDER_ALL, 1); + colbox.add_sizer(head, 0, sf::EXPAND | sf::BORDER_ALL, 2); let lst = Widget::check_list_box(dlg); + lst.set_min_size(140, 220); // so Fit gives the checklist real space let current: Option> = self.view.filters.get(&c).cloned(); for v in &values { - lst.clb_append(v); + let shown = if v.is_empty() { "(blank)" } else { v.as_str() }; + lst.clb_append(shown); let checked = match ¤t { Some(allowed) => allowed.contains(v), None => true, }; lst.clb_set_checked(lst.clb_count() - 1, checked); } - root.add(lst, 1, sf::EXPAND | sf::BORDER_ALL, 4); + colbox.add(lst, 1, sf::EXPAND | sf::BORDER_ALL, 2); + content.add_sizer(colbox, 1, sf::EXPAND | sf::BORDER_ALL, 4); lists.push((c, lst)); } if lists.is_empty() { - let lbl = Widget::static_text(dlg, "Nothing to filter."); - root.add(lbl, 0, sf::BORDER_ALL, 8); + let lbl = Widget::static_text(dlg, "Nothing to filter yet - run a scan first."); + content.add(lbl, 0, sf::BORDER_ALL, 8); } + root.add_sizer(content, 1, sf::EXPAND | sf::BORDER_ALL, 4); let btns = Widget::box_sizer(false); - btns.add(Widget::button(dlg, "OK", ID_FILTER_OK), 0, sf::BORDER_ALL, 6); + 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::ALIGN_CENTRE_VERTICAL, 0); + root.add_sizer(btns, 0, sf::BORDER_ALL, 6); root.set_sizer_on(dlg); + // Size the dialog to fit however many category columns there are. + dlg.fit(dlg); self.filter_dialog = dlg; self.filter_lists = lists; - self.open_dialog = DialogKind::Filter; - dlg.show_modal(); - self.open_dialog = DialogKind::None; - dlg.destroy(); + dlg + } + + /// Check or uncheck every value in one column's list (0-based index into + /// `filter_lists`). + fn filter_check_all(&self, idx: usize, checked: bool) { + if let Some((_c, lst)) = self.filter_lists.get(idx) { + for i in 0..lst.clb_count() { + lst.clb_set_checked(i, checked); + } + } } fn apply_filter(&mut self) { @@ -389,11 +605,13 @@ impl App { let mut allowed = HashSet::new(); for i in 0..count { if lst.clb_checked(i) { - allowed.insert(lst.clb_string(i).unwrap_or_default()); + // map the shown "(blank)" back to the empty string + let v = lst.clb_string(i).unwrap_or_default(); + allowed.insert(if v == "(blank)" { String::new() } else { v }); } } if allowed.is_empty() || allowed.len() == count { - self.view.filters.remove(c); // unchecked-all = clear + self.view.filters.remove(c); // all (or none) checked = no filter } else { self.view.filters.insert(*c, allowed); } @@ -401,6 +619,152 @@ impl App { self.filter_dialog.close(1); self.fill_rows(); } + + fn reset_filters(&mut self) { + self.view.filters.clear(); + self.filter_dialog.close(1); + self.fill_rows(); + } + + /// Handle one widget event under the App borrow. Returns a dialog to show + /// modally *after* the borrow is released (see `dispatch`); all in-place + /// work is done here, so most events return None. + fn handle(&mut self, ev: WxEvent) -> Option { + match ev.kind { + WxEventKind::ButtonClicked => { + let id = ev.p1 as i32; + match id { + ID_RANGES => return Some(self.build_ranges_dialog()), + ID_RANGES_APPLY => self.apply_ranges(), + ID_RANGES_CANCEL => self.ranges_dialog.close(0), + ID_COLUMNS => return Some(self.build_columns_dialog()), + ID_COLUMNS_OK => self.apply_columns(), + ID_COLUMNS_CANCEL => self.columns_dialog.close(0), + ID_COLUMNS_ALL => self.columns_check_all(true), + ID_COLUMNS_NONE => self.columns_check_all(false), + ID_COLUMNS_RESET => self.columns_reset_defaults(), + ID_FILTER => return Some(self.build_filter_dialog()), + ID_FILTER_OK => self.apply_filter(), + ID_FILTER_CANCEL => self.filter_dialog.close(0), + ID_FILTER_RESET => self.reset_filters(), + ID_RESCAN => { + let ranges = scan::load_ranges(); + self.scan_rx = Some(scan::start_scan(ranges)); + self.scanning = true; + wx_rs::set_status_text("scanning..."); + } + _ if (ID_FILTER_ALL_BASE..ID_FILTER_NONE_BASE).contains(&id) => { + self.filter_check_all((id - ID_FILTER_ALL_BASE) as usize, true); + } + _ if (ID_FILTER_NONE_BASE..ID_FILTER_NONE_BASE + 200).contains(&id) => { + self.filter_check_all((id - ID_FILTER_NONE_BASE) as usize, false); + } + _ => {} + } + } + WxEventKind::DvlcHeaderClick => self.header_click(ev.p1 as usize), + WxEventKind::DvlcValueChanged => self.toggle_select(ev.p1 as usize, ev.p2 as usize), + WxEventKind::DvlcActivated => self.activate_row(ev.p1 as usize), + WxEventKind::DvlcReordered => self.column_reordered(), + WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => self.drain_scan(), + _ => {} + } + None + } + + /// Headless workflow self-test: load the bench-fleet fixtures, render them + /// through the real widgets, then read back what the table and KPIs + /// actually display and compare to the expected hardware output. Prints one + /// line per check and returns true iff every check passed. + pub fn run_fixture_selftest(&mut self) -> bool { + self.rows = crate::fixtures::bench_fleet(); + self.view = ViewState::default(); + self.fill_rows(); + + let mut ok = true; + let mut check = |name: &str, pass: bool, detail: String| { + println!("[{}] {}{}", if pass { "PASS" } else { "FAIL" }, name, + if detail.is_empty() { String::new() } else { format!(" -- {detail}") }); + ok &= pass; + }; + + // 1. KPI values: independent, hand-computed from the fixtures. The + // labels are static; the value widgets carry the numbers. + let want_kpis = [ + (self.kpi_total, "Total", "9"), + (self.kpi_hashing, "Hashing", "6"), + (self.kpi_slow, "Slow", "1"), + (self.kpi_not, "Not hashing", "2"), + (self.kpi_hashrate, "Hashrate", "685 TH/s"), + (self.kpi_power, "Est. power", "21.3 kW"), + ]; + for (w, name, want) in want_kpis { + let got = w.get_label(); + check(&format!("kpi {name} == \"{want}\""), got == want, format!("got \"{got}\"")); + } + + let Some(t) = self.table else { + check("table exists", false, "no table widget".into()); + return false; + }; + let cols = self.view.display_columns(); + + // 2. Row count in the store matches the (unfiltered) fixture count. + let want_rows = self.view_idx.len(); + check("table row count == 9", + t.dvlc_row_count() == 9 && want_rows == 9, + format!("store={}, view={}", t.dvlc_row_count(), want_rows)); + + // 3. Every store cell equals what the model produced for that row/col + // (catches column-order / off-by-one / append bugs). + let mut mismatches = 0; + for (disp_row, &ri) in self.view_idx.iter().enumerate() { + let r = &self.rows[ri]; + for (j, c) in cols.iter().enumerate().skip(1) { + let want = c.cell(r); + let got = t.dvlc_get_cell(disp_row, j).unwrap_or_default(); + if got != want { + if mismatches < 5 { + println!(" cell[{disp_row}][{j}] {}: want \"{want}\" got \"{got}\"", c.title()); + } + mismatches += 1; + } + } + } + check("every table cell matches the model", mismatches == 0, + format!("{mismatches} mismatched cells")); + + // 4. Independent spot-checks by IP against the known hardware output. + let ip_col = cols.iter().position(|c| *c == Column::Ip); + let status_col = cols.iter().position(|c| *c == Column::Status); + let hr_col = cols.iter().position(|c| *c == Column::Hashrate); + let find = |ip: &str| -> Option { + self.view_idx.iter().position(|&ri| self.rows[ri].ip == ip) + }; + let cell = |row: usize, col: Option| -> String { + match col { Some(c) => t.dvlc_get_cell(row, c).unwrap_or_default(), None => String::new() } + }; + if let (Some(row), Some(_)) = (find("10.255.1.149"), status_col) { + check("S21 Pro (.149) is slow", cell(row, status_col) == "slow", + format!("status=\"{}\"", cell(row, status_col))); + check("S21 Pro (.149) hashrate == 60.0 TH/s", cell(row, hr_col) == "60.0 TH/s", + format!("hashrate=\"{}\"", cell(row, hr_col))); + } else { + check("S21 Pro (.149) present", false, "row not found".into()); + } + if let Some(row) = find("10.255.1.112") { + check("S17 (.112) is not hashing", cell(row, status_col) == "not hashing", + format!("status=\"{}\"", cell(row, status_col))); + check("S17 (.112) blank hashrate", cell(row, hr_col).is_empty(), + format!("hashrate=\"{}\"", cell(row, hr_col))); + } else { + check("S17 (.112) present", false, "row not found".into()); + } + check("IP is the first text column", ip_col == Some(1), + format!("ip col index = {ip_col:?}")); + + ok + } } // The wx event loop is single-threaded; keep the app in a thread-local. @@ -412,34 +776,22 @@ 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) { - APP.with(|cell| { - let mut app_ref = cell.borrow_mut(); - let Some(app) = app_ref.as_mut() else { return }; - match ev.kind { - WxEventKind::ButtonClicked => match ev.p1 as i32 { - ID_RANGES => app.open_ranges_dialog(), - ID_RANGES_APPLY => app.apply_ranges(), - ID_RANGES_CANCEL => app.ranges_dialog.close(0), - ID_COLUMNS => app.open_columns_dialog(), - ID_COLUMNS_OK => app.apply_columns(), - ID_COLUMNS_CANCEL => app.columns_dialog.close(0), - ID_FILTER => app.open_filter_dialog(), - ID_FILTER_OK => app.apply_filter(), - ID_FILTER_CANCEL => app.filter_dialog.close(0), - ID_RESCAN => { - let ranges = scan::load_ranges(); - app.scan_rx = Some(scan::start_scan(ranges)); - app.scanning = true; - app.status_lbl.set_label("scanning..."); - } - _ => {} - }, - WxEventKind::DvlcHeaderClick => app.header_click(ev.p1 as usize), - WxEventKind::DvlcValueChanged => app.toggle_select(ev.p1 as usize, ev.p2 as usize), - WxEventKind::DvlcReordered => app.column_reordered(), - WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => app.drain_scan(), - _ => {} - } + 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) + } } diff --git a/scripts/ui-screenshot.sh b/scripts/ui-screenshot.sh new file mode 100644 index 00000000..54c4b3af --- /dev/null +++ b/scripts/ui-screenshot.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Off-screen screenshot of the running UI, for visual review. +# +# Runs alkane-toolkit under a private Xvfb display (never the real desktop), +# waits for its window to map, and captures it to a PNG. By default it renders +# the offline bench-fleet fixtures (ALKANE_FAKE_SCAN) so the shot is +# deterministic and needs no hardware; pass --live to scan the real network. +# +# Usage: scripts/ui-screenshot.sh [out.png] [--live] [binary] +set -u +REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +WX_PREFIX="${WX_PREFIX:-$HOME/.cache/wx-3.3.3-linux}" +export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$WX_PREFIX/bin/wx-config}" + +OUT="${1:-alkane-toolkit.png}" +LIVE=0; BIN="" +shift 2>/dev/null || true +for a in "$@"; do + case "$a" in + --live) LIVE=1 ;; + *) BIN="$a" ;; + esac +done + +if [ -z "$BIN" ]; then + if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then "$REPO/scripts/build-wx-linux.sh"; fi + ( cd "$REPO" && cargo build --release -p alkane-gui --offline ) || exit 3 + TDIR=$(cd "$REPO" && cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \ + | tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4) + [ -n "$TDIR" ] || TDIR="$REPO/target" + BIN="$TDIR/release/alkane-toolkit" +fi +[ -x "$BIN" ] || { echo "binary not found: $BIN" >&2; exit 3; } + +DISP=":98" +FAKE_ENV="ALKANE_FAKE_SCAN=1" +[ "$LIVE" = "1" ] && FAKE_ENV="" + +Xvfb "$DISP" -screen 0 1280x850x24 -nolisten tcp >/dev/null 2>&1 & +XPID=$! +sleep 1.2 +# warm the font/GTK caches so the first window map is not stalled +DISPLAY="$DISP" xclock >/dev/null 2>&1 & WARM=$!; sleep 1.2; kill "$WARM" 2>/dev/null +# shellcheck disable=SC2086 +DISPLAY="$DISP" GDK_BACKEND=x11 $FAKE_ENV "$BIN" >/dev/null 2>&1 & +APID=$! +WID=""; t=0 +while [ "$t" -lt 25 ]; do + sleep 1; t=$((t+1)) + kill -0 "$APID" 2>/dev/null || { echo "app exited early" >&2; break; } + line=$(DISPLAY="$DISP" xwininfo -root -tree 2>/dev/null | grep '"alkane-toolkit"' | grep -E '1[0-9]{3}x[0-9]{3}' | head -1) + [ -n "$line" ] && { WID=$(echo "$line" | awk '{print $1}'); break; } +done +sleep 2 # let it paint and drain a scan tick +if [ -n "$WID" ]; then + DISPLAY="$DISP" import -window "$WID" "$OUT" && echo "wrote $OUT (window $WID, ${t}s)" +else + DISPLAY="$DISP" import -window root "$OUT"; echo "no app window; captured root -> $OUT" >&2 +fi +kill "$APID" 2>/dev/null +kill "$XPID" 2>/dev/null diff --git a/scripts/ui-selftest.sh b/scripts/ui-selftest.sh new file mode 100644 index 00000000..f919cbf0 --- /dev/null +++ b/scripts/ui-selftest.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Headless UI workflow self-test. +# +# Builds alkane-toolkit, then runs it in ALKANE_SELFTEST mode under a private +# Xvfb display. In that mode the app loads the bench-fleet fixtures (the +# expected hardware output), renders them through the real wxWidgets table and +# KPI header, reads back what the widgets actually display, and compares to the +# expected result. It prints one line per check and exits non-zero on any +# mismatch -- so this is a CI-able, hardware-free check that the app's functions +# produce the intended output. +# +# Usage: scripts/ui-selftest.sh [binary] +# binary defaults to the release build in the cargo target dir. +set -u +REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +WX_PREFIX="${WX_PREFIX:-$HOME/.cache/wx-3.3.3-linux}" +export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$WX_PREFIX/bin/wx-config}" + +BIN="${1:-}" +if [ -z "$BIN" ]; then + if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then "$REPO/scripts/build-wx-linux.sh"; fi + ( cd "$REPO" && cargo build --release -p alkane-gui --offline ) || exit 3 + # locate the binary via the machine-local target dir + TDIR=$(cd "$REPO" && cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \ + | tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4) + [ -n "$TDIR" ] || TDIR="$REPO/target" + BIN="$TDIR/release/alkane-toolkit" +fi +[ -x "$BIN" ] || { echo "binary not found: $BIN" >&2; exit 3; } + +DISP=":98" +Xvfb "$DISP" -screen 0 1280x850x24 -nolisten tcp >/dev/null 2>&1 & +XPID=$! +sleep 1.2 +DISPLAY="$DISP" GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN" +RC=$? +kill "$XPID" 2>/dev/null +echo "== ui-selftest exit=$RC ==" +exit "$RC" diff --git a/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch b/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch index c9afebd6..0d6474dc 100644 --- a/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch +++ b/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch @@ -1,6 +1,5 @@ --- a/src/lib.rs +++ b/src/lib.rs -+++ wx-rs-0.2.0-patched/src/lib.rs 2026-09-15 12:27:16.559261300 -0600 @@ -3,3 +3,7 @@ mod menu; @@ -11,8 +10,7 @@ +pub use widgets::*; --- a/src/widgets.rs +++ b/src/widgets.rs -+++ wx-rs-0.2.0-patched/src/widgets.rs 2026-09-15 13:05:24.616388500 -0600 -@@ -0,0 +1,365 @@ +@@ -0,0 +1,473 @@ +// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge +// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the +// wxWidgets object tree (parents own children; nothing to free in Rust). @@ -35,10 +33,13 @@ + pub fn wxbr_sizer_add_spacer(sizer: *mut c_void, px: c_int); + pub fn wxbr_sizer_add_stretch(sizer: *mut c_void, proportion: c_int); + pub fn wxbr_set_sizer(win: *mut c_void, sizer: *mut c_void); ++ pub fn wxbr_layout(win: *mut c_void); ++ pub fn wxbr_sizer_detach(sizer: *mut c_void, win: *mut c_void); + pub fn wxbr_fit(win: *mut c_void); + pub fn wxbr_set_min_size(win: *mut c_void, w: c_int, h: c_int); + pub fn wxbr_static_text(parent: *mut c_void, label: *const c_char) -> *mut c_void; + pub fn wxbr_set_label(win: *mut c_void, label: *const c_char); ++ pub fn wxbr_get_label(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int; + pub fn wxbr_set_bold(win: *mut c_void); + pub fn wxbr_set_font_size(win: *mut c_void, pts: c_int); + pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void; @@ -68,10 +69,22 @@ + pub fn wxbr_dvlc_set_cell(win: *mut c_void, row: usize, col: usize, value: *const c_char); + pub fn wxbr_dvlc_get_cell(win: *mut c_void, row: usize, col: usize, buf: *mut c_char, cap: c_int) -> c_int; + pub fn wxbr_dvlc_col_count(win: *mut c_void) -> c_int; ++ pub fn wxbr_dvlc_set_sort_indicator(win: *mut c_void, col: c_int, active: c_int, ascending: c_int); + pub fn wxbr_dvlc_col_at_pos(win: *mut c_void, pos: c_int) -> c_int; + pub fn wxbr_dvlc_selected_row(win: *mut c_void) -> c_long; + pub fn wxbr_dvlc_select_row(win: *mut c_void, row: c_long); + pub fn wxbr_timer(id: c_int, ms: c_int) -> *mut c_void; ++ pub fn wxbr_gauge(parent: *mut c_void, range: c_int) -> *mut c_void; ++ pub fn wxbr_gauge_set_range(win: *mut c_void, range: c_int); ++ pub fn wxbr_gauge_set_value(win: *mut c_void, value: c_int); ++ pub fn wxbr_gauge_pulse(win: *mut c_void); ++ pub fn wxbr_show(win: *mut c_void, shown: c_int); ++ pub fn wxbr_launch_browser(url: *const c_char) -> c_int; ++ pub fn wxbr_set_appearance_system(); ++ pub fn wxbr_is_dark() -> c_int; ++ pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8); ++ pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int); ++ pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int); + pub fn wxbr_destroy(win: *mut c_void); + } +} @@ -101,6 +114,7 @@ + DvlcHeaderClick, + DvlcReordered, + TimerTick, ++ DvlcActivated, +} + +impl WxEventKind { @@ -112,11 +126,36 @@ + 5 => WxEventKind::DvlcHeaderClick, + 6 => WxEventKind::DvlcReordered, + 7 => WxEventKind::TimerTick, ++ 8 => WxEventKind::DvlcActivated, + _ => return None, + }) + } +} + ++/// Open a URL in the system default browser. Returns true on success. ++pub fn launch_browser(url: &str) -> bool { ++ let c = CString::new(url).unwrap_or_default(); ++ unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 } ++} ++ ++/// Ask wx to follow the system light/dark appearance (no-op before 3.3). ++pub fn set_appearance_system() { ++ unsafe { notsafe::wxbr_set_appearance_system() } ++} ++ ++/// True if the current system appearance is dark. ++pub fn is_dark() -> bool { ++ unsafe { notsafe::wxbr_is_dark() != 0 } ++} ++ ++/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight, ++/// 3=button face, 4=grey text. Returns (r, g, b). ++pub fn system_color(which: i32) -> (u8, u8, u8) { ++ let (mut r, mut g, mut b) = (0u8, 0u8, 0u8); ++ unsafe { notsafe::wxbr_system_color(which, &mut r, &mut g, &mut b) } ++ (r, g, b) ++} ++ +/// A widget event: kind plus two payload words. +/// ButtonClicked: p1 = button id. +/// ClbToggled: p1 = control handle, p2 = item index. @@ -189,6 +228,18 @@ + unsafe { notsafe::wxbr_set_sizer(win.0, self.0) } + } + ++ /// Re-run this window's sizer (self = a window). Call after adding a child ++ /// window to an already-installed sizer, or after rebuilding the table. ++ pub fn layout(&self) { ++ unsafe { notsafe::wxbr_layout(self.0) } ++ } ++ ++ /// Detach a child window from this sizer (self = a sizer) without ++ /// destroying it. Use before destroying a sizer-managed window. ++ pub fn detach(&self, win: Widget) { ++ unsafe { notsafe::wxbr_sizer_detach(self.0, win.0) } ++ } ++ + pub fn fit(&self, win: Widget) { + unsafe { notsafe::wxbr_fit(win.0) } + } @@ -207,6 +258,18 @@ + unsafe { notsafe::wxbr_set_label(self.0, c.as_ptr()) } + } + ++ /// Read back a control's current label text (self-test uses this to verify ++ /// what a KPI actually displays). ++ pub fn get_label(&self) -> String { ++ let mut buf = vec![0i8; 4096]; ++ let n = unsafe { notsafe::wxbr_get_label(self.0, buf.as_mut_ptr(), buf.len() as c_int) }; ++ if n <= 0 { ++ return String::new(); ++ } ++ let bytes: Vec = buf[..(n - 1) as usize].iter().map(|&b| b as u8).collect(); ++ String::from_utf8_lossy(&bytes).into_owned() ++ } ++ + pub fn set_bold(&self) { + unsafe { notsafe::wxbr_set_bold(self.0) } + } @@ -368,10 +431,53 @@ + unsafe { notsafe::wxbr_dvlc_select_row(self.0, row as c_long) } + } + ++ /// Show or clear the native sort arrow on a column (creation index). ++ pub fn dvlc_set_sort_indicator(&self, col: usize, active: bool, ascending: bool) { ++ unsafe { ++ notsafe::wxbr_dvlc_set_sort_indicator( ++ self.0, ++ col as c_int, ++ active as c_int, ++ ascending as c_int, ++ ) ++ } ++ } ++ + pub fn timer(id: i32, ms: i32) -> Widget { + Widget(unsafe { notsafe::wxbr_timer(id, ms) }) + } + ++ // ---- gauge (progress bar) ---- ++ ++ pub fn gauge(parent: Widget, range: i32) -> Widget { ++ Widget(unsafe { notsafe::wxbr_gauge(parent.0, range) }) ++ } ++ ++ pub fn gauge_set_range(&self, range: i32) { ++ unsafe { notsafe::wxbr_gauge_set_range(self.0, range) } ++ } ++ ++ pub fn gauge_set_value(&self, value: i32) { ++ unsafe { notsafe::wxbr_gauge_set_value(self.0, value) } ++ } ++ ++ pub fn gauge_pulse(&self) { ++ unsafe { notsafe::wxbr_gauge_pulse(self.0) } ++ } ++ ++ /// Show or hide this window. ++ pub fn show(&self, shown: bool) { ++ unsafe { notsafe::wxbr_show(self.0, shown as c_int) } ++ } ++ ++ pub fn set_bg(&self, r: u8, g: u8, b: u8) { ++ unsafe { notsafe::wxbr_set_bg(self.0, r as c_int, g as c_int, b as c_int) } ++ } ++ ++ pub fn set_fg(&self, r: u8, g: u8, b: u8) { ++ unsafe { notsafe::wxbr_set_fg(self.0, r as c_int, g as c_int, b as c_int) } ++ } ++ + /// Deferred destruction (safe from event handlers); used to rebuild + /// the table when its column set changes. + pub fn destroy(&self) { diff --git a/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch b/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch index 160c6a74..47a1c386 100644 --- a/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch +++ b/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch @@ -1,7 +1,6 @@ --- a/cpp_src/widgets_bridge.cpp +++ b/cpp_src/widgets_bridge.cpp -+++ wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp 2026-09-15 13:14:21.288485800 -0600 -@@ -0,0 +1,352 @@ +@@ -0,0 +1,482 @@ +// widgets_bridge.cpp — alkane-toolkit extension to wx-rs +// Adds the widget/event surface the toolkit UI needs on top of the upstream +// render-callback bridge (which is kept untouched). @@ -18,6 +17,10 @@ +#include +#include +#include ++#include ++#include ++#include ++#include + +typedef void (*WxWidgetEventFn)(int kind, long p1, long p2); +static WxWidgetEventFn g_widget_event = nullptr; @@ -30,6 +33,7 @@ + WxEV_DVLC_HEADER_CLICK = 5, + WxEV_DVLC_REORDERED = 6, + WxEV_TIMER_TICK = 7, ++ WxEV_DVLC_ACTIVATED = 8, +}; + +extern "C" { @@ -87,6 +91,17 @@ + ((wxWindow*)win)->SetSizer((wxSizer*)sizer); +} + ++// Re-run this window's sizer to (re)position its children. Needed after a ++// child window is added to an already-installed sizer (e.g. the table, which ++// is created after the frame's sizer is set and rebuilt on column changes). ++void wxbr_layout(void* win) { ((wxWindow*)win)->Layout(); } ++ ++// Remove a child window from a sizer without destroying the window. Call this ++// before destroying a sizer-managed window so the sizer keeps no dangling item. ++void wxbr_sizer_detach(void* sizer, void* win) { ++ ((wxSizer*)sizer)->Detach((wxWindow*)win); ++} ++ +void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); } + +void wxbr_set_min_size(void* win, int w, int h) { @@ -106,6 +121,20 @@ + else ((wxWindow*)win)->SetLabel(wxString::FromUTF8(label)); +} + ++// Read a control's current label text (used by the headless self-test to read ++// back what a KPI static text actually displays). ++int wxbr_get_label(void* win, char* buf, int cap) { ++ wxWindow* w = (wxWindow*)win; ++ wxStaticText* st = dynamic_cast(w); ++ wxString s = st ? st->GetLabel() : w->GetLabel(); ++ wxCharBuffer b = s.ToUTF8(); ++ int n = (int)strlen(b.data()); ++ if (n >= cap) n = cap - 1; ++ memcpy(buf, b.data(), n); ++ buf[n] = 0; ++ return n + 1; ++} ++ +void wxbr_set_bold(void* win) { + wxWindow* w = (wxWindow*)win; + wxFont f = w->GetFont(); @@ -252,6 +281,19 @@ + lc->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) { + if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0); + }); ++ // Row activation (double-click / Enter): report the row + column so the app ++ // can, e.g., open the miner's IP in a browser. ++ lc->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) { ++ if (g_widget_event) { ++ wxDataViewListCtrl* lc = ++ dynamic_cast((wxWindow*)e.GetEventObject()); ++ if (!lc) return; ++ wxDataViewItem item = e.GetItem(); ++ if (!item.IsOk()) return; ++ int row = lc->GetStore()->GetRow(item); ++ g_widget_event(WxEV_DVLC_ACTIVATED, row, (long)e.GetColumn()); ++ } ++ }); + return (void*)lc; +} + @@ -273,7 +315,9 @@ + wxVector values; + for (int i = 0; i < nvals; i++) { + if (i == 0) -+ values.push_back(wxVariant(false)); // toggle column (checkbox) ++ // toggle column (checkbox): vals[0] carries the checked state as "1"/"0" ++ // so a refresh preserves the row selection instead of clearing it. ++ values.push_back(wxVariant(vals[0] && vals[0][0] == '1')); + else if (vals[i]) + values.push_back(wxVariant(wxString::FromUTF8(vals[i]))); + else @@ -317,6 +361,21 @@ + return (int)((wxDataViewListCtrl*)win)->GetColumnCount(); +} + ++// Show/clear the native sort arrow on a column (creation index). The app does ++// its own sorting; this only draws the indicator so the header shows which ++// column is the sort key and in which direction. ++void wxbr_dvlc_set_sort_indicator(void* win, int col, int active, int ascending) { ++ wxDataViewCtrl* dv = (wxDataViewCtrl*)win; ++ if (col < 0 || (unsigned)col >= dv->GetColumnCount()) return; ++ wxDataViewColumn* c = dv->GetColumn(col); ++ if (!c) return; ++ if (active) { ++ c->SetSortOrder(ascending != 0); ++ } else if (c->IsSortKey()) { ++ c->UnsetAsSortKey(); ++ } ++} ++ +// model column index (creation order) currently shown at display position pos +int wxbr_dvlc_col_at_pos(void* win, int pos) { + wxDataViewCtrl* dv = (wxDataViewCtrl*)win; @@ -349,6 +408,76 @@ + return (void*)t; +} + ++// ---- gauge (progress bar) --------------------------------------------------- ++ ++void* wxbr_gauge(void* parent, int range) { ++ wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range, ++ wxDefaultPosition, wxSize(-1, 6), ++ wxGA_HORIZONTAL | wxGA_SMOOTH); ++ return (void*)g; ++} ++ ++void wxbr_gauge_set_range(void* win, int range) { ++ ((wxGauge*)win)->SetRange(range < 1 ? 1 : range); ++} ++ ++void wxbr_gauge_set_value(void* win, int value) { ++ ((wxGauge*)win)->SetValue(value); ++} ++ ++void wxbr_gauge_pulse(void* win) { ((wxGauge*)win)->Pulse(); } ++ ++// ---- show / hide any window ------------------------------------------------- ++ ++void wxbr_show(void* win, int shown) { ((wxWindow*)win)->Show(shown != 0); } ++ ++// ---- open a URL in the default browser -------------------------------------- ++ ++int wxbr_launch_browser(const char* url) { ++ return wxLaunchDefaultBrowser(wxString::FromUTF8(url)) ? 1 : 0; ++} ++ ++// ---- appearance / dark mode ------------------------------------------------- ++ ++void wxbr_set_appearance_system() { ++#if wxCHECK_VERSION(3, 3, 0) ++ if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System); ++#endif ++} ++ ++int wxbr_is_dark() { ++ return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0; ++} ++ ++// Fetch a theme colour so custom widgets follow light/dark. which: ++// 0=window bg, 1=window text, 2=highlight, 3=button face, 4=grey text. ++void wxbr_system_color(int which, unsigned char* r, unsigned char* g, ++ unsigned char* b) { ++ wxSystemColour idx = wxSYS_COLOUR_WINDOW; ++ switch (which) { ++ case 0: idx = wxSYS_COLOUR_WINDOW; break; ++ case 1: idx = wxSYS_COLOUR_WINDOWTEXT; break; ++ case 2: idx = wxSYS_COLOUR_HIGHLIGHT; break; ++ case 3: idx = wxSYS_COLOUR_BTNFACE; break; ++ case 4: idx = wxSYS_COLOUR_GRAYTEXT; break; ++ default: idx = wxSYS_COLOUR_WINDOW; break; ++ } ++ wxColour c = wxSystemSettings::GetColour(idx); ++ *r = c.Red(); ++ *g = c.Green(); ++ *b = c.Blue(); ++} ++ ++// ---- widget colours (for the KPI cards) ------------------------------------- ++ ++void wxbr_set_bg(void* win, int r, int g, int b) { ++ ((wxWindow*)win)->SetBackgroundColour(wxColour(r, g, b)); ++} ++ ++void wxbr_set_fg(void* win, int r, int g, int b) { ++ ((wxWindow*)win)->SetForegroundColour(wxColour(r, g, b)); ++} ++ +// ---- deferred destroy (safe from event handlers) ---------------------------- + +void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); } diff --git a/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp b/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp index b9b0a2c5..0e604e5f 100644 --- a/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp +++ b/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp @@ -14,6 +14,10 @@ #include #include #include +#include +#include +#include +#include typedef void (*WxWidgetEventFn)(int kind, long p1, long p2); static WxWidgetEventFn g_widget_event = nullptr; @@ -26,6 +30,7 @@ enum WxWidgetEventKind { WxEV_DVLC_HEADER_CLICK = 5, WxEV_DVLC_REORDERED = 6, WxEV_TIMER_TICK = 7, + WxEV_DVLC_ACTIVATED = 8, }; extern "C" { @@ -83,6 +88,17 @@ void wxbr_set_sizer(void* win, void* sizer) { ((wxWindow*)win)->SetSizer((wxSizer*)sizer); } +// Re-run this window's sizer to (re)position its children. Needed after a +// child window is added to an already-installed sizer (e.g. the table, which +// is created after the frame's sizer is set and rebuilt on column changes). +void wxbr_layout(void* win) { ((wxWindow*)win)->Layout(); } + +// Remove a child window from a sizer without destroying the window. Call this +// before destroying a sizer-managed window so the sizer keeps no dangling item. +void wxbr_sizer_detach(void* sizer, void* win) { + ((wxSizer*)sizer)->Detach((wxWindow*)win); +} + void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); } void wxbr_set_min_size(void* win, int w, int h) { @@ -102,6 +118,20 @@ void wxbr_set_label(void* win, const char* label) { else ((wxWindow*)win)->SetLabel(wxString::FromUTF8(label)); } +// Read a control's current label text (used by the headless self-test to read +// back what a KPI static text actually displays). +int wxbr_get_label(void* win, char* buf, int cap) { + wxWindow* w = (wxWindow*)win; + wxStaticText* st = dynamic_cast(w); + wxString s = st ? st->GetLabel() : w->GetLabel(); + wxCharBuffer b = s.ToUTF8(); + int n = (int)strlen(b.data()); + if (n >= cap) n = cap - 1; + memcpy(buf, b.data(), n); + buf[n] = 0; + return n + 1; +} + void wxbr_set_bold(void* win) { wxWindow* w = (wxWindow*)win; wxFont f = w->GetFont(); @@ -248,6 +278,19 @@ void* wxbr_dvlc(void* parent) { lc->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) { if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0); }); + // Row activation (double-click / Enter): report the row + column so the app + // can, e.g., open the miner's IP in a browser. + lc->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) { + if (g_widget_event) { + wxDataViewListCtrl* lc = + dynamic_cast((wxWindow*)e.GetEventObject()); + if (!lc) return; + wxDataViewItem item = e.GetItem(); + if (!item.IsOk()) return; + int row = lc->GetStore()->GetRow(item); + g_widget_event(WxEV_DVLC_ACTIVATED, row, (long)e.GetColumn()); + } + }); return (void*)lc; } @@ -269,7 +312,9 @@ void wxbr_dvlc_append_row(void* win, int nvals, const char** vals) { wxVector values; for (int i = 0; i < nvals; i++) { if (i == 0) - values.push_back(wxVariant(false)); // toggle column (checkbox) + // toggle column (checkbox): vals[0] carries the checked state as "1"/"0" + // so a refresh preserves the row selection instead of clearing it. + values.push_back(wxVariant(vals[0] && vals[0][0] == '1')); else if (vals[i]) values.push_back(wxVariant(wxString::FromUTF8(vals[i]))); else @@ -313,6 +358,30 @@ int wxbr_dvlc_col_count(void* win) { return (int)((wxDataViewListCtrl*)win)->GetColumnCount(); } +// Update a column's header text in place (creation index) without recreating +// the control -- used to refresh the ASCII sort marker on a sort click. +void wxbr_dvlc_set_col_title(void* win, int col, const char* title) { + wxDataViewCtrl* dv = (wxDataViewCtrl*)win; + if (col < 0 || (unsigned)col >= dv->GetColumnCount()) return; + wxDataViewColumn* c = dv->GetColumn(col); + if (c) c->SetTitle(wxString::FromUTF8(title)); +} + +// Show/clear the native sort arrow on a column (creation index). The app does +// its own sorting; this only draws the indicator so the header shows which +// column is the sort key and in which direction. +void wxbr_dvlc_set_sort_indicator(void* win, int col, int active, int ascending) { + wxDataViewCtrl* dv = (wxDataViewCtrl*)win; + if (col < 0 || (unsigned)col >= dv->GetColumnCount()) return; + wxDataViewColumn* c = dv->GetColumn(col); + if (!c) return; + if (active) { + c->SetSortOrder(ascending != 0); + } else if (c->IsSortKey()) { + c->UnsetAsSortKey(); + } +} + // model column index (creation order) currently shown at display position pos int wxbr_dvlc_col_at_pos(void* win, int pos) { wxDataViewCtrl* dv = (wxDataViewCtrl*)win; @@ -345,6 +414,76 @@ void* wxbr_timer(int id, int ms) { return (void*)t; } +// ---- gauge (progress bar) --------------------------------------------------- + +void* wxbr_gauge(void* parent, int range) { + wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range, + wxDefaultPosition, wxSize(-1, 6), + wxGA_HORIZONTAL | wxGA_SMOOTH); + return (void*)g; +} + +void wxbr_gauge_set_range(void* win, int range) { + ((wxGauge*)win)->SetRange(range < 1 ? 1 : range); +} + +void wxbr_gauge_set_value(void* win, int value) { + ((wxGauge*)win)->SetValue(value); +} + +void wxbr_gauge_pulse(void* win) { ((wxGauge*)win)->Pulse(); } + +// ---- show / hide any window ------------------------------------------------- + +void wxbr_show(void* win, int shown) { ((wxWindow*)win)->Show(shown != 0); } + +// ---- open a URL in the default browser -------------------------------------- + +int wxbr_launch_browser(const char* url) { + return wxLaunchDefaultBrowser(wxString::FromUTF8(url)) ? 1 : 0; +} + +// ---- appearance / dark mode ------------------------------------------------- + +void wxbr_set_appearance_system() { +#if wxCHECK_VERSION(3, 3, 0) + if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System); +#endif +} + +int wxbr_is_dark() { + return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0; +} + +// Fetch a theme colour so custom widgets follow light/dark. which: +// 0=window bg, 1=window text, 2=highlight, 3=button face, 4=grey text. +void wxbr_system_color(int which, unsigned char* r, unsigned char* g, + unsigned char* b) { + wxSystemColour idx = wxSYS_COLOUR_WINDOW; + switch (which) { + case 0: idx = wxSYS_COLOUR_WINDOW; break; + case 1: idx = wxSYS_COLOUR_WINDOWTEXT; break; + case 2: idx = wxSYS_COLOUR_HIGHLIGHT; break; + case 3: idx = wxSYS_COLOUR_BTNFACE; break; + case 4: idx = wxSYS_COLOUR_GRAYTEXT; break; + default: idx = wxSYS_COLOUR_WINDOW; break; + } + wxColour c = wxSystemSettings::GetColour(idx); + *r = c.Red(); + *g = c.Green(); + *b = c.Blue(); +} + +// ---- widget colours (for the KPI cards) ------------------------------------- + +void wxbr_set_bg(void* win, int r, int g, int b) { + ((wxWindow*)win)->SetBackgroundColour(wxColour(r, g, b)); +} + +void wxbr_set_fg(void* win, int r, int g, int b) { + ((wxWindow*)win)->SetForegroundColour(wxColour(r, g, b)); +} + // ---- deferred destroy (safe from event handlers) ---------------------------- void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); } diff --git a/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs b/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs index 42c31bc0..26fcb7d2 100644 --- a/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs +++ b/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs @@ -20,10 +20,13 @@ mod notsafe { pub fn wxbr_sizer_add_spacer(sizer: *mut c_void, px: c_int); pub fn wxbr_sizer_add_stretch(sizer: *mut c_void, proportion: c_int); pub fn wxbr_set_sizer(win: *mut c_void, sizer: *mut c_void); + pub fn wxbr_layout(win: *mut c_void); + pub fn wxbr_sizer_detach(sizer: *mut c_void, win: *mut c_void); pub fn wxbr_fit(win: *mut c_void); pub fn wxbr_set_min_size(win: *mut c_void, w: c_int, h: c_int); pub fn wxbr_static_text(parent: *mut c_void, label: *const c_char) -> *mut c_void; pub fn wxbr_set_label(win: *mut c_void, label: *const c_char); + pub fn wxbr_get_label(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int; pub fn wxbr_set_bold(win: *mut c_void); pub fn wxbr_set_font_size(win: *mut c_void, pts: c_int); pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void; @@ -53,10 +56,23 @@ mod notsafe { pub fn wxbr_dvlc_set_cell(win: *mut c_void, row: usize, col: usize, value: *const c_char); pub fn wxbr_dvlc_get_cell(win: *mut c_void, row: usize, col: usize, buf: *mut c_char, cap: c_int) -> c_int; pub fn wxbr_dvlc_col_count(win: *mut c_void) -> c_int; + pub fn wxbr_dvlc_set_col_title(win: *mut c_void, col: c_int, title: *const c_char); + pub fn wxbr_dvlc_set_sort_indicator(win: *mut c_void, col: c_int, active: c_int, ascending: c_int); pub fn wxbr_dvlc_col_at_pos(win: *mut c_void, pos: c_int) -> c_int; pub fn wxbr_dvlc_selected_row(win: *mut c_void) -> c_long; pub fn wxbr_dvlc_select_row(win: *mut c_void, row: c_long); pub fn wxbr_timer(id: c_int, ms: c_int) -> *mut c_void; + pub fn wxbr_gauge(parent: *mut c_void, range: c_int) -> *mut c_void; + pub fn wxbr_gauge_set_range(win: *mut c_void, range: c_int); + pub fn wxbr_gauge_set_value(win: *mut c_void, value: c_int); + pub fn wxbr_gauge_pulse(win: *mut c_void); + pub fn wxbr_show(win: *mut c_void, shown: c_int); + pub fn wxbr_launch_browser(url: *const c_char) -> c_int; + pub fn wxbr_set_appearance_system(); + pub fn wxbr_is_dark() -> c_int; + pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8); + pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int); + pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int); pub fn wxbr_destroy(win: *mut c_void); } } @@ -86,6 +102,7 @@ pub enum WxEventKind { DvlcHeaderClick, DvlcReordered, TimerTick, + DvlcActivated, } impl WxEventKind { @@ -97,11 +114,36 @@ impl WxEventKind { 5 => WxEventKind::DvlcHeaderClick, 6 => WxEventKind::DvlcReordered, 7 => WxEventKind::TimerTick, + 8 => WxEventKind::DvlcActivated, _ => return None, }) } } +/// Open a URL in the system default browser. Returns true on success. +pub fn launch_browser(url: &str) -> bool { + let c = CString::new(url).unwrap_or_default(); + unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 } +} + +/// Ask wx to follow the system light/dark appearance (no-op before 3.3). +pub fn set_appearance_system() { + unsafe { notsafe::wxbr_set_appearance_system() } +} + +/// True if the current system appearance is dark. +pub fn is_dark() -> bool { + unsafe { notsafe::wxbr_is_dark() != 0 } +} + +/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight, +/// 3=button face, 4=grey text. Returns (r, g, b). +pub fn system_color(which: i32) -> (u8, u8, u8) { + let (mut r, mut g, mut b) = (0u8, 0u8, 0u8); + unsafe { notsafe::wxbr_system_color(which, &mut r, &mut g, &mut b) } + (r, g, b) +} + /// A widget event: kind plus two payload words. /// ButtonClicked: p1 = button id. /// ClbToggled: p1 = control handle, p2 = item index. @@ -174,6 +216,18 @@ impl Widget { unsafe { notsafe::wxbr_set_sizer(win.0, self.0) } } + /// Re-run this window's sizer (self = a window). Call after adding a child + /// window to an already-installed sizer, or after rebuilding the table. + pub fn layout(&self) { + unsafe { notsafe::wxbr_layout(self.0) } + } + + /// Detach a child window from this sizer (self = a sizer) without + /// destroying it. Use before destroying a sizer-managed window. + pub fn detach(&self, win: Widget) { + unsafe { notsafe::wxbr_sizer_detach(self.0, win.0) } + } + pub fn fit(&self, win: Widget) { unsafe { notsafe::wxbr_fit(win.0) } } @@ -192,6 +246,18 @@ impl Widget { unsafe { notsafe::wxbr_set_label(self.0, c.as_ptr()) } } + /// Read back a control's current label text (self-test uses this to verify + /// what a KPI actually displays). + pub fn get_label(&self) -> String { + let mut buf = vec![0i8; 4096]; + let n = unsafe { notsafe::wxbr_get_label(self.0, buf.as_mut_ptr(), buf.len() as c_int) }; + if n <= 0 { + return String::new(); + } + let bytes: Vec = buf[..(n - 1) as usize].iter().map(|&b| b as u8).collect(); + String::from_utf8_lossy(&bytes).into_owned() + } + pub fn set_bold(&self) { unsafe { notsafe::wxbr_set_bold(self.0) } } @@ -353,10 +419,59 @@ impl Widget { unsafe { notsafe::wxbr_dvlc_select_row(self.0, row as c_long) } } + /// Update a column's header text in place (creation index). + pub fn dvlc_set_col_title(&self, col: usize, title: &str) { + let c = CString::new(title).unwrap_or_default(); + unsafe { notsafe::wxbr_dvlc_set_col_title(self.0, col as c_int, c.as_ptr()) } + } + + /// Show or clear the native sort arrow on a column (creation index). + pub fn dvlc_set_sort_indicator(&self, col: usize, active: bool, ascending: bool) { + unsafe { + notsafe::wxbr_dvlc_set_sort_indicator( + self.0, + col as c_int, + active as c_int, + ascending as c_int, + ) + } + } + pub fn timer(id: i32, ms: i32) -> Widget { Widget(unsafe { notsafe::wxbr_timer(id, ms) }) } + // ---- gauge (progress bar) ---- + + pub fn gauge(parent: Widget, range: i32) -> Widget { + Widget(unsafe { notsafe::wxbr_gauge(parent.0, range) }) + } + + pub fn gauge_set_range(&self, range: i32) { + unsafe { notsafe::wxbr_gauge_set_range(self.0, range) } + } + + pub fn gauge_set_value(&self, value: i32) { + unsafe { notsafe::wxbr_gauge_set_value(self.0, value) } + } + + pub fn gauge_pulse(&self) { + unsafe { notsafe::wxbr_gauge_pulse(self.0) } + } + + /// Show or hide this window. + pub fn show(&self, shown: bool) { + unsafe { notsafe::wxbr_show(self.0, shown as c_int) } + } + + pub fn set_bg(&self, r: u8, g: u8, b: u8) { + unsafe { notsafe::wxbr_set_bg(self.0, r as c_int, g as c_int, b as c_int) } + } + + pub fn set_fg(&self, r: u8, g: u8, b: u8) { + unsafe { notsafe::wxbr_set_fg(self.0, r as c_int, g as c_int, b as c_int) } + } + /// Deferred destruction (safe from event handlers); used to rebuild /// the table when its column set changes. pub fn destroy(&self) {