diff --git a/crates/alkane-gui/src/credentials.rs b/crates/alkane-gui/src/credentials.rs index 27be41c2..ffcbf064 100644 --- a/crates/alkane-gui/src/credentials.rs +++ b/crates/alkane-gui/src/credentials.rs @@ -74,12 +74,15 @@ pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> { save_creds_file(CREDENTIALS_FILE, user, pass) } -/// Load the saved SSH username/password for the PIC probe, if any. +/// Load the saved SSH username/password (used by the Braiins restore-to-stock +/// flow), if any. pub fn load_ssh_credentials() -> Option<(String, String)> { load_creds_file(SSH_CREDENTIALS_FILE) } -/// Save the SSH username/password for the PIC probe (0600). +/// Save the SSH username/password (0600). Retained for a future SSH-login dialog +/// now that the SSH PIC probe that used to save it has been removed (round 14 #5). +#[allow(dead_code)] pub fn save_ssh_credentials(user: &str, pass: &str) -> std::io::Result<()> { save_creds_file(SSH_CREDENTIALS_FILE, user, pass) } diff --git a/crates/alkane-gui/src/fixtures.rs b/crates/alkane-gui/src/fixtures.rs index 9b87c193..435ce29d 100644 --- a/crates/alkane-gui/src/fixtures.rs +++ b/crates/alkane-gui/src/fixtures.rs @@ -158,6 +158,7 @@ impl Board { power_limit: self.mining, tuning: self.mining, firmware_flash, + pools: true, }, // Demo values for the round-8/9 columns (synthetic, so the columns // show variety offline). control_board is derived above via naming. diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 9ed9a637..173de546 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -7,7 +7,6 @@ mod fixtures; mod log_scan; mod model; mod naming; -mod pic_probe; mod presets; mod restore; mod scan; diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 687ca796..fe00340f 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -134,6 +134,30 @@ pub fn decode_segments_plain(s: &str) -> String { .collect::() } +/// Replace every case-insensitive occurrence of `placeholder` in `s` with +/// `value` (round 14 #7 worker templates). Placeholders and the surrounding +/// worker name are ASCII, so lowercasing preserves byte offsets; a non-ASCII +/// input (offsets would shift) falls back to a case-sensitive replace. +fn replace_placeholder_ci(s: &str, placeholder: &str, value: &str) -> String { + if !s.is_ascii() { + return s.replace(placeholder, value); + } + let hay = s.to_ascii_lowercase(); + let needle = placeholder.to_ascii_lowercase(); + let mut out = String::with_capacity(s.len()); + let mut last = 0usize; + let mut from = 0usize; + while let Some(rel) = hay[from..].find(&needle) { + let at = from + rel; + out.push_str(&s[last..at]); + out.push_str(value); + last = at + placeholder.len(); + from = last; + } + out.push_str(&s[last..]); + out +} + /// Split a full pool worker "account.worker" into (account, worker). Mining /// pools name a worker "."; split on the first '.'. With no '.', /// the whole string is the account and the worker name is empty. @@ -192,6 +216,9 @@ pub struct MinerCaps { /// Whether this miner's asic-rs driver supports `upgrade_firmware` /// (probed via `supports_upgrade_firmware()` at scan time). pub firmware_flash: bool, + /// Whether this miner's driver supports writing pool configuration (probed + /// via `supports_pools_config()` at scan time; round 14 #7). + pub pools: bool, } impl MinerCaps { @@ -205,6 +232,7 @@ impl MinerCaps { power_limit: self.power_limit && other.power_limit, tuning: self.tuning && other.tuning, firmware_flash: self.firmware_flash && other.firmware_flash, + pools: self.pools && other.pools, } } @@ -233,6 +261,7 @@ impl MinerCaps { || self.power_limit || self.tuning || self.firmware_flash + || self.pools } } @@ -518,6 +547,47 @@ impl MinerRow { parts.join(", ") } + /// Expand a worker-name template against this miner's scanned data (round 14 + /// #7). Placeholders are case-insensitive and wrapped in braces: + /// {ip1}..{ip4} the four IP octets {serial} serial number + /// {mac} MAC with ':' removed {brand} manufacturer + /// {model} model {submodel} model sub-variant + /// {cpu} control-board CPU {cb} control-board code + /// {firmware} firmware family {hostname} hostname + /// {nameplate-hr} rated hashrate in TH (integer, no unit) + /// Unknown placeholders are left untouched so a typo is visible. + pub fn expand_worker_template(&self, template: &str) -> String { + let octets: Vec<&str> = self.ip.split('.').collect(); + let oct = |i: usize| octets.get(i).copied().unwrap_or("").to_string(); + let nameplate = if self.expected_ths > 0.0 { + format!("{:.0}", self.expected_ths) + } else { + String::new() + }; + let subs: [(&str, String); 15] = [ + ("ip1", oct(0)), + ("ip2", oct(1)), + ("ip3", oct(2)), + ("ip4", oct(3)), + ("serial", self.serial.clone()), + ("mac", self.mac.replace(':', "")), + ("nameplate-hr", nameplate), + ("brand", self.brand.clone()), + ("model", self.model.clone()), + ("submodel", self.submodel.clone()), + ("cpu", self.cpu.clone()), + ("cb", self.board_code.clone()), + ("firmware", self.firmware.clone()), + ("hostname", self.hostname.clone()), + ("fw", self.firmware.clone()), + ]; + let mut out = template.to_string(); + for (key, val) in subs { + out = replace_placeholder_ci(&out, &format!("{{{key}}}"), &val); + } + out + } + /// Upsert into `rows` by ip; returns true if the row is new. pub fn upsert_into(self, rows: &mut Vec) -> bool { if let Some(r) = rows.iter_mut().find(|r| r.ip == self.ip) { @@ -1277,6 +1347,39 @@ mod tests { (rows, view, idx) } + #[test] + fn worker_template_expands_scanned_fields() { + // Round 14 #7: placeholders are case-insensitive; MAC drops its colons; + // nameplate-hr is the rated hashrate in whole TH; unknown keys are kept. + let r = MinerRow { + ip: "10.2.3.44".into(), + serial: "SNXYZ".into(), + mac: "AA:BB:CC:11:22:33".into(), + brand: "Antminer".into(), + model: "S19j Pro".into(), + submodel: "".into(), + cpu: "AML".into(), + board_code: "C76".into(), + firmware: "VNish".into(), + hostname: "rig-1".into(), + expected_ths: 104.0, + ..Default::default() + }; + assert_eq!(r.expand_worker_template("{ip3}x{ip4}"), "3x44"); + assert_eq!(r.expand_worker_template("{MAC}"), "AABBCC112233"); + assert_eq!(r.expand_worker_template("{mac}"), "AABBCC112233"); + assert_eq!(r.expand_worker_template("{nameplate-hr}TH"), "104TH"); + assert_eq!( + r.expand_worker_template("{brand}-{cpu}-{cb}-{fw}"), + "Antminer-AML-C76-VNish" + ); + assert_eq!(r.expand_worker_template("{serial}"), "SNXYZ"); + // Unknown placeholder is left untouched. + assert_eq!(r.expand_worker_template("w-{bogus}"), "w-{bogus}"); + // A plain worker name with no placeholders is unchanged. + assert_eq!(r.expand_worker_template("worker1"), "worker1"); + } + #[test] fn component_health_maps_states_to_the_four_levels() { // Round 13 #3: power/control/fan/board health map to the grey/red/yellow/ @@ -1901,6 +2004,7 @@ mod tests { power_limit: true, tuning: true, firmware_flash: true, + pools: true, }; let idle = MinerCaps { fault_light: true, restart: true, ..Default::default() }; // Two full miners keep every action. diff --git a/crates/alkane-gui/src/pic_probe.rs b/crates/alkane-gui/src/pic_probe.rs deleted file mode 100644 index a3012361..00000000 --- a/crates/alkane-gui/src/pic_probe.rs +++ /dev/null @@ -1,238 +0,0 @@ -//! Real PIC-vs-noPIC detection for Antminer control boards, over SSH + i2c-tools. -//! -//! asic-rs and the miner's network API cannot report PIC presence (see the -//! project wiki, 30-power-thermal-and-board-identity/hashboard-eeprom-pic.md); -//! the authoritative tell lives on the control board's I2C bus. On a -//! PIC/MCU-equipped board, I2C 0x48 is a hashboard MCU exposing an 8-byte -//! register file that WRAPS every 8 bytes (e.g. `17 00 4b 50 7f 00 00 00 ...`); -//! on a noPIC board, 0x48 is a plain LM75 temperature sensor with a 4-register -//! layout that wraps every 4 bytes. We read 0x48 with `i2cdump` over SSH and -//! discriminate by that period. -//! -//! This is a slow, credentialed, opt-in probe (an SSH handshake + shell command -//! per miner), never part of the fast network scan. We shell out to `ssh` -//! (via `sshpass` for password auth) rather than pull in an SSH crate, so the -//! offline/vendored build is unaffected. - -use std::process::Command; -use std::time::Duration; - -/// SSH login for the miner's control board (distinct from the web/API creds). -#[derive(Debug, Clone)] -pub struct SshCreds { - pub user: String, - /// Empty means key-based auth (BatchMode); otherwise `sshpass` is used. - pub pass: String, -} - -/// I2C buses to probe for the hashboard MCU/LM75 at 0x48, most-likely first, -/// chosen from the control-board family. `probe_pic` tries them in order and -/// stops at the first bus that classifies definitively, so extra fallbacks only -/// cost an SSH round-trip when earlier buses are absent/indeterminate. -/// -/// Confirmed live (2026-09-19): a VNish CVITek S19k Pro exposes the hashboard -/// MCU on i2c-3 (i2c-4 is the second, usually empty); its buses are i2c-3/i2c-4, -/// NOT i2c-0/i2c-1 -- the earlier CVITek -> [1,0] guess never found the MCU, -/// which is why PIC detection appeared not to work. AMLogic=i2c-1 and -/// BeagleBone=i2c-0 are from the wiki; buses vary across firmware, so each family -/// also lists the others as fallbacks. -pub fn bus_candidates(control_board: &str) -> Vec { - let cb = control_board.to_lowercase(); - if cb.contains("cvi") { - vec![3, 4, 1, 0] - } else if cb.contains("amlogic") || cb.contains("aml") { - vec![1, 3, 4, 0] - } else if cb.contains("beaglebone") || cb.contains("bb") { - vec![0, 1, 3, 4] - } else { - // Xilinx / unknown: try the common buses. - vec![1, 0, 3, 4] - } -} - -/// Classify an `i2cdump -y 0x48 b` dump: `Some(true)` = PIC (8-byte MCU -/// register file), `Some(false)` = noPIC (4-register LM75), `None` = couldn't -/// tell (address unresponsive, no periodicity, or unparseable). Conservative: -/// anything ambiguous is `None`, never a guess. -pub fn classify_i2cdump(stdout: &str) -> Option { - let bytes = parse_dump_offset0(stdout)?; - // An LM75's 4 registers repeat every 4 bytes; check that first because a - // period-4 sequence is trivially also period-8. - let period4 = (0..12).all(|i| bytes[i] == bytes[i + 4]); - if period4 { - return Some(false); // LM75 -> noPIC - } - let period8 = (0..8).all(|i| bytes[i] == bytes[i + 8]); - if period8 { - return Some(true); // 8-byte MCU register file -> PIC - } - None -} - -/// Parse the 16 bytes of the `00:` row of an `i2cdump ... b` output. Returns -/// `None` if the row is missing or any cell is unreadable ("XX"). -fn parse_dump_offset0(stdout: &str) -> Option<[u8; 16]> { - let line = stdout.lines().find_map(|l| { - let l = l.trim(); - l.strip_prefix("00:").map(str::trim_start) - })?; - // The row is "<16 hex/XX cells> "; take the first 16 cells. - let mut out = [0u8; 16]; - let mut n = 0; - for tok in line.split_whitespace() { - if n == 16 { - break; - } - if tok.len() != 2 { - break; // reached the ascii gutter - } - match u8::from_str_radix(tok, 16) { - Ok(b) => { - out[n] = b; - n += 1; - } - Err(_) => return None, // "XX" = no response -> indeterminate - } - } - (n == 16).then_some(out) -} - -/// Build the ssh argv for one `i2cdump` on `bus`. Uses `sshpass -p ` when -/// a password is set, else relies on key auth (BatchMode). -fn ssh_command(ip: &str, bus: u8, creds: &SshCreds) -> Command { - let remote = format!("i2cdump -y {bus} 0x48 b"); - let target = format!("{}@{ip}", creds.user); - let ssh_opts = [ - "-o", "StrictHostKeyChecking=no", - "-o", "UserKnownHostsFile=/dev/null", - "-o", "ConnectTimeout=6", - "-o", "NumberOfPasswordPrompts=1", - ]; - if creds.pass.is_empty() { - let mut c = Command::new("ssh"); - c.arg("-o").arg("BatchMode=yes"); - c.args(ssh_opts).arg(&target).arg(&remote); - c - } else { - // sshpass reads the password from the env var named after -e's default, - // but we use -p for simplicity; the password never reaches the argv of - // a child that logs it (sshpass scrubs its own argv). - let mut c = Command::new("sshpass"); - c.arg("-p").arg(&creds.pass).arg("ssh"); - c.args(ssh_opts).arg(&target).arg(&remote); - c - } -} - -/// Probe one miner's PIC state over SSH. Returns `Ok(Some(true/false))` on a -/// confident PIC/noPIC read, `Ok(None)` if reachable but indeterminate, or -/// `Err` on an SSH/connection/auth failure. -pub fn probe_pic(ip: &str, control_board: &str, creds: &SshCreds) -> Result, String> { - let mut last_err = String::from("no i2c bus responded"); - for bus in bus_candidates(control_board) { - match run_probe(ip, bus, creds) { - Ok(Some(v)) => return Ok(Some(v)), - Ok(None) => last_err = format!("i2c-0x48 on bus {bus} was indeterminate"), - Err(e) => return Err(e), // an auth/connection error won't improve on another bus - } - } - // Reachable but couldn't classify on any candidate bus. - let _ = last_err; - Ok(None) -} - -fn run_probe(ip: &str, bus: u8, creds: &SshCreds) -> Result, String> { - let out = wait_with_timeout(ssh_command(ip, bus, creds), Duration::from_secs(12))?; - if !out.status.success() { - let err = String::from_utf8_lossy(&out.stderr); - // A failed i2cdump on this bus (e.g. bus doesn't exist) is not fatal -- - // let the caller try the next bus. But an SSH/auth failure is fatal. - let e = err.trim().to_string(); - if e.to_lowercase().contains("permission denied") - || e.to_lowercase().contains("connection") - || e.to_lowercase().contains("timed out") - || e.to_lowercase().contains("no route") - || e.to_lowercase().contains("host key") - { - return Err(if e.is_empty() { "ssh failed".into() } else { e }); - } - return Ok(None); - } - Ok(classify_i2cdump(&String::from_utf8_lossy(&out.stdout))) -} - -/// Run a command with a wall-clock timeout (SSH can hang on a dead host). -fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result { - use std::io::Read; - cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); - let mut child = cmd.spawn().map_err(|e| format!("spawn ssh: {e}"))?; - let start = std::time::Instant::now(); - loop { - match child.try_wait().map_err(|e| e.to_string())? { - Some(status) => { - let mut stdout = Vec::new(); - let mut stderr = Vec::new(); - if let Some(mut o) = child.stdout.take() { - let _ = o.read_to_end(&mut stdout); - } - if let Some(mut e) = child.stderr.take() { - let _ = e.read_to_end(&mut stderr); - } - return Ok(std::process::Output { status, stdout, stderr }); - } - None => { - if start.elapsed() >= timeout { - let _ = child.kill(); - return Err("ssh timed out".into()); - } - std::thread::sleep(Duration::from_millis(100)); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn classify_pic_from_wiki_dump() { - // The wiki's PIC/MCU board dump: 8-byte register file that wraps. - let dump = "\ - 0 1 2 3 4 5 6 7 8 9 a b c d e f 0123456789abcdef -00: 17 00 4b 50 7f 00 00 00 17 00 4b 50 7f 00 00 00 ................ -10: 17 00 4b 50 7f 00 00 00 17 00 4b 50 7f 00 00 00 ................"; - assert_eq!(classify_i2cdump(dump), Some(true), "8-byte wrap -> PIC"); - } - - #[test] - fn classify_nopic_from_lm75() { - // An LM75 has 4 registers (temp/config/Thyst/Tos) that wrap every 4. - let dump = "\ - 0 1 2 3 4 5 6 7 8 9 a b c d e f 0123456789abcdef -00: 19 00 4b 50 19 00 4b 50 19 00 4b 50 19 00 4b 50 ................"; - assert_eq!(classify_i2cdump(dump), Some(false), "4-register LM75 -> noPIC"); - } - - #[test] - fn classify_indeterminate() { - // No response (XX) or no periodicity -> None (never a guess). - let xx = "00: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX"; - assert_eq!(classify_i2cdump(xx), None); - let noisy = "00: 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10"; - assert_eq!(classify_i2cdump(noisy), None); - assert_eq!(classify_i2cdump("no offset row here"), None); - } - - #[test] - fn bus_from_control_board() { - // Most-likely bus first, then fallbacks. CVITek's i2c-3 first is the live - // fix; AMLogic i2c-1 and BeagleBone i2c-0 keep their wiki-confirmed lead. - assert_eq!(bus_candidates("CVI (C88)"), vec![3, 4, 1, 0]); - assert_eq!(bus_candidates("CVITek"), vec![3, 4, 1, 0]); - assert_eq!(bus_candidates("AMLogic")[0], 1); - assert_eq!(bus_candidates("BeagleBone Black")[0], 0); - assert_eq!(bus_candidates("Xilinx")[0], 1); - assert_eq!(bus_candidates("")[0], 1); - } -} diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index e7e364db..7001b4d1 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -31,6 +31,9 @@ pub enum ScanMsg { pub const CONFIG_DIR: &str = ".config/alkane-toolkit"; pub const RANGES_FILE: &str = "scan-ranges.txt"; pub const AUTO_FILE: &str = "auto-rescan-secs.txt"; +pub const SCAN_TIMEOUT_FILE: &str = "scan-timeout-secs.txt"; +/// Default per-miner scan timeout (matches asic-rs' identification timeout). +pub const DEFAULT_SCAN_TIMEOUT_SECS: u64 = 10; pub const DEFAULT_RANGE: &str = "10.255.1.0/24"; /// Default seconds between automatic rescans. pub const DEFAULT_AUTO_SECS: u64 = 300; @@ -52,6 +55,26 @@ pub fn save_auto_secs(secs: u64) -> std::io::Result<()> { std::fs::write(p, secs.to_string()) } +/// Load the per-miner scan timeout in seconds (round 14 #2), clamped to at least +/// 1s. This is asic-rs' identification timeout: how long a responding miner is +/// given to identify + return data before the scan gives up on it. +pub fn load_scan_timeout() -> u64 { + std::fs::read_to_string(config_path(SCAN_TIMEOUT_FILE)) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .map(|s| s.max(1)) + .unwrap_or(DEFAULT_SCAN_TIMEOUT_SECS) +} + +/// Save the per-miner scan timeout in seconds. +pub fn save_scan_timeout(secs: u64) -> std::io::Result<()> { + let p = config_path(SCAN_TIMEOUT_FILE); + if let Some(dir) = p.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(p, secs.max(1).to_string()) +} + pub fn config_path(file: &str) -> PathBuf { let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); PathBuf::from(home).join(CONFIG_DIR).join(file) @@ -296,7 +319,7 @@ impl ScanHandle { } } -pub fn start_scan(lines: Vec) -> ScanHandle { +pub fn start_scan(lines: Vec, timeout_secs: u64) -> ScanHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); @@ -353,7 +376,8 @@ pub fn start_scan(lines: Vec) -> ScanHandle { } }; rt.block_on(async move { - let mut factory = crate::credentials::configured_factory(); + let mut factory = crate::credentials::configured_factory() + .with_identification_timeout_secs(timeout_secs.max(1)); for (ip, prefix) in &cidrs { factory = match factory.with_subnet(&format!("{ip}/{prefix}")) { Ok(f) => f, @@ -562,6 +586,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { power_limit, tuning: miner.supports_set_tuning_percent(), firmware_flash: miner.supports_upgrade_firmware(), + pools: miner.supports_pools_config(), }; // PIC vs noPIC is not reported over the network by asic-rs; best-effort // heuristic from the model string, else unknown (true detection needs an @@ -569,16 +594,12 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { let pic_present = if model.to_lowercase().contains("nopic") { Some(false) } else { None }; // Access: locked/view-only when the miner exposes no writable control at // all, otherwise unlocked. Inferred from asic-rs capabilities (there is no - // direct lock-state field). WhatsMiner is the exception: it is controllable - // over its :4028 token API regardless of which commands the matched asic-rs - // backend implements, so this heuristic falsely marks older units "locked". - // Leave it unknown and let the real access probe (the :4028 token check) - // decide (round 12 #8b). - let write_locked = if brand.eq_ignore_ascii_case("whatsminer") { - None - } else { - Some(!caps.any_control()) - }; + // direct lock-state field). This now covers WhatsMiner too: since round 12 + // #8b gave the V1/V2/V3 backends their control commands, a WhatsMiner reports + // control caps and reads as unlocked here instead of a blank cell (round 14 + // #6). The right-click access check (the :4028 token handshake) still refines + // this to "locked" for a unit whose API is in read-only mode. + let write_locked = Some(!caps.any_control()); // Per-hashboard health for the Boards status dots (round 11 #10): green = // present & hashing, red = present but idle/faulty, grey = expected but not // detected. Boards keep asic-rs's reported order (board 1 first); any boards @@ -698,6 +719,20 @@ impl ConfigAction { ConfigAction::TuningPercent(p) => format!("tuning {p}%"), } } + + /// Short present-tense label shown in a miner's Health cell while the action + /// runs (round 14 #4). + pub fn progress_label(&self) -> String { + match self { + ConfigAction::FaultLight(true) => "light on…".into(), + ConfigAction::FaultLight(false) => "light off…".into(), + ConfigAction::Restart => "restarting…".into(), + ConfigAction::Pause => "pausing…".into(), + ConfigAction::Resume => "resuming…".into(), + ConfigAction::PowerLimit(_) => "setting power…".into(), + ConfigAction::TuningPercent(_) => "tuning…".into(), + } + } } /// Progress/results from a running config action. @@ -807,6 +842,106 @@ pub fn start_config_action(ips: Vec, action: ConfigAction) -> ActionHand ActionHandle { rx, cancel } } +/// One miner's pool config to write (round 14 #7). The worker `username` has +/// already been expanded from the per-firmware worker template in the UI (which +/// holds the scanned MinerRow), so this carries a fully-resolved endpoint. +pub struct PoolTarget { + pub ip: String, + pub url: String, + pub username: String, + pub password: String, +} + +/// Apply a single "default" pool group to each target miner on a background +/// thread (round 14 #7). Reuses the ActionMsg/ActionHandle plumbing so the +/// existing drain_action + status handling covers it. Miners whose backend does +/// not support pool configuration report "not supported" rather than failing the +/// batch. +pub fn start_pools_action(targets: Vec) -> ActionHandle { + use asic_rs::core::config::pools::{PoolConfig, PoolGroupConfig}; + use asic_rs::core::data::pool::PoolURL; + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + let _ = tx.send(ActionMsg::Started { total }); + + if fake_scan_enabled() { + let err_tx = tx.clone(); + let res = std::thread::Builder::new().name("fake-pools".into()).spawn(move || { + for t in targets { + let _ = tx.send(ActionMsg::Result { + ip: t.ip, + ok: true, + detail: format!("simulated ({})", t.username), + }); + } + let _ = tx.send(ActionMsg::Done { ok: total, total }); + }); + if res.is_err() { + let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); + } + return ActionHandle { rx, cancel }; + } + + let thread_cancel = cancel.clone(); + let err_tx = tx.clone(); + let res = std::thread::Builder::new().name("pools-action".into()).spawn(move || { + let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { + Ok(rt) => rt, + Err(_) => { + let _ = tx.send(ActionMsg::Done { ok: 0, total }); + return; + } + }; + rt.block_on(async move { + let factory = crate::credentials::configured_factory(); + let mut ok = 0usize; + for t in targets { + if thread_cancel.load(Ordering::Relaxed) { + break; + } + let (success, detail) = match t.ip.parse::() { + Err(_) => (false, "bad IP".to_string()), + Ok(ip) => match factory.scan_miner(ip).await { + Ok(Some(miner)) if !miner.supports_pools_config() => { + (false, "not supported".to_string()) + } + Ok(Some(miner)) => { + let group = PoolGroupConfig { + name: "default".to_string(), + quota: 1, + pools: vec![PoolConfig { + url: PoolURL::from(t.url.clone()), + username: t.username.clone(), + password: t.password.clone(), + }], + }; + match miner.set_pools_config(vec![group]).await { + Ok(true) => (true, "ok".to_string()), + Ok(false) => (false, "refused".to_string()), + Err(e) => (false, format!("{e}")), + } + } + Ok(None) => (false, "no miner at IP".to_string()), + Err(e) => (false, format!("{e}")), + }, + }; + if success { + ok += 1; + } + if tx.send(ActionMsg::Result { ip: t.ip, ok: success, detail }).is_err() { + return; + } + } + let _ = tx.send(ActionMsg::Done { ok, total }); + }); + }); + if res.is_err() { + let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); + } + ActionHandle { rx, cancel } +} + /// Progress/results from a background refresh of a specific, already-known /// set of miners (re-poll on a timer or after a right-click "Refresh" action, /// as opposed to `start_scan`'s full subnet sweep). @@ -1013,89 +1148,6 @@ pub fn start_firmware_flash_action(ips: Vec, image: FirmwareImage) -> Ac ActionHandle { rx, cancel } } -/// Progress/results from a background SSH PIC probe of specific miners. -pub enum PicProbeMsg { - Started { total: usize }, - /// One miner's PIC result: `pic` = Some(true/false)/None (indeterminate), - /// or `error` set on an SSH/connection failure. - Result { ip: String, pic: Option, error: Option }, - Done { total: usize }, -} - -/// A running PIC probe; `stop` cancels the remaining miners. -pub struct PicProbeHandle { - pub rx: Receiver, - cancel: Arc, -} - -impl PicProbeHandle { - pub fn stop(&self) { - self.cancel.store(true, Ordering::Relaxed); - } -} - -/// Probe the PIC state of `targets` (ip + control-board string) over SSH on a -/// background thread, one miner at a time (each is a slow SSH round trip). In -/// fake-scan mode it reports simulated results without touching the network. -pub fn start_pic_probe( - targets: Vec<(String, String)>, - creds: crate::pic_probe::SshCreds, -) -> PicProbeHandle { - let (tx, rx) = channel(); - let cancel = Arc::new(AtomicBool::new(false)); - let total = targets.len(); - let _ = tx.send(PicProbeMsg::Started { total }); - - if fake_scan_enabled() { - let err_tx = tx.clone(); - let thread_cancel = cancel.clone(); - let res = std::thread::Builder::new().name("fake-pic-probe".into()).spawn(move || { - for (ip, cb) in targets { - if thread_cancel.load(Ordering::Relaxed) { - break; - } - // Deterministic demo: Antminer S21 (CVITek) noPIC, other - // Antminers PIC, WhatsMiner indeterminate. - let pic = if cb.to_lowercase().contains("cvitek") { - Some(false) - } else if !cb.is_empty() { - Some(true) - } else { - None - }; - let _ = tx.send(PicProbeMsg::Result { ip, pic, error: None }); - } - let _ = tx.send(PicProbeMsg::Done { total }); - }); - if res.is_err() { - let _ = err_tx.send(PicProbeMsg::Done { total }); - } - return PicProbeHandle { rx, cancel }; - } - - let thread_cancel = cancel.clone(); - let err_tx = tx.clone(); - let res = std::thread::Builder::new().name("pic-probe".into()).spawn(move || { - for (ip, cb) in targets { - if thread_cancel.load(Ordering::Relaxed) { - break; - } - let (pic, error) = match crate::pic_probe::probe_pic(&ip, &cb, &creds) { - Ok(v) => (v, None), - Err(e) => (None, Some(e)), - }; - if tx.send(PicProbeMsg::Result { ip, pic, error }).is_err() { - return; // UI gone - } - } - let _ = tx.send(PicProbeMsg::Done { total }); - }); - if res.is_err() { - let _ = err_tx.send(PicProbeMsg::Done { total }); - } - PicProbeHandle { rx, cancel } -} - /// Progress/results from a background access (lock-state) probe. pub enum AccessProbeMsg { Started { total: usize }, @@ -1451,7 +1503,7 @@ mod tests { // start_scan (fake): streams exactly the bench-fleet fixtures, one Row // per fixture, and no fabricated rows for empty addresses. { - let h = start_scan(vec!["10.255.1.0/30".into()]); + let h = start_scan(vec!["10.255.1.0/30".into()], DEFAULT_SCAN_TIMEOUT_SECS); let mut rows = Vec::new(); let mut total = 0usize; loop { diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 337f2dae..f494cc0d 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -58,7 +58,6 @@ const ID_CTX_RESUME: i32 = 726; const ID_CTX_TUNING: i32 = 727; const ID_CTX_POWER: i32 = 728; const ID_CTX_RESTART: i32 = 729; -const ID_CTX_PIC_PROBE: i32 = 730; const ID_CTX_ACCESS_PROBE: i32 = 731; // View a miner's log fetched over its firmware API (round 12 #12). const ID_CTX_VIEW_LOG: i32 = 734; @@ -67,9 +66,10 @@ const ID_LOGVIEW_CLOSE: i32 = 785; const ID_CTX_RESTORE_STOCK: i32 = 735; const ID_RESTORE_OK: i32 = 786; const ID_RESTORE_CANCEL: i32 = 787; -// SSH PIC-probe credentials dialog. -const ID_PICSSH_OK: i32 = 780; -const ID_PICSSH_CANCEL: i32 = 781; +// Configure pools (round 14 #7): pool address + account + worker-name template. +const ID_CTX_POOLS: i32 = 736; +const ID_POOLS_OK: i32 = 788; +const ID_POOLS_CANCEL: i32 = 789; // Value-prompt dialog for power-limit / tuning-percent actions. const ID_ACTION_OK: i32 = 740; const ID_ACTION_CANCEL: i32 = 741; @@ -585,6 +585,8 @@ pub struct App { // scan loop (play/pause/stop + auto-rescan) playing: bool, auto_secs: u64, + // Per-miner scan timeout in seconds (round 14 #2). + scan_timeout_secs: u64, countdown: u64, // selection (replaces the old checkbox column), tracked by IP so it // survives table refreshes during a scan. @@ -621,6 +623,10 @@ pub struct App { // IPs the current config action targets, re-probed after it completes so the // table reflects the change (e.g. the identify light toggling). action_targets: Vec, + // Per-miner in-flight operation label (round 14 #4): while a miner has an + // operation running (refresh, config action, light, firmware, restore, access + // check), its Health cell shows this text instead of the component icons. + op_status: std::collections::HashMap, // A confirmation dialog for disruptive actions, plus its pending target. confirm_dialog: Widget, pending_confirm: Option<(Vec, scan::ConfigAction)>, @@ -649,9 +655,6 @@ pub struct App { fwcreds_rows: Vec<(String, Widget, Widget)>, // Background access (lock-state) probe. access_probe: Option, - // Background SSH PIC probe + its credentials dialog. - pic_probe: Option, - pending_pic_targets: Vec<(String, String)>, // The API log viewer dialog (round 12 #12). logview_dialog: Widget, // Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog. @@ -659,9 +662,11 @@ pub struct App { restore_dialog: Widget, restore_input: Widget, pending_restore: Vec, - picssh_dialog: Widget, - picssh_user_input: Widget, - picssh_pass_input: Widget, + // Configure-pools dialog (round 14 #7). + pools_dialog: Widget, + pools_url_input: Widget, + pools_account_input: Widget, + pools_worker_input: Widget, // Saved view presets + the Presets dialog widgets. presets: Vec, presets_dialog: Widget, @@ -673,6 +678,7 @@ pub struct App { ranges_dialog: Widget, ranges_edit: Widget, ranges_auto: Widget, + ranges_timeout: Widget, columns_dialog: Widget, columns_list: Widget, /// The columns-dialog "hide empty columns" checkbox, read at Apply. @@ -867,6 +873,8 @@ pub fn build(frame: Widget) -> App { // errors (red) and warnings (amber) so they don't overwrite the scan state. wx_rs::create_status_bar(); wx_rs::status_indicator_init(frame); + // Table-zoom slider in the bottom-right of the status bar (round 14 #3). + wx_rs::status_zoom_init(frame); wx_rs::set_status_text("starting scan..."); // Repaint custom-coloured widgets when the OS switches light/dark. @@ -890,13 +898,14 @@ pub fn build(frame: Widget) -> App { table: None, table_parent, root_sizer: root, - scan: Some(scan::start_scan(ranges.clone())), + scan: Some(scan::start_scan(ranges.clone(), scan::load_scan_timeout())), scanning: true, scan_total: 0, target_ips: HashSet::new(), refresh: None, playing: true, auto_secs: scan::load_auto_secs(), + scan_timeout_secs: scan::load_scan_timeout(), countdown: 0, selected_ips: HashSet::new(), pal, @@ -915,6 +924,7 @@ pub fn build(frame: Widget) -> App { action_total: 0, action_done: 0, action_targets: Vec::new(), + op_status: std::collections::HashMap::new(), confirm_dialog: frame, pending_confirm: None, flash_confirm_dialog: frame, @@ -927,16 +937,15 @@ pub fn build(frame: Widget) -> App { fwcreds_dialog: frame, fwcreds_rows: Vec::new(), access_probe: None, - pic_probe: None, - pending_pic_targets: Vec::new(), logview_dialog: frame, restore: None, restore_dialog: frame, restore_input: frame, pending_restore: Vec::new(), - picssh_dialog: frame, - picssh_user_input: frame, - picssh_pass_input: frame, + pools_dialog: frame, + pools_url_input: frame, + pools_account_input: frame, + pools_worker_input: frame, presets: crate::presets::load_presets(), presets_dialog: frame, presets_choice: frame, @@ -946,6 +955,7 @@ pub fn build(frame: Widget) -> App { ranges_dialog: frame, ranges_edit: frame, ranges_auto: frame, + ranges_timeout: frame, columns_dialog: frame, columns_list: frame, columns_hide_empty_cb: frame, @@ -1069,6 +1079,9 @@ impl App { self.root_sizer.add(t, 1, sf::EXPAND | sf::BORDER_ALL, 4); self.table = Some(t); self.table_parent.layout(); + // Re-apply the table zoom so a non-100% zoom survives this rebuild + // (round 14 #3); the fresh columns come back at their 100% widths. + wx_rs::table_zoom_reapply(); self.fill_rows(); } @@ -1108,7 +1121,12 @@ impl App { encode_combined_cell(&self.pal, actual, expected, "/", ratio) } // Health column: one coloured icon per component (round 13 #3). - Column::Health => encode_component_health(&self.pal, r), + // While an operation runs on this miner, its Health cell shows + // the progress text instead of the component icons (round 14 #4). + Column::Health => match self.op_status.get(&r.ip) { + Some(op) => encode_segments(&[(Some(self.pal.amber), op.clone())]), + None => encode_component_health(&self.pal, r), + }, // Boards column: per-hashboard health dots (round 11 #10). Column::Hashboards => encode_board_dots(&self.pal, &r.board_status), Column::TotalChips => { @@ -1337,9 +1355,6 @@ impl App { // Refresh is always offered for a non-empty selection, independent of // the capability intersection below. menu.menu_append(ID_CTX_REFRESH, "Refresh"); - // Real PIC-vs-noPIC detection via an on-board SSH i2c probe (asic-rs - // cannot report it over the network); offered for any selection. - menu.menu_append(ID_CTX_PIC_PROBE, "Detect PIC (SSH)..."); // Real access/lock-state check (credentialed digest GET; uses the saved // scan credentials). menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)"); @@ -1377,6 +1392,9 @@ impl App { if caps.restart { menu.menu_append(ID_CTX_RESTART, &format!("Restart{sfx}")); } + if caps.pools { + menu.menu_append(ID_CTX_POOLS, &format!("Configure pools...{sfx}")); + } } // Firmware flash is offered when AT LEAST ONE selected miner supports // it (not the full intersection) -- flashing a mixed batch simply @@ -1409,6 +1427,141 @@ impl App { self.rows.iter().filter(|r| self.selected_ips.contains(&r.ip)).collect() } + /// Mark each of `ips` as having an in-flight operation labelled `label` + /// (round 14 #4), so its Health cell shows the progress text instead of the + /// component icons, and repaint those cells. + fn set_op_status(&mut self, ips: &[String], label: &str) { + for ip in ips { + self.op_status.insert(ip.clone(), label.to_string()); + } + self.fill_rows(); + } + + /// Clear one miner's in-flight operation label. Repaint is left to the caller + /// (usually a single fill_rows after draining a batch of results). + fn clear_op_status(&mut self, ip: &str) { + self.op_status.remove(ip); + } + + /// Build (but do not show) the Configure-pools dialog (round 14 #7): pool + /// address + account (both required) + an optional worker-name template that + /// is expanded per miner. Returns None when nothing is selected or a flash + /// holds the exclusive lock. + fn build_pools_dialog(&mut self) -> Option { + if self.flashing { + wx_rs::set_status_text("firmware flash in progress -- wait for it to finish"); + return None; + } + if self.selected_rows().is_empty() { + return None; + } + let n = self.selected_ip_list().len(); + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, "Configure pools"); + let root = Widget::box_sizer(true); + root.add( + Widget::static_text( + dlg, + &format!("Set the primary pool on {n} selected miner(s). Address and account are required."), + ), + 0, + sf::BORDER_ALL, + 8, + ); + let mut field = |label: &str, hint: &str| -> Widget { + let row = Widget::box_sizer(false); + let l = Widget::static_text(dlg, label); + l.set_min_size(90, -1); + row.add(l, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + let input = Widget::text_ctrl(dlg, false); + input.set_min_size(320, -1); + row.add(input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + root.add_sizer(row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4); + let _ = hint; + input + }; + let url_input = field("Address:", ""); + url_input.set_value("stratum+tcp://"); + let account_input = field("Account:", ""); + let worker_input = field("Worker:", ""); + root.add( + Widget::static_text( + dlg, + "Worker name may use per-miner placeholders (case-insensitive):\n {ip1}..{ip4} IP octets {serial} {mac} (no ':') {nameplate-hr} rated TH\n {brand} {model} {submodel} {cpu} {cb} control board {firmware} {hostname}\nThe pool user sent is \"account.worker\" (or just the account when Worker is empty).", + ), + 0, + sf::BORDER_ALL, + 8, + ); + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add(Widget::button(dlg, "Apply", ID_POOLS_OK), 0, sf::BORDER_ALL, 6); + btns.add(Widget::button(dlg, "Cancel", ID_POOLS_CANCEL), 0, sf::BORDER_ALL, 6); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(520, 300); + dlg.fit(dlg); + self.pools_dialog = dlg; + self.pools_url_input = url_input; + self.pools_account_input = account_input; + self.pools_worker_input = worker_input; + Some(dlg) + } + + /// Validate the pool inputs, expand the worker template per selected miner, + /// and start the background pool-config action (round 14 #7). + fn apply_pools(&mut self) { + let url = self.pools_url_input.get_value().trim().to_string(); + let account = self.pools_account_input.get_value().trim().to_string(); + let worker_tpl = self.pools_worker_input.get_value(); + if url.is_empty() || url == "stratum+tcp://" { + wx_rs::set_status_text("enter a pool address"); + return; + } + if account.is_empty() { + wx_rs::set_status_text("enter a pool account"); + return; + } + if self.flashing { + wx_rs::set_status_text("firmware flash in progress -- wait for it to finish"); + return; + } + let targets: Vec = self + .selected_rows() + .iter() + .map(|r| { + let worker = r.expand_worker_template(&worker_tpl); + let worker = worker.trim(); + let username = if worker.is_empty() { + account.clone() + } else { + format!("{account}.{worker}") + }; + scan::PoolTarget { + ip: r.ip.clone(), + url: url.clone(), + username, + // Most pools ignore the worker password; "x" is the convention. + password: "x".to_string(), + } + }) + .collect(); + if targets.is_empty() { + self.pools_dialog.close(0); + return; + } + let ips: Vec = targets.iter().map(|t| t.ip.clone()).collect(); + let n = ips.len(); + if let Some(old) = self.action.take() { + old.stop(); + } + self.pools_dialog.close(1); + self.action_targets = ips.clone(); + self.set_op_status(&ips, "setting pools…"); + self.action = Some(scan::start_pools_action(targets)); + wx_rs::set_status_text(&format!("configuring pools on {n} miner(s)...")); + } + /// Start a config action against `ips` on a background thread, cancelling any /// action already in flight so two never run at once. fn start_action(&mut self, ips: Vec, action: scan::ConfigAction) { @@ -1424,6 +1577,7 @@ impl App { } let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len()); self.action_targets = ips.clone(); + self.set_op_status(&ips, &action.progress_label()); self.action = Some(scan::start_config_action(ips, action)); // Clear any stale error/warning from a previous operation; the new // outcome repopulates the indicator when this action finishes. @@ -1446,6 +1600,8 @@ impl App { old.stop(); } let msg = format!("refreshing {} miner(s)...", ips.len()); + // Show "refreshing…" in each miner's Health cell while it re-probes (#4). + self.set_op_status(&ips, "refreshing…"); self.refresh = Some(scan::start_refresh(ips)); wx_rs::set_status_text(&msg); } @@ -1568,7 +1724,9 @@ impl App { let vnish_pass = if vnish_pass.is_empty() { "admin".to_string() } else { vnish_pass }; let (ssh_user, ssh_pass) = credentials::load_ssh_credentials().unwrap_or_default(); let n = targets.len(); + let ips: Vec = targets.iter().map(|t| t.ip.clone()).collect(); self.restore_dialog.close(1); + self.set_op_status(&ips, "restoring…"); self.restore = Some(restore::start_restore(targets, vnish_pass, ssh_user, ssh_pass)); wx_rs::set_status_text(&format!("restoring {n} miner(s) to stock...")); } @@ -1579,12 +1737,14 @@ impl App { let mut done = false; let mut oks = 0usize; let mut fails: Vec = Vec::new(); + let mut op_clear: Vec = Vec::new(); while let Ok(msg) = h.rx.try_recv() { match msg { restore::RestoreMsg::Started { total } => { wx_rs::set_status_text(&format!("restoring {total} miner(s) to stock...")); } restore::RestoreMsg::Result { ip, ok, detail } => { + op_clear.push(ip.clone()); if ok { oks += 1; } else { @@ -1594,8 +1754,17 @@ impl App { restore::RestoreMsg::Done { .. } => done = true, } } + for ip in &op_clear { + self.op_status.remove(ip); + } if done { self.restore = None; + self.op_status.retain(|_, v| v != "restoring…"); + } + if !op_clear.is_empty() || done { + self.fill_rows(); + } + if done { if fails.is_empty() { wx_rs::set_status_text(&format!("restore-to-stock: {oks} started; miners reboot to stock")); } else { @@ -1609,96 +1778,6 @@ impl App { } } - /// Build the SSH PIC-probe dialog: captures the selected miners, collects - /// SSH credentials (prefilled from the saved SSH login), and on OK runs the - /// on-board i2c probe. Returns None (no dialog) if nothing is selected or a - /// flash holds the exclusive lock. - fn build_pic_probe_dialog(&mut self) -> Option { - if self.flashing { - wx_rs::set_status_text("firmware flash in progress -- wait for it to finish"); - return None; - } - if self.pic_probe.is_some() { - wx_rs::set_status_text("a PIC probe is already running"); - return None; - } - let targets: Vec<(String, String)> = self - .selected_rows() - .iter() - .map(|r| (r.ip.clone(), r.control_board.clone())) - .collect(); - if targets.is_empty() { - return None; - } - self.pending_pic_targets = targets; - let (saved_user, _) = credentials::load_ssh_credentials().unwrap_or_default(); - let frame = Widget::main_frame(); - let dlg = Widget::dialog(frame, "Detect PIC via SSH"); - let root = Widget::box_sizer(true); - root.add( - Widget::static_text( - dlg, - &format!( - "Probe {} miner(s) over SSH (runs i2cdump on the control board). SSH login for the miner (root, etc.):", - self.pending_pic_targets.len() - ), - ), - 0, - sf::BORDER_ALL, - 8, - ); - let user_row = Widget::box_sizer(false); - user_row.add(Widget::static_text(dlg, "SSH user:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); - let user_input = Widget::text_ctrl(dlg, false); - user_input.set_value(if saved_user.is_empty() { "root" } else { &saved_user }); - user_input.set_min_size(180, -1); - user_row.add(user_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); - root.add_sizer(user_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); - let pass_row = Widget::box_sizer(false); - pass_row.add(Widget::static_text(dlg, "SSH password:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); - let pass_input = Widget::text_ctrl(dlg, false); - pass_input.set_min_size(180, -1); - pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); - root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); - root.add( - Widget::static_text(dlg, "(Leave the password blank to use SSH key auth.)"), - 0, - sf::BORDER_ALL, - 6, - ); - let btns = Widget::box_sizer(false); - btns.add_stretch(1); - btns.add(Widget::button(dlg, "Probe", ID_PICSSH_OK), 0, sf::BORDER_ALL, 6); - btns.add(Widget::button(dlg, "Cancel", ID_PICSSH_CANCEL), 0, sf::BORDER_ALL, 6); - root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); - root.set_sizer_on(dlg); - dlg.set_min_size(420, 210); - dlg.fit(dlg); - self.picssh_dialog = dlg; - self.picssh_user_input = user_input; - self.picssh_pass_input = pass_input; - Some(dlg) - } - - /// Start the PIC probe with the SSH credentials just entered. - fn apply_pic_probe(&mut self) { - let user = self.picssh_user_input.get_value().trim().to_string(); - if user.is_empty() { - wx_rs::set_status_text("enter an SSH user"); - return; - } - let pass = self.picssh_pass_input.get_value(); - let _ = credentials::save_ssh_credentials(&user, &pass); - self.picssh_dialog.close(1); - let targets = std::mem::take(&mut self.pending_pic_targets); - let n = targets.len(); - self.pic_probe = Some(scan::start_pic_probe( - targets, - crate::pic_probe::SshCreds { user, pass }, - )); - wx_rs::set_status_text(&format!("probing PIC on {n} miner(s) via SSH...")); - } - /// Start the access (lock-state) probe on the selected miners, using the /// saved scan (web) credentials (defaulting to root/root if none are set). fn start_access_probe(&mut self) { @@ -1723,6 +1802,8 @@ impl App { } let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into())); let n = targets.len(); + let ips: Vec = targets.iter().map(|(ip, _)| ip.clone()).collect(); + self.set_op_status(&ips, "checking…"); self.access_probe = Some(scan::start_access_probe(targets, creds)); wx_rs::set_status_text(&format!("checking access on {n} miner(s)...")); } @@ -1734,12 +1815,14 @@ impl App { let mut status: Option = None; let mut done = false; let mut changed = false; + let mut op_clear: Vec = Vec::new(); loop { match h.rx.try_recv() { Ok(scan::AccessProbeMsg::Started { total }) => { status = Some(format!("access check: 0/{total}...")); } Ok(scan::AccessProbeMsg::Result { ip, locked, error }) => { + op_clear.push(ip.clone()); if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) { if error.is_none() { r.write_locked = locked; @@ -1765,7 +1848,13 @@ impl App { } } } - if changed { + for ip in &op_clear { + self.op_status.remove(ip); + } + if done { + self.op_status.retain(|_, v| v != "checking…"); + } + if changed || !op_clear.is_empty() || done { self.fill_rows(); } if done { @@ -1778,57 +1867,6 @@ impl App { } } - /// Drain the running PIC probe: update each miner's pic_present as its result - /// arrives, and refresh the table + status when done. - fn drain_pic_probe(&mut self) { - let Some(h) = &self.pic_probe else { return }; - let mut status: Option = None; - let mut done = false; - let mut changed = false; - loop { - match h.rx.try_recv() { - Ok(scan::PicProbeMsg::Started { total }) => { - status = Some(format!("PIC probe: 0/{total}...")); - } - Ok(scan::PicProbeMsg::Result { ip, pic, error }) => { - if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) { - if error.is_none() { - r.pic_present = pic; - changed = true; - } - } - status = Some(match (&pic, &error) { - (_, Some(e)) => format!("PIC probe {ip}: {e}"), - (Some(true), _) => format!("PIC probe {ip}: PIC"), - (Some(false), _) => format!("PIC probe {ip}: noPIC"), - (None, _) => format!("PIC probe {ip}: indeterminate"), - }); - } - Ok(scan::PicProbeMsg::Done { total }) => { - status = Some(format!("PIC probe done ({total} miner(s))")); - done = true; - break; - } - Err(std::sync::mpsc::TryRecvError::Empty) => break, - Err(std::sync::mpsc::TryRecvError::Disconnected) => { - done = true; - break; - } - } - } - if changed { - self.fill_rows(); - } - if done { - self.pic_probe = None; - self.action_result = status.clone(); - self.action_result_ticks = ACTION_RESULT_TICKS; - } - if let Some(s) = status { - wx_rs::set_status_text(&s); - } - } - /// A menu item was chosen. Direct actions start immediately; the value-input /// actions (power limit / tuning %) return a prompt dialog to show modally. fn on_menu_item(&mut self, id: i32) -> Option { @@ -1841,10 +1879,10 @@ impl App { } } ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()), - ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(), ID_CTX_ACCESS_PROBE => self.start_access_probe(), ID_CTX_VIEW_LOG => return self.build_log_view_dialog(), ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(), + ID_CTX_POOLS => return self.build_pools_dialog(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if // any scan / refresh / action is running (re-checked at confirm). @@ -2061,6 +2099,8 @@ impl App { } let msg = format!("flashing firmware to {} miner(s)...", ips.len()); self.flashing = true; + self.action_targets = ips.clone(); + self.set_op_status(&ips, "flashing…"); self.action = Some(scan::start_firmware_flash_action(ips, image)); wx_rs::set_status_text(&msg); } @@ -2288,10 +2328,17 @@ impl App { self.action_result_ticks = ACTION_RESULT_TICKS; // Re-probe the miners the action touched so the table reflects the // change (e.g. the identify light). Skip after a flash (the miner is - // rebooting and won't answer a refresh yet). + // rebooting and won't answer a refresh yet). The follow-up refresh + // overwrites each miner's Health op-status ("restarting…" -> + // "refreshing…"); with no refresh we clear it back to icons (#4). let targets = std::mem::take(&mut self.action_targets); if !was_flash && !targets.is_empty() { self.start_refresh(targets); + } else { + for ip in &targets { + self.op_status.remove(ip); + } + self.fill_rows(); } } // Apply the captured indicator now the `h` borrow is gone. @@ -2315,16 +2362,21 @@ impl App { let mut status: Option = None; let mut finished = false; let mut changed = false; + // IPs whose per-miner refresh completed this tick: clear their Health + // op-status back to icons (round 14 #4). + let mut op_clear: Vec = Vec::new(); loop { match h.rx.try_recv() { Ok(scan::RefreshMsg::Started { total }) => { status = Some(format!("refreshing 0/{total} miner(s)...")); } Ok(scan::RefreshMsg::Row(row)) => { + op_clear.push(row.ip.clone()); row.upsert_into(&mut self.rows); changed = true; } Ok(scan::RefreshMsg::Failed { ip, detail }) => { + op_clear.push(ip.clone()); status = Some(format!("refresh failed ({ip}: {detail})")); } Ok(scan::RefreshMsg::Done { ok, total }) => { @@ -2344,13 +2396,18 @@ impl App { } } } + for ip in &op_clear { + self.op_status.remove(ip); + } if finished { self.refresh = None; + // Any stragglers still marked "refreshing…" revert to icons. + self.op_status.retain(|_, v| v != "refreshing…"); } if let Some(s) = status { wx_rs::set_status_text(&s); } - if changed { + if changed || !op_clear.is_empty() || finished { self.fill_rows(); } } @@ -2440,13 +2497,12 @@ impl App { self.drain_scan(); self.drain_action(); self.drain_refresh(); - self.drain_pic_probe(); self.drain_access_probe(); self.drain_restore(); if self.scanning { return; // status already shows scan progress } - if self.pic_probe.is_some() || self.access_probe.is_some() { + if self.access_probe.is_some() { return; // a probe is in flight; keep its status } if self.action.is_some() { @@ -2496,7 +2552,7 @@ impl App { if let Some(old) = self.scan.take() { old.stop(); } - self.scan = Some(scan::start_scan(lines)); + self.scan = Some(scan::start_scan(lines, self.scan_timeout_secs)); self.scanning = true; self.countdown = 0; } @@ -2721,14 +2777,24 @@ impl App { let edit = Widget::text_ctrl(dlg, true); edit.set_value(&scan::load_ranges().join("\n")); root.add(edit, 1, sf::EXPAND | sf::BORDER_ALL, 6); - // Auto-rescan interval (seconds; 0 = off). + // Auto-rescan interval (seconds; 0 = off) and per-miner scan timeout. let auto_row = Widget::box_sizer(false); let auto_lbl = Widget::static_text(dlg, "Rescan (s):"); auto_row.add(auto_lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); let auto_edit = Widget::text_ctrl(dlg, false); auto_edit.set_value(&self.auto_secs.to_string()); + auto_edit.set_min_size(60, -1); auto_row.add(auto_edit, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); - root.add_sizer(auto_row, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); + // Per-miner scan timeout (round 14 #2): how long a responding miner is + // given to identify + return data before the scan gives up on it. + auto_row.add_stretch(1); + let to_lbl = Widget::static_text(dlg, "Timeout (s):"); + auto_row.add(to_lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + let to_edit = Widget::text_ctrl(dlg, false); + to_edit.set_value(&self.scan_timeout_secs.to_string()); + to_edit.set_min_size(60, -1); + auto_row.add(to_edit, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + root.add_sizer(auto_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); let btns = Widget::box_sizer(false); let apply = Widget::button(dlg, "Apply", ID_RANGES_APPLY); btns.add(apply, 0, sf::BORDER_ALL, 6); @@ -2739,6 +2805,7 @@ impl App { self.ranges_dialog = dlg; self.ranges_edit = edit; self.ranges_auto = auto_edit; + self.ranges_timeout = to_edit; dlg } @@ -2764,6 +2831,11 @@ impl App { self.auto_secs = secs; let _ = scan::save_auto_secs(secs); } + // Save the per-miner scan timeout (round 14 #2), clamped to >= 1s. + if let Ok(secs) = self.ranges_timeout.get_value().trim().parse::() { + self.scan_timeout_secs = secs.max(1); + let _ = scan::save_scan_timeout(self.scan_timeout_secs); + } let _ = scan::save_ranges(&lines); self.begin_scan(lines); wx_rs::set_status_text("scanning..."); @@ -3340,11 +3412,6 @@ impl App { ID_COLS_ALPHA => self.apply_columns_sort(false), ID_COLS_CATEGORIES => self.apply_columns_sort(true), ID_PRESETS => return Some(self.build_presets_dialog()), - ID_PICSSH_OK => self.apply_pic_probe(), - ID_PICSSH_CANCEL => { - self.pending_pic_targets.clear(); - self.picssh_dialog.close(0); - } ID_PRESET_LOAD => self.apply_preset_load(), ID_PRESET_SAVE => self.apply_preset_save(), ID_PRESET_DELETE => self.apply_preset_delete(), @@ -3380,6 +3447,8 @@ impl App { self.pending_restore.clear(); self.restore_dialog.close(0); } + ID_POOLS_OK => self.apply_pools(), + ID_POOLS_CANCEL => self.pools_dialog.close(0), ID_KPI_HASHING => self.toggle_kpi_filter("hashing"), ID_KPI_SLOW => self.toggle_kpi_filter("slow"), ID_KPI_NOT => self.toggle_kpi_filter("not hashing"), diff --git a/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch b/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch index b12f55c1..4d86b90a 100644 --- a/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch +++ b/thirdparty/wx-rs/patches/0002-widget-bridge-rs.patch @@ -10,7 +10,7 @@ +pub use widgets::*; --- a/src/widgets.rs +++ b/src/widgets.rs -@@ -0,0 +1,826 @@ +@@ -0,0 +1,847 @@ +// 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). @@ -126,6 +126,9 @@ + pub fn wxbr_call_after(id: c_int); + pub fn wxbr_status_indicator_init(frame: *mut c_void); + pub fn wxbr_status_indicator_set(text: *const c_char, r: c_int, g: c_int, b: c_int); ++ pub fn wxbr_status_zoom_init(frame: *mut c_void); ++ pub fn wxbr_table_set_zoom(factor: f64); ++ pub fn wxbr_table_zoom_reapply(); + } +} + @@ -209,6 +212,24 @@ + unsafe { notsafe::wxbr_status_indicator_init(frame.0) } +} + ++/// Add the table-zoom slider + percent label to the frame's status bar (round 14 ++/// #3). Call after the table exists so the slider can find it. The slider scales ++/// the table entirely in C++; no further Rust calls are needed. ++pub fn status_zoom_init(frame: Widget) { ++ unsafe { notsafe::wxbr_status_zoom_init(frame.0) } ++} ++ ++/// Set the table zoom factor programmatically (1.0 = 100%); also moves the slider. ++pub fn table_set_zoom(factor: f64) { ++ unsafe { notsafe::wxbr_table_set_zoom(factor) } ++} ++ ++/// Re-apply the current zoom after the table's columns are rebuilt, so a non-100% ++/// zoom survives a column show/hide/reorder (round 14 #3). ++pub fn table_zoom_reapply() { ++ unsafe { notsafe::wxbr_table_zoom_reapply() } ++} ++ +/// Set the bottom-right status indicator's text and colour (an empty string +/// clears it). Used for scan/apply errors (red) and warnings (amber). +pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) { diff --git a/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch b/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch index c62c1126..2bc9b484 100644 --- a/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch +++ b/thirdparty/wx-rs/patches/0003-widget-bridge-cpp.patch @@ -1,6 +1,6 @@ --- a/cpp_src/widgets_bridge.cpp +++ b/cpp_src/widgets_bridge.cpp -@@ -0,0 +1,1737 @@ +@@ -0,0 +1,1886 @@ +// 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). @@ -178,6 +178,16 @@ +const wxUniChar SHAPE_CHIP = 0x10; // hashboard +const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies + ++// Table zoom factor (round 14 #3), 1.0 = 100%. A status-bar slider scales the ++// table font (native columns) and, through this factor, the custom-renderer ++// icon sizes so the whole table zooms together. ++double g_table_zoom = 1.0; ++static wxDataViewCtrl* g_zoom_table = nullptr; // the table the zoom scales ++static wxFont g_zoom_base_font; // its font at 100% (captured lazily) ++static wxVector g_zoom_base_w; // column widths at 100% (per column) ++static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider ++static wxStaticText* g_zoom_label = nullptr; // the "100%" readout next to it ++ +// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a +// wxTimer while any such dot is on screen; the treeview it repaints is tracked so +// the timer can invalidate exactly it. @@ -292,13 +302,28 @@ + // SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the + // segment colour, rasterise (cached), and draw centred in its slot. + if (const ShapeSvg* sv = LookupShapeSvg(shape)) { -+ int h = cell.height - 4; -+ if (h > 15) h = 15; ++ // Component-health icons render bigger (nearly the full row height) and pack ++ // tighter than a padlock/status icon, so a row of power/control/fan/board ++ // icons stays large and compact (round 14 #1). ++ bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN || ++ shape == SHAPE_FAN || shape == SHAPE_CHIP); ++ int h = cell.height - (health ? 1 : 4); ++ int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5); ++ if (cap < 8) cap = 8; ++ if (h > cap) h = cap; + if (h < 8) h = 8; + int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h; + if (w < 1) w = 1; + const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, w, h); + if (bmp.IsOk()) { ++ if (health) { ++ // Left-align and advance by less than the icon width so adjacent health ++ // icons sit close together (the Font Awesome glyphs carry inner margin, ++ // so a small bounding-box overlap does not visually collide). ++ dc->DrawBitmap(bmp, x, cy - h / 2, true); ++ int adv = w - 3; ++ return adv < 1 ? 1 : adv; ++ } + int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE; + dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true); + return slot; @@ -405,6 +430,12 @@ + if (!plain.IsOk()) { + plain = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT); + } ++ // Draw segment text in the control's current font so it scales with the ++ // table zoom exactly like the native columns (round 14 #3); the DC otherwise ++ // keeps a default font that ignores SetFont on the control. ++ if (g_zoom_table && g_zoom_table->GetFont().IsOk()) { ++ dc->SetFont(g_zoom_table->GetFont()); ++ } + wxCoord x = cell.x; + for (const ColorSegment& seg : ParseColorSegments(m_value)) { + // Shape segments (status dots, access padlock) keep their own semantic @@ -439,14 +470,25 @@ + for (const ColorSegment& seg : ParseColorSegments(m_value)) { + wxUniChar shape; + if (IsShapeSentinel(seg.text, shape)) { ++ bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN || ++ shape == SHAPE_FAN || shape == SHAPE_CHIP); + int adv = SHAPE_ADVANCE; ++ // Health icons measure bigger and pack tighter, and report a taller ++ // content height so the row grows to fit them (round 14 #1). Sizes scale ++ // with the table zoom (round 14 #3). ++ int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5); ++ if (hh < 8) hh = 8; + if (const ShapeSvg* sv = LookupShapeSvg(shape)) { -+ int hh = 15; + int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh; -+ if (ww > adv) adv = ww; ++ if (health) { ++ adv = ww - 3; ++ if (adv < 1) adv = 1; ++ } else if (ww > adv) { ++ adv = ww; ++ } + } + w += adv; -+ if (h < 12) h = 12; ++ if (h < hh) h = hh; + continue; + } + wxSize e = GetTextExtent(seg.text); @@ -846,6 +888,7 @@ + dv->AssociateModel(store); + store->DecRef(); // the control owns a reference now + g_pulse_target = dv; // the locate-dot pulse timer repaints this control ++ g_zoom_table = dv; // the status-bar zoom slider scales this control (#3) + dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) { + if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0); + }); @@ -955,6 +998,10 @@ + dvlc_store(win)->AppendColumn("string"); + dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT, + width, wxALIGN_NOT, flags); ++ // Record the 100% column width for the zoom (round 14 #3); the first column of ++ // a (re)built table resets the list. ++ if (col == 0) g_zoom_base_w.clear(); ++ g_zoom_base_w.push_back(width); +} + +// Same bookkeeping as wxbr_dvlc_append_text_col, but the column is drawn by a @@ -971,6 +1018,9 @@ + wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col, + width, wxALIGN_NOT, flags); + dv->AppendColumn(c); ++ // Record the 100% column width for the zoom (round 14 #3). ++ if (col == 0) g_zoom_base_w.clear(); ++ g_zoom_base_w.push_back(width); + return (void*)c; +} + @@ -1690,15 +1740,69 @@ +static wxStaticText* g_status_indicator = nullptr; + +static void reposition_status_indicator() { -+ if (!g_status_indicator) return; -+ wxStatusBar* sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar); ++ wxStatusBar* sb = nullptr; ++ if (g_status_indicator) sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar); ++ if (!sb && g_zoom_slider) sb = wxDynamicCast(g_zoom_slider->GetParent(), wxStatusBar); + if (!sb) return; -+ wxRect r; -+ if (!sb->GetFieldRect(1, r)) return; -+ wxSize best = g_status_indicator->GetBestSize(); -+ int h = best.GetHeight(); -+ int y = r.y + (r.height - h) / 2; -+ g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h); ++ // Scan/apply indicator in field 1. ++ if (g_status_indicator) { ++ wxRect r; ++ if (sb->GetFieldRect(1, r)) { ++ wxSize best = g_status_indicator->GetBestSize(); ++ int h = best.GetHeight(); ++ int y = r.y + (r.height - h) / 2; ++ g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h); ++ } ++ } ++ // Zoom slider + "NNN%" label in the far-right field (round 14 #3): label at the ++ // right edge, slider filling the space to its left. ++ if (g_zoom_slider && g_zoom_label) { ++ int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1; ++ wxRect r; ++ if (sb->GetFieldRect(fld, r)) { ++ wxSize lbest = g_zoom_label->GetBestSize(); ++ int lw = lbest.GetWidth() + 6; ++ int lh = lbest.GetHeight(); ++ g_zoom_label->SetSize(r.x + r.width - lw, r.y + (r.height - lh) / 2, lw, lh); ++ int sw = r.width - lw - 8; ++ if (sw < 20) sw = 20; ++ int sh = r.height - 2; ++ g_zoom_slider->SetSize(r.x + 2, r.y + (r.height - sh) / 2, sw, sh); ++ } ++ } ++} ++ ++// Scale the table (round 14 #3): the font (native columns) and, via g_table_zoom, ++// the custom-renderer icon sizes. Purely a view change; no model or Rust state. ++static void apply_table_zoom(double factor) { ++ if (factor < 0.5) factor = 0.5; ++ if (factor > 2.5) factor = 2.5; ++ g_table_zoom = factor; ++ if (g_zoom_table) { ++ if (!g_zoom_base_font.IsOk()) g_zoom_base_font = g_zoom_table->GetFont(); ++ wxFont base = g_zoom_base_font.IsOk() ? g_zoom_base_font : *wxNORMAL_FONT; ++ wxFont f = base; ++ int pt = (int)(base.GetPointSize() * factor + 0.5); ++ if (pt < 5) pt = 5; ++ f.SetPointSize(pt); ++ g_zoom_table->SetFont(f); ++ // Scale every column width from its 100% width (recorded at append time) so ++ // text does not clip when zoomed (round 14 #3). ++ unsigned int nc = g_zoom_table->GetColumnCount(); ++ for (unsigned int i = 0; i < nc && i < g_zoom_base_w.size(); i++) { ++ int w = (int)(g_zoom_base_w[i] * factor + 0.5); ++ if (w < 8) w = 8; ++ g_zoom_table->GetColumn(i)->SetWidth(w); ++ } ++ // Recompute row heights / re-request renderer sizes, then repaint. ++ g_zoom_table->InvalidateBestSize(); ++ g_zoom_table->Refresh(); ++ g_zoom_table->Update(); ++ } ++ if (g_zoom_label) { ++ g_zoom_label->SetLabel(wxString::Format(wxT("%d%%"), (int)(factor * 100 + 0.5))); ++ reposition_status_indicator(); ++ } +} + +void wxbr_status_indicator_init(void* frame_ptr) { @@ -1729,6 +1833,51 @@ + g_status_indicator->Refresh(); +} + ++// Add the table-zoom slider + percent label to the frame's status bar (round 14 ++// #3). Widens the bar to three fields (status | indicator | zoom) and wires the ++// slider straight to apply_table_zoom -- no Rust round-trip. Call after the table ++// exists so the slider can find it. ++void wxbr_status_zoom_init(void* frame_ptr) { ++ wxFrame* frame = (wxFrame*)frame_ptr; ++ wxStatusBar* sb = frame->GetStatusBar(); ++ if (!sb) sb = frame->CreateStatusBar(); ++ int widths[3] = { -1, 240, 190 }; ++ sb->SetFieldsCount(3); ++ sb->SetStatusWidths(3, widths); ++ // A native slider needs more vertical room than a default status bar gives, so ++ // grow the bar to fit it (round 14 #3). ++ sb->SetMinHeight(30); ++ if (!g_zoom_slider) { ++ g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250); ++ g_zoom_slider->SetToolTip(wxT("Table zoom")); ++ g_zoom_label = new wxStaticText(sb, wxID_ANY, wxT("100%"), ++ wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE); ++ g_zoom_slider->Bind(wxEVT_SLIDER, [](wxCommandEvent& e) { ++ apply_table_zoom(e.GetInt() / 100.0); ++ }); ++ sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) { ++ reposition_status_indicator(); ++ ev.Skip(); ++ }); ++ } ++ reposition_status_indicator(); ++} ++ ++// Set the table zoom programmatically (e.g. to restore a saved value); also moves ++// the slider to match. ++void wxbr_table_set_zoom(double factor) { ++ if (g_zoom_slider) g_zoom_slider->SetValue((int)(factor * 100 + 0.5)); ++ apply_table_zoom(factor); ++} ++ ++// Re-apply the current zoom to freshly-rebuilt columns (round 14 #3). Called from ++// Rust right after the table's columns are recreated (they come back at their ++// 100% widths), so a non-100% zoom survives a column show/hide/reorder rebuild. ++void wxbr_table_zoom_reapply() { ++ // g_zoom_base_w was repopulated by the column appends during the rebuild. ++ apply_table_zoom(g_table_zoom); ++} ++ +// ---- 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 e50e8f32..42c98c61 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 @@ -175,6 +175,16 @@ const wxUniChar SHAPE_FAN = 0x0F; // cooling fan const wxUniChar SHAPE_CHIP = 0x10; // hashboard const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies +// Table zoom factor (round 14 #3), 1.0 = 100%. A status-bar slider scales the +// table font (native columns) and, through this factor, the custom-renderer +// icon sizes so the whole table zooms together. +double g_table_zoom = 1.0; +static wxDataViewCtrl* g_zoom_table = nullptr; // the table the zoom scales +static wxFont g_zoom_base_font; // its font at 100% (captured lazily) +static wxVector g_zoom_base_w; // column widths at 100% (per column) +static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider +static wxStaticText* g_zoom_label = nullptr; // the "100%" readout next to it + // Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a // wxTimer while any such dot is on screen; the treeview it repaints is tracked so // the timer can invalidate exactly it. @@ -289,13 +299,28 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, // SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the // segment colour, rasterise (cached), and draw centred in its slot. if (const ShapeSvg* sv = LookupShapeSvg(shape)) { - int h = cell.height - 4; - if (h > 15) h = 15; + // Component-health icons render bigger (nearly the full row height) and pack + // tighter than a padlock/status icon, so a row of power/control/fan/board + // icons stays large and compact (round 14 #1). + bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN || + shape == SHAPE_FAN || shape == SHAPE_CHIP); + int h = cell.height - (health ? 1 : 4); + int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5); + if (cap < 8) cap = 8; + if (h > cap) h = cap; if (h < 8) h = 8; int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h; if (w < 1) w = 1; const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, w, h); if (bmp.IsOk()) { + if (health) { + // Left-align and advance by less than the icon width so adjacent health + // icons sit close together (the Font Awesome glyphs carry inner margin, + // so a small bounding-box overlap does not visually collide). + dc->DrawBitmap(bmp, x, cy - h / 2, true); + int adv = w - 3; + return adv < 1 ? 1 : adv; + } int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE; dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true); return slot; @@ -402,6 +427,12 @@ class SegmentRenderer : public wxDataViewCustomRenderer { if (!plain.IsOk()) { plain = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT); } + // Draw segment text in the control's current font so it scales with the + // table zoom exactly like the native columns (round 14 #3); the DC otherwise + // keeps a default font that ignores SetFont on the control. + if (g_zoom_table && g_zoom_table->GetFont().IsOk()) { + dc->SetFont(g_zoom_table->GetFont()); + } wxCoord x = cell.x; for (const ColorSegment& seg : ParseColorSegments(m_value)) { // Shape segments (status dots, access padlock) keep their own semantic @@ -436,14 +467,25 @@ class SegmentRenderer : public wxDataViewCustomRenderer { for (const ColorSegment& seg : ParseColorSegments(m_value)) { wxUniChar shape; if (IsShapeSentinel(seg.text, shape)) { + bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN || + shape == SHAPE_FAN || shape == SHAPE_CHIP); int adv = SHAPE_ADVANCE; + // Health icons measure bigger and pack tighter, and report a taller + // content height so the row grows to fit them (round 14 #1). Sizes scale + // with the table zoom (round 14 #3). + int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5); + if (hh < 8) hh = 8; if (const ShapeSvg* sv = LookupShapeSvg(shape)) { - int hh = 15; int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh; - if (ww > adv) adv = ww; + if (health) { + adv = ww - 3; + if (adv < 1) adv = 1; + } else if (ww > adv) { + adv = ww; + } } w += adv; - if (h < 12) h = 12; + if (h < hh) h = hh; continue; } wxSize e = GetTextExtent(seg.text); @@ -843,6 +885,7 @@ void* wxbr_dvlc(void* parent) { dv->AssociateModel(store); store->DecRef(); // the control owns a reference now g_pulse_target = dv; // the locate-dot pulse timer repaints this control + g_zoom_table = dv; // the status-bar zoom slider scales this control (#3) dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) { if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0); }); @@ -952,6 +995,10 @@ void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reor dvlc_store(win)->AppendColumn("string"); dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT, width, wxALIGN_NOT, flags); + // Record the 100% column width for the zoom (round 14 #3); the first column of + // a (re)built table resets the list. + if (col == 0) g_zoom_base_w.clear(); + g_zoom_base_w.push_back(width); } // Same bookkeeping as wxbr_dvlc_append_text_col, but the column is drawn by a @@ -968,6 +1015,9 @@ void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col, width, wxALIGN_NOT, flags); dv->AppendColumn(c); + // Record the 100% column width for the zoom (round 14 #3). + if (col == 0) g_zoom_base_w.clear(); + g_zoom_base_w.push_back(width); return (void*)c; } @@ -1687,15 +1737,69 @@ void wxbr_call_after(int id) { static wxStaticText* g_status_indicator = nullptr; static void reposition_status_indicator() { - if (!g_status_indicator) return; - wxStatusBar* sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar); + wxStatusBar* sb = nullptr; + if (g_status_indicator) sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar); + if (!sb && g_zoom_slider) sb = wxDynamicCast(g_zoom_slider->GetParent(), wxStatusBar); if (!sb) return; - wxRect r; - if (!sb->GetFieldRect(1, r)) return; - wxSize best = g_status_indicator->GetBestSize(); - int h = best.GetHeight(); - int y = r.y + (r.height - h) / 2; - g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h); + // Scan/apply indicator in field 1. + if (g_status_indicator) { + wxRect r; + if (sb->GetFieldRect(1, r)) { + wxSize best = g_status_indicator->GetBestSize(); + int h = best.GetHeight(); + int y = r.y + (r.height - h) / 2; + g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h); + } + } + // Zoom slider + "NNN%" label in the far-right field (round 14 #3): label at the + // right edge, slider filling the space to its left. + if (g_zoom_slider && g_zoom_label) { + int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1; + wxRect r; + if (sb->GetFieldRect(fld, r)) { + wxSize lbest = g_zoom_label->GetBestSize(); + int lw = lbest.GetWidth() + 6; + int lh = lbest.GetHeight(); + g_zoom_label->SetSize(r.x + r.width - lw, r.y + (r.height - lh) / 2, lw, lh); + int sw = r.width - lw - 8; + if (sw < 20) sw = 20; + int sh = r.height - 2; + g_zoom_slider->SetSize(r.x + 2, r.y + (r.height - sh) / 2, sw, sh); + } + } +} + +// Scale the table (round 14 #3): the font (native columns) and, via g_table_zoom, +// the custom-renderer icon sizes. Purely a view change; no model or Rust state. +static void apply_table_zoom(double factor) { + if (factor < 0.5) factor = 0.5; + if (factor > 2.5) factor = 2.5; + g_table_zoom = factor; + if (g_zoom_table) { + if (!g_zoom_base_font.IsOk()) g_zoom_base_font = g_zoom_table->GetFont(); + wxFont base = g_zoom_base_font.IsOk() ? g_zoom_base_font : *wxNORMAL_FONT; + wxFont f = base; + int pt = (int)(base.GetPointSize() * factor + 0.5); + if (pt < 5) pt = 5; + f.SetPointSize(pt); + g_zoom_table->SetFont(f); + // Scale every column width from its 100% width (recorded at append time) so + // text does not clip when zoomed (round 14 #3). + unsigned int nc = g_zoom_table->GetColumnCount(); + for (unsigned int i = 0; i < nc && i < g_zoom_base_w.size(); i++) { + int w = (int)(g_zoom_base_w[i] * factor + 0.5); + if (w < 8) w = 8; + g_zoom_table->GetColumn(i)->SetWidth(w); + } + // Recompute row heights / re-request renderer sizes, then repaint. + g_zoom_table->InvalidateBestSize(); + g_zoom_table->Refresh(); + g_zoom_table->Update(); + } + if (g_zoom_label) { + g_zoom_label->SetLabel(wxString::Format(wxT("%d%%"), (int)(factor * 100 + 0.5))); + reposition_status_indicator(); + } } void wxbr_status_indicator_init(void* frame_ptr) { @@ -1726,6 +1830,51 @@ void wxbr_status_indicator_set(const char* text, int r, int g, int b) { g_status_indicator->Refresh(); } +// Add the table-zoom slider + percent label to the frame's status bar (round 14 +// #3). Widens the bar to three fields (status | indicator | zoom) and wires the +// slider straight to apply_table_zoom -- no Rust round-trip. Call after the table +// exists so the slider can find it. +void wxbr_status_zoom_init(void* frame_ptr) { + wxFrame* frame = (wxFrame*)frame_ptr; + wxStatusBar* sb = frame->GetStatusBar(); + if (!sb) sb = frame->CreateStatusBar(); + int widths[3] = { -1, 240, 190 }; + sb->SetFieldsCount(3); + sb->SetStatusWidths(3, widths); + // A native slider needs more vertical room than a default status bar gives, so + // grow the bar to fit it (round 14 #3). + sb->SetMinHeight(30); + if (!g_zoom_slider) { + g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250); + g_zoom_slider->SetToolTip(wxT("Table zoom")); + g_zoom_label = new wxStaticText(sb, wxID_ANY, wxT("100%"), + wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE); + g_zoom_slider->Bind(wxEVT_SLIDER, [](wxCommandEvent& e) { + apply_table_zoom(e.GetInt() / 100.0); + }); + sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) { + reposition_status_indicator(); + ev.Skip(); + }); + } + reposition_status_indicator(); +} + +// Set the table zoom programmatically (e.g. to restore a saved value); also moves +// the slider to match. +void wxbr_table_set_zoom(double factor) { + if (g_zoom_slider) g_zoom_slider->SetValue((int)(factor * 100 + 0.5)); + apply_table_zoom(factor); +} + +// Re-apply the current zoom to freshly-rebuilt columns (round 14 #3). Called from +// Rust right after the table's columns are recreated (they come back at their +// 100% widths), so a non-100% zoom survives a column show/hide/reorder rebuild. +void wxbr_table_zoom_reapply() { + // g_zoom_base_w was repopulated by the column appends during the rebuild. + apply_table_zoom(g_table_zoom); +} + // ---- 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 11ee9532..2a9af318 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 @@ -113,6 +113,9 @@ mod notsafe { pub fn wxbr_call_after(id: c_int); pub fn wxbr_status_indicator_init(frame: *mut c_void); pub fn wxbr_status_indicator_set(text: *const c_char, r: c_int, g: c_int, b: c_int); + pub fn wxbr_status_zoom_init(frame: *mut c_void); + pub fn wxbr_table_set_zoom(factor: f64); + pub fn wxbr_table_zoom_reapply(); } } @@ -196,6 +199,24 @@ pub fn status_indicator_init(frame: Widget) { unsafe { notsafe::wxbr_status_indicator_init(frame.0) } } +/// Add the table-zoom slider + percent label to the frame's status bar (round 14 +/// #3). Call after the table exists so the slider can find it. The slider scales +/// the table entirely in C++; no further Rust calls are needed. +pub fn status_zoom_init(frame: Widget) { + unsafe { notsafe::wxbr_status_zoom_init(frame.0) } +} + +/// Set the table zoom factor programmatically (1.0 = 100%); also moves the slider. +pub fn table_set_zoom(factor: f64) { + unsafe { notsafe::wxbr_table_set_zoom(factor) } +} + +/// Re-apply the current zoom after the table's columns are rebuilt, so a non-100% +/// zoom survives a column show/hide/reorder (round 14 #3). +pub fn table_zoom_reapply() { + unsafe { notsafe::wxbr_table_zoom_reapply() } +} + /// Set the bottom-right status indicator's text and colour (an empty string /// clears it). Used for scan/apply errors (red) and warnings (amber). pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) {