Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77399bdd06 | ||
|
|
408b7d12b4 | ||
|
|
50cd463bee | ||
|
|
d73299166e | ||
|
|
a81fef3c7d | ||
|
|
365732b5d4 | ||
|
|
98603077e3 |
Generated
+2
@@ -81,6 +81,8 @@ dependencies = [
|
|||||||
"asic-rs",
|
"asic-rs",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"measurements",
|
"measurements",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
"wx-rs",
|
"wx-rs",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -17,3 +17,5 @@ asic-rs = "0.8.1"
|
|||||||
measurements = "0.11"
|
measurements = "0.11"
|
||||||
tokio = { version = "1", features = ["rt"] }
|
tokio = { version = "1", features = ["rt"] }
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//! Real access / lock-state detection: whether this miner accepts privileged
|
||||||
|
//! (credentialed) command writes, or is view-only.
|
||||||
|
//!
|
||||||
|
//! asic-rs has no lock-state signal (a wrong-password miner just silently
|
||||||
|
//! returns fewer fields, because the collector drops the 401). We build the real
|
||||||
|
//! check ON TOP of asic-rs: a NON-mutating, digest-authenticated GET to a
|
||||||
|
//! privileged endpoint. On Antminer every `/cgi-bin/*.cgi` requires digest auth,
|
||||||
|
//! so the HTTP status is decisive -- 200 means our credentials authenticate
|
||||||
|
//! (we can write -> unlocked), 401/403 means they are rejected (view-only ->
|
||||||
|
//! locked). We probe `get_miner_conf.cgi`, which is read-only (never the
|
||||||
|
//! mutating `set_miner_conf.cgi`).
|
||||||
|
//!
|
||||||
|
//! We shell out to `curl --digest` (already present, supports digest auth)
|
||||||
|
//! rather than add an HTTP+digest crate, so the offline/vendored build is
|
||||||
|
//! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` =
|
||||||
|
//! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover).
|
||||||
|
|
||||||
|
use std::process::Command;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
/// Classify a miner's access state from an HTTP status code string (curl's
|
||||||
|
/// `%{http_code}` output). Conservative: anything other than a clear
|
||||||
|
/// authenticated/unauthorized answer is `None`.
|
||||||
|
pub fn classify_http_code(code: &str) -> Option<bool> {
|
||||||
|
match code.trim() {
|
||||||
|
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
||||||
|
"401" | "403" => Some(true), // rejected -> locked/view-only
|
||||||
|
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The privileged, read-only endpoint we probe per firmware family. Antminer
|
||||||
|
/// stock/aftermarket all gate `get_miner_conf.cgi` behind digest auth.
|
||||||
|
fn endpoint(_firmware: &str) -> &'static str {
|
||||||
|
"/cgi-bin/get_miner_conf.cgi"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probe one miner's access state over its web API with the given credentials.
|
||||||
|
/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)`
|
||||||
|
/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or
|
||||||
|
/// `Err` only on a failure to run curl at all.
|
||||||
|
pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
|
||||||
|
let url = format!("http://{ip}{}", endpoint(firmware));
|
||||||
|
let userpass = format!("{user}:{pass}");
|
||||||
|
let mut cmd = Command::new("curl");
|
||||||
|
cmd.args([
|
||||||
|
"-s",
|
||||||
|
"-o",
|
||||||
|
"/dev/null",
|
||||||
|
"-w",
|
||||||
|
"%{http_code}",
|
||||||
|
"--digest",
|
||||||
|
"-u",
|
||||||
|
&userpass,
|
||||||
|
"--connect-timeout",
|
||||||
|
"5",
|
||||||
|
"--max-time",
|
||||||
|
"9",
|
||||||
|
&url,
|
||||||
|
]);
|
||||||
|
let out = wait_with_timeout(cmd, Duration::from_secs(12))?;
|
||||||
|
// curl prints the status code to stdout regardless of exit status (000 on a
|
||||||
|
// connection failure), so classify the code rather than the exit status.
|
||||||
|
let code = String::from_utf8_lossy(&out.stdout);
|
||||||
|
Ok(classify_http_code(&code))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a command with a wall-clock timeout (curl can hang past --max-time on a
|
||||||
|
/// black-holed host).
|
||||||
|
fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process::Output, String> {
|
||||||
|
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 curl: {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("curl timed out".into());
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classify_codes() {
|
||||||
|
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
|
||||||
|
assert_eq!(classify_http_code("204"), Some(false));
|
||||||
|
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
|
||||||
|
assert_eq!(classify_http_code("403"), Some(true));
|
||||||
|
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
|
||||||
|
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
|
||||||
|
assert_eq!(classify_http_code("500"), None);
|
||||||
|
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
|
||||||
|
assert_eq!(classify_http_code(""), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,20 +14,24 @@ use asic_rs::core::traits::miner::MinerAuth;
|
|||||||
use crate::scan::config_path;
|
use crate::scan::config_path;
|
||||||
|
|
||||||
pub const CREDENTIALS_FILE: &str = "scan-credentials.txt";
|
pub const CREDENTIALS_FILE: &str = "scan-credentials.txt";
|
||||||
|
/// SSH login for the control board (used by the PIC probe; distinct from the
|
||||||
|
/// web/API scan credentials above -- miners' SSH root login is usually not the
|
||||||
|
/// same account as the web digest-auth login).
|
||||||
|
pub const SSH_CREDENTIALS_FILE: &str = "ssh-credentials.txt";
|
||||||
|
|
||||||
/// Load the saved miner username/password, if any were saved.
|
/// Load a saved username/password pair from `file`, if present.
|
||||||
pub fn load_credentials() -> Option<(String, String)> {
|
fn load_creds_file(file: &str) -> Option<(String, String)> {
|
||||||
let s = std::fs::read_to_string(config_path(CREDENTIALS_FILE)).ok()?;
|
let s = std::fs::read_to_string(config_path(file)).ok()?;
|
||||||
let mut lines = s.lines();
|
let mut lines = s.lines();
|
||||||
let user = lines.next()?.to_string();
|
let user = lines.next()?.to_string();
|
||||||
let pass = lines.next().unwrap_or("").to_string();
|
let pass = lines.next().unwrap_or("").to_string();
|
||||||
Some((user, pass))
|
Some((user, pass))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Save the miner username/password, restricting the file to owner
|
/// Save a username/password pair to `file`, restricting it to owner read/write
|
||||||
/// read/write (credentials are plaintext on disk, so the mode matters).
|
/// (credentials are plaintext on disk, so the mode matters).
|
||||||
pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
fn save_creds_file(file: &str, user: &str, pass: &str) -> std::io::Result<()> {
|
||||||
let p = config_path(CREDENTIALS_FILE);
|
let p = config_path(file);
|
||||||
if let Some(dir) = p.parent() {
|
if let Some(dir) = p.parent() {
|
||||||
std::fs::create_dir_all(dir)?;
|
std::fs::create_dir_all(dir)?;
|
||||||
}
|
}
|
||||||
@@ -47,15 +51,42 @@ pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove the saved credentials, if any. Not an error if none were saved.
|
fn clear_creds_file(file: &str) -> std::io::Result<()> {
|
||||||
pub fn clear_credentials() -> std::io::Result<()> {
|
match std::fs::remove_file(config_path(file)) {
|
||||||
match std::fs::remove_file(config_path(CREDENTIALS_FILE)) {
|
|
||||||
Ok(()) => Ok(()),
|
Ok(()) => Ok(()),
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Load the saved miner web/API username/password, if any were saved.
|
||||||
|
pub fn load_credentials() -> Option<(String, String)> {
|
||||||
|
load_creds_file(CREDENTIALS_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save the miner web/API username/password (0600).
|
||||||
|
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.
|
||||||
|
pub fn load_ssh_credentials() -> Option<(String, String)> {
|
||||||
|
load_creds_file(SSH_CREDENTIALS_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save the SSH username/password for the PIC probe (0600).
|
||||||
|
pub fn save_ssh_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
||||||
|
save_creds_file(SSH_CREDENTIALS_FILE, user, pass)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the saved web/API credentials, if any. Not an error if none were saved.
|
||||||
|
pub fn clear_credentials() -> std::io::Result<()> {
|
||||||
|
match clear_creds_file(CREDENTIALS_FILE) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Build a `MinerFactory` with the saved credentials (if any) applied as
|
/// Build a `MinerFactory` with the saved credentials (if any) applied as
|
||||||
/// discovery auth for every firmware backend, so scans, refreshes, config
|
/// discovery auth for every firmware backend, so scans, refreshes, config
|
||||||
/// actions, and firmware flashes all authenticate against a non-default
|
/// actions, and firmware flashes all authenticate against a non-default
|
||||||
|
|||||||
@@ -106,8 +106,9 @@ impl Board {
|
|||||||
tuning: self.mining,
|
tuning: self.mining,
|
||||||
firmware_flash,
|
firmware_flash,
|
||||||
},
|
},
|
||||||
// Demo values for the round-8 columns (synthetic, so the columns
|
// Demo values for the round-8/9 columns (synthetic, so the columns
|
||||||
// show variety offline).
|
// show variety offline).
|
||||||
|
algorithm: "SHA256".to_string(),
|
||||||
control_board: if self.model.contains("S17") {
|
control_board: if self.model.contains("S17") {
|
||||||
"Xilinx".to_string()
|
"Xilinx".to_string()
|
||||||
} else if self.model.contains("S19j") || self.model.contains("S19k") {
|
} else if self.model.contains("S19j") || self.model.contains("S19k") {
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
|
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
|
||||||
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
|
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
|
||||||
|
|
||||||
|
mod access_probe;
|
||||||
mod credentials;
|
mod credentials;
|
||||||
mod fixtures;
|
mod fixtures;
|
||||||
mod model;
|
mod model;
|
||||||
|
mod pic_probe;
|
||||||
|
mod presets;
|
||||||
mod scan;
|
mod scan;
|
||||||
mod ui;
|
mod ui;
|
||||||
|
|
||||||
|
|||||||
@@ -243,6 +243,8 @@ pub struct MinerRow {
|
|||||||
pub firmware: String,
|
pub firmware: String,
|
||||||
pub api_version: String,
|
pub api_version: String,
|
||||||
pub control_board: String,
|
pub control_board: String,
|
||||||
|
/// Mining algorithm (e.g. "SHA256", "Scrypt", "Equihash"), from asic-rs.
|
||||||
|
pub algorithm: String,
|
||||||
/// Whether the hashboards carry a PIC MCU. asic-rs does not report this over
|
/// Whether the hashboards carry a PIC MCU. asic-rs does not report this over
|
||||||
/// the network, so it is a best-effort inference (model-string heuristic):
|
/// the network, so it is a best-effort inference (model-string heuristic):
|
||||||
/// `None` = unknown, `Some(true)` = PIC, `Some(false)` = noPIC. True
|
/// `None` = unknown, `Some(true)` = PIC, `Some(false)` = noPIC. True
|
||||||
@@ -345,7 +347,7 @@ pub fn flash_confirmed(input: &str) -> bool {
|
|||||||
/// Model columns. Ip is fixed (always shown first); the rest map 1:1 to a
|
/// Model columns. Ip is fixed (always shown first); the rest map 1:1 to a
|
||||||
/// scannable metric and can be shown/hidden/reordered. Row selection replaces
|
/// scannable metric and can be shown/hidden/reordered. Row selection replaces
|
||||||
/// the old checkbox column.
|
/// the old checkbox column.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum Column {
|
pub enum Column {
|
||||||
Ip,
|
Ip,
|
||||||
Hashrate,
|
Hashrate,
|
||||||
@@ -369,6 +371,7 @@ pub enum Column {
|
|||||||
Serial,
|
Serial,
|
||||||
ApiVersion,
|
ApiVersion,
|
||||||
ControlBoard,
|
ControlBoard,
|
||||||
|
Algorithm,
|
||||||
Pic,
|
Pic,
|
||||||
Locked,
|
Locked,
|
||||||
Error,
|
Error,
|
||||||
@@ -389,7 +392,7 @@ pub enum Column {
|
|||||||
|
|
||||||
/// Every column, in registry order. Ip first, then the default-visible set
|
/// Every column, in registry order. Ip first, then the default-visible set
|
||||||
/// (UI-SPEC order), then all remaining metrics.
|
/// (UI-SPEC order), then all remaining metrics.
|
||||||
pub const ALL_COLUMNS: [Column; 38] = [
|
pub const ALL_COLUMNS: [Column; 39] = [
|
||||||
Column::Ip,
|
Column::Ip,
|
||||||
Column::Hashrate,
|
Column::Hashrate,
|
||||||
Column::Power,
|
Column::Power,
|
||||||
@@ -412,6 +415,7 @@ pub const ALL_COLUMNS: [Column; 38] = [
|
|||||||
Column::Serial,
|
Column::Serial,
|
||||||
Column::ApiVersion,
|
Column::ApiVersion,
|
||||||
Column::ControlBoard,
|
Column::ControlBoard,
|
||||||
|
Column::Algorithm,
|
||||||
Column::Pic,
|
Column::Pic,
|
||||||
Column::Locked,
|
Column::Locked,
|
||||||
Column::Error,
|
Column::Error,
|
||||||
@@ -467,6 +471,7 @@ impl Column {
|
|||||||
Column::Serial => "Serial",
|
Column::Serial => "Serial",
|
||||||
Column::ApiVersion => "API ver",
|
Column::ApiVersion => "API ver",
|
||||||
Column::ControlBoard => "Control board",
|
Column::ControlBoard => "Control board",
|
||||||
|
Column::Algorithm => "Algorithm",
|
||||||
Column::Pic => "PIC",
|
Column::Pic => "PIC",
|
||||||
Column::Locked => "Access",
|
Column::Locked => "Access",
|
||||||
Column::Error => "Errors",
|
Column::Error => "Errors",
|
||||||
@@ -503,6 +508,7 @@ impl Column {
|
|||||||
Column::Mac | Column::Hostname | Column::Serial => 150,
|
Column::Mac | Column::Hostname | Column::Serial => 150,
|
||||||
Column::ApiVersion | Column::Light => 90,
|
Column::ApiVersion | Column::Light => 90,
|
||||||
Column::ControlBoard => 130,
|
Column::ControlBoard => 130,
|
||||||
|
Column::Algorithm => 100,
|
||||||
Column::Pic => 70,
|
Column::Pic => 70,
|
||||||
Column::Locked => 90,
|
Column::Locked => 90,
|
||||||
Column::Error => 160,
|
Column::Error => 160,
|
||||||
@@ -644,6 +650,7 @@ impl Column {
|
|||||||
Column::Serial => r.serial.clone(),
|
Column::Serial => r.serial.clone(),
|
||||||
Column::ApiVersion => r.api_version.clone(),
|
Column::ApiVersion => r.api_version.clone(),
|
||||||
Column::ControlBoard => r.control_board.clone(),
|
Column::ControlBoard => r.control_board.clone(),
|
||||||
|
Column::Algorithm => r.algorithm.clone(),
|
||||||
Column::Pic => match r.pic_present {
|
Column::Pic => match r.pic_present {
|
||||||
Some(true) => "PIC".to_string(),
|
Some(true) => "PIC".to_string(),
|
||||||
Some(false) => "noPIC".to_string(),
|
Some(false) => "noPIC".to_string(),
|
||||||
@@ -688,7 +695,7 @@ pub enum SortKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Text-column filter operators (Excel-style text filters).
|
/// Text-column filter operators (Excel-style text filters).
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum TextOp {
|
pub enum TextOp {
|
||||||
Contains,
|
Contains,
|
||||||
NotContains,
|
NotContains,
|
||||||
@@ -698,7 +705,7 @@ pub enum TextOp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Numeric-column filter operators (Excel-style number filters).
|
/// Numeric-column filter operators (Excel-style number filters).
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum NumOp {
|
pub enum NumOp {
|
||||||
Between,
|
Between,
|
||||||
Eq,
|
Eq,
|
||||||
@@ -711,7 +718,7 @@ pub enum NumOp {
|
|||||||
|
|
||||||
/// One column's active filter. Text columns can filter by a value checklist
|
/// One column's active filter. Text columns can filter by a value checklist
|
||||||
/// ("is any of") or a text predicate; numeric columns by a numeric predicate.
|
/// ("is any of") or a text predicate; numeric columns by a numeric predicate.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum ColFilter {
|
pub enum ColFilter {
|
||||||
Values(HashSet<String>),
|
Values(HashSet<String>),
|
||||||
Text { op: TextOp, needle: String },
|
Text { op: TextOp, needle: String },
|
||||||
@@ -752,6 +759,7 @@ impl ColFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Display state: order, visibility, sort, filter.
|
/// Display state: order, visibility, sort, filter.
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct ViewState {
|
pub struct ViewState {
|
||||||
/// Model column order as displayed (Ip is always the first visible column).
|
/// Model column order as displayed (Ip is always the first visible column).
|
||||||
pub order: Vec<Column>,
|
pub order: Vec<Column>,
|
||||||
|
|||||||
@@ -0,0 +1,223 @@
|
|||||||
|
//! 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which I2C bus to probe, chosen from the control-board family. AMLogic uses
|
||||||
|
/// i2c-1, BeagleBone uses i2c-0; for anything else (Xilinx/CVITek/unknown) we
|
||||||
|
/// try both. The wiki confirms the AML/BB buses; Zynx/CVITek are unconfirmed.
|
||||||
|
pub fn bus_candidates(control_board: &str) -> Vec<u8> {
|
||||||
|
let cb = control_board.to_lowercase();
|
||||||
|
if cb.contains("amlogic") || cb.contains("aml") {
|
||||||
|
vec![1]
|
||||||
|
} else if cb.contains("beaglebone") || cb.contains("bb") {
|
||||||
|
vec![0]
|
||||||
|
} else {
|
||||||
|
vec![1, 0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Classify an `i2cdump -y <bus> 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<bool> {
|
||||||
|
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> <ascii gutter>"; 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 <pass>` 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<Option<bool>, 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<Option<bool>, 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<std::process::Output, String> {
|
||||||
|
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() {
|
||||||
|
assert_eq!(bus_candidates("AMLogic"), vec![1]);
|
||||||
|
assert_eq!(bus_candidates("BeagleBone Black"), vec![0]);
|
||||||
|
assert_eq!(bus_candidates("Xilinx"), vec![1, 0]);
|
||||||
|
assert_eq!(bus_candidates(""), vec![1, 0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
//! Saved view presets: named snapshots of the table's column arrangement,
|
||||||
|
//! visibility, sort, and filters. Persisted as JSON in the config dir. The
|
||||||
|
//! first preset is always a built-in "Default" profile.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::model::{ColFilter, Column, ViewState, ALL_COLUMNS};
|
||||||
|
use crate::scan::config_path;
|
||||||
|
|
||||||
|
pub const PRESETS_FILE: &str = "presets.json";
|
||||||
|
|
||||||
|
/// The built-in default profile's visible columns, in display order (Ip first).
|
||||||
|
const DEFAULT_PROFILE: [Column; 9] = [
|
||||||
|
Column::Ip,
|
||||||
|
Column::Model,
|
||||||
|
Column::Hashrate,
|
||||||
|
Column::Power,
|
||||||
|
Column::ChipTemp,
|
||||||
|
Column::Firmware,
|
||||||
|
Column::ControlBoard,
|
||||||
|
Column::Pic,
|
||||||
|
Column::Status,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// A serializable snapshot of a `ViewState` (Vec-based so JSON has no map keys
|
||||||
|
/// that are enums, and column order within `visible` is preserved).
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PresetView {
|
||||||
|
pub order: Vec<Column>,
|
||||||
|
pub visible: Vec<Column>,
|
||||||
|
pub sort: Option<(Column, bool)>,
|
||||||
|
pub filters: Vec<(Column, ColFilter)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PresetView {
|
||||||
|
pub fn from_view(v: &ViewState) -> PresetView {
|
||||||
|
PresetView {
|
||||||
|
order: v.order.clone(),
|
||||||
|
// keep the visible columns in display order for stability
|
||||||
|
visible: v.order.iter().copied().filter(|c| v.visible.contains(c)).collect(),
|
||||||
|
sort: v.sort,
|
||||||
|
filters: v.filters.iter().map(|(k, f)| (*k, f.clone())).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuild a `ViewState` from this snapshot. Any column missing from a
|
||||||
|
/// loaded (possibly older) preset is appended to `order` and left hidden, so
|
||||||
|
/// the result always covers every `Column`.
|
||||||
|
pub fn to_view(&self) -> ViewState {
|
||||||
|
let mut order = self.order.clone();
|
||||||
|
for c in ALL_COLUMNS {
|
||||||
|
if !order.contains(&c) {
|
||||||
|
order.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut visible: HashSet<Column> = self.visible.iter().copied().collect();
|
||||||
|
visible.insert(Column::Ip); // IP is always shown
|
||||||
|
let filters: HashMap<Column, ColFilter> = self.filters.iter().cloned().collect();
|
||||||
|
ViewState { order, visible, sort: self.sort, filters }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Preset {
|
||||||
|
pub name: String,
|
||||||
|
pub view: PresetView,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The built-in default profile (always present as the first preset).
|
||||||
|
pub fn default_preset() -> Preset {
|
||||||
|
let mut order: Vec<Column> = DEFAULT_PROFILE.to_vec();
|
||||||
|
for c in ALL_COLUMNS {
|
||||||
|
if !order.contains(&c) {
|
||||||
|
order.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Preset {
|
||||||
|
name: "Default".to_string(),
|
||||||
|
view: PresetView {
|
||||||
|
order,
|
||||||
|
visible: DEFAULT_PROFILE.to_vec(),
|
||||||
|
sort: None,
|
||||||
|
filters: Vec::new(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load saved presets, always with the built-in "Default" first. A missing or
|
||||||
|
/// unreadable file yields just the default.
|
||||||
|
pub fn load_presets() -> Vec<Preset> {
|
||||||
|
let mut presets = std::fs::read_to_string(config_path(PRESETS_FILE))
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| serde_json::from_str::<Vec<Preset>>(&s).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
// The default profile is always present and always first.
|
||||||
|
presets.retain(|p| p.name != "Default");
|
||||||
|
presets.insert(0, default_preset());
|
||||||
|
presets
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persist presets (the built-in "Default" is not written; it is re-seeded on
|
||||||
|
/// load). Best-effort: errors are returned for the caller to surface.
|
||||||
|
pub fn save_presets(presets: &[Preset]) -> std::io::Result<()> {
|
||||||
|
let p = config_path(PRESETS_FILE);
|
||||||
|
if let Some(dir) = p.parent() {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
let user: Vec<&Preset> = presets.iter().filter(|p| p.name != "Default").collect();
|
||||||
|
let json = serde_json::to_string_pretty(&user)
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||||
|
std::fs::write(p, json)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_preset_round_trips_through_view() {
|
||||||
|
let p = default_preset();
|
||||||
|
let view = p.view.to_view();
|
||||||
|
// IP first + the requested default columns visible.
|
||||||
|
assert!(view.visible.contains(&Column::Ip));
|
||||||
|
assert!(view.visible.contains(&Column::ControlBoard));
|
||||||
|
assert!(view.visible.contains(&Column::Pic));
|
||||||
|
assert!(view.visible.contains(&Column::Status));
|
||||||
|
assert!(!view.visible.contains(&Column::Cooling), "not in the default profile");
|
||||||
|
// to_view covers every column in `order`.
|
||||||
|
assert_eq!(view.order.len(), ALL_COLUMNS.len());
|
||||||
|
// Round-trip a snapshot back out.
|
||||||
|
let snap = PresetView::from_view(&view);
|
||||||
|
assert_eq!(snap.visible.first(), Some(&Column::Ip));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preset_json_round_trip() {
|
||||||
|
let p = default_preset();
|
||||||
|
let json = serde_json::to_string(&vec![&p]).unwrap();
|
||||||
|
let back: Vec<Preset> = serde_json::from_str(&json).unwrap();
|
||||||
|
assert_eq!(back.len(), 1);
|
||||||
|
assert_eq!(back[0].name, "Default");
|
||||||
|
assert_eq!(back[0].view.visible, DEFAULT_PROFILE.to_vec());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -498,6 +498,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
|
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
|
||||||
.fold(0.0f64, f64::max);
|
.fold(0.0f64, f64::max);
|
||||||
|
let algorithm = data.hashrate.as_ref().map(|h| h.algo.to_string()).unwrap_or_default();
|
||||||
let is_mining = data.is_mining;
|
let is_mining = data.is_mining;
|
||||||
let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths);
|
let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths);
|
||||||
let operating_state = data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default();
|
let operating_state = data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default();
|
||||||
@@ -525,6 +526,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
|
|||||||
ip: data.ip.to_string(),
|
ip: data.ip.to_string(),
|
||||||
selected: false,
|
selected: false,
|
||||||
caps,
|
caps,
|
||||||
|
algorithm,
|
||||||
pic_present,
|
pic_present,
|
||||||
write_locked,
|
write_locked,
|
||||||
errors,
|
errors,
|
||||||
@@ -905,6 +907,167 @@ pub fn start_firmware_flash_action(ips: Vec<String>, image: FirmwareImage) -> Ac
|
|||||||
ActionHandle { rx, cancel }
|
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<bool>, error: Option<String> },
|
||||||
|
Done { total: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A running PIC probe; `stop` cancels the remaining miners.
|
||||||
|
pub struct PicProbeHandle {
|
||||||
|
pub rx: Receiver<PicProbeMsg>,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 },
|
||||||
|
/// `locked` = Some(true) locked/view-only, Some(false) unlocked/writable,
|
||||||
|
/// None indeterminate; `error` set only when the probe couldn't run.
|
||||||
|
Result { ip: String, locked: Option<bool>, error: Option<String> },
|
||||||
|
Done { total: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A running access probe; `stop` cancels the remaining miners.
|
||||||
|
pub struct AccessProbeHandle {
|
||||||
|
pub rx: Receiver<AccessProbeMsg>,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AccessProbeHandle {
|
||||||
|
pub fn stop(&self) {
|
||||||
|
self.cancel.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probe the access/lock state of `targets` (ip + firmware string) over the web
|
||||||
|
/// API with `creds` (user, pass), on a background thread. A digest-auth GET is
|
||||||
|
/// fast, but we still run one miner at a time with cancel-between. Fake-scan mode
|
||||||
|
/// returns deterministic demo results.
|
||||||
|
pub fn start_access_probe(
|
||||||
|
targets: Vec<(String, String)>,
|
||||||
|
creds: (String, String),
|
||||||
|
) -> AccessProbeHandle {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let cancel = Arc::new(AtomicBool::new(false));
|
||||||
|
let total = targets.len();
|
||||||
|
let _ = tx.send(AccessProbeMsg::Started { total });
|
||||||
|
let (user, pass) = creds;
|
||||||
|
|
||||||
|
if fake_scan_enabled() {
|
||||||
|
let err_tx = tx.clone();
|
||||||
|
let thread_cancel = cancel.clone();
|
||||||
|
let res = std::thread::Builder::new().name("fake-access-probe".into()).spawn(move || {
|
||||||
|
for (ip, _fw) in targets {
|
||||||
|
if thread_cancel.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// Demo: the WardenOS-dev unit (.115) is locked, others unlocked.
|
||||||
|
let locked = Some(ip.ends_with(".115"));
|
||||||
|
let _ = tx.send(AccessProbeMsg::Result { ip, locked, error: None });
|
||||||
|
}
|
||||||
|
let _ = tx.send(AccessProbeMsg::Done { total });
|
||||||
|
});
|
||||||
|
if res.is_err() {
|
||||||
|
let _ = err_tx.send(AccessProbeMsg::Done { total });
|
||||||
|
}
|
||||||
|
return AccessProbeHandle { rx, cancel };
|
||||||
|
}
|
||||||
|
|
||||||
|
let thread_cancel = cancel.clone();
|
||||||
|
let err_tx = tx.clone();
|
||||||
|
let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || {
|
||||||
|
for (ip, fw) in targets {
|
||||||
|
if thread_cancel.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) {
|
||||||
|
Ok(v) => (v, None),
|
||||||
|
Err(e) => (None, Some(e)),
|
||||||
|
};
|
||||||
|
if tx.send(AccessProbeMsg::Result { ip, locked, error }).is_err() {
|
||||||
|
return; // UI gone
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = tx.send(AccessProbeMsg::Done { total });
|
||||||
|
});
|
||||||
|
if res.is_err() {
|
||||||
|
let _ = err_tx.send(AccessProbeMsg::Done { total });
|
||||||
|
}
|
||||||
|
AccessProbeHandle { rx, cancel }
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
+411
-3
@@ -16,6 +16,13 @@ pub const ID_PLAY: i32 = 104;
|
|||||||
pub const ID_PAUSE: i32 = 105;
|
pub const ID_PAUSE: i32 = 105;
|
||||||
pub const ID_STOP: i32 = 106;
|
pub const ID_STOP: i32 = 106;
|
||||||
pub const ID_SCAN_CREDS: i32 = 107;
|
pub const ID_SCAN_CREDS: i32 = 107;
|
||||||
|
pub const ID_PRESETS: i32 = 108;
|
||||||
|
// Presets dialog.
|
||||||
|
const ID_PRESET_LOAD: i32 = 770;
|
||||||
|
const ID_PRESET_SAVE: i32 = 771;
|
||||||
|
const ID_PRESET_DELETE: i32 = 772;
|
||||||
|
const ID_PRESET_CLOSE: i32 = 773;
|
||||||
|
const ID_PRESET_CHOICE: i32 = 774;
|
||||||
const ID_RANGES_APPLY: i32 = 201;
|
const ID_RANGES_APPLY: i32 = 201;
|
||||||
const ID_RANGES_CANCEL: i32 = 202;
|
const ID_RANGES_CANCEL: i32 = 202;
|
||||||
const ID_COLUMNS_OK: i32 = 203;
|
const ID_COLUMNS_OK: i32 = 203;
|
||||||
@@ -45,6 +52,11 @@ const ID_CTX_RESUME: i32 = 726;
|
|||||||
const ID_CTX_TUNING: i32 = 727;
|
const ID_CTX_TUNING: i32 = 727;
|
||||||
const ID_CTX_POWER: i32 = 728;
|
const ID_CTX_POWER: i32 = 728;
|
||||||
const ID_CTX_RESTART: i32 = 729;
|
const ID_CTX_RESTART: i32 = 729;
|
||||||
|
const ID_CTX_PIC_PROBE: i32 = 730;
|
||||||
|
const ID_CTX_ACCESS_PROBE: i32 = 731;
|
||||||
|
// SSH PIC-probe credentials dialog.
|
||||||
|
const ID_PICSSH_OK: i32 = 780;
|
||||||
|
const ID_PICSSH_CANCEL: i32 = 781;
|
||||||
// Value-prompt dialog for power-limit / tuning-percent actions.
|
// Value-prompt dialog for power-limit / tuning-percent actions.
|
||||||
const ID_ACTION_OK: i32 = 740;
|
const ID_ACTION_OK: i32 = 740;
|
||||||
const ID_ACTION_CANCEL: i32 = 741;
|
const ID_ACTION_CANCEL: i32 = 741;
|
||||||
@@ -315,6 +327,9 @@ pub struct App {
|
|||||||
action_is_power: bool,
|
action_is_power: bool,
|
||||||
action_total: usize,
|
action_total: usize,
|
||||||
action_done: usize,
|
action_done: usize,
|
||||||
|
// IPs the current config action targets, re-probed after it completes so the
|
||||||
|
// table reflects the change (e.g. the identify light toggling).
|
||||||
|
action_targets: Vec<String>,
|
||||||
// A confirmation dialog for disruptive actions, plus its pending target.
|
// A confirmation dialog for disruptive actions, plus its pending target.
|
||||||
confirm_dialog: Widget,
|
confirm_dialog: Widget,
|
||||||
pending_confirm: Option<(Vec<String>, scan::ConfigAction)>,
|
pending_confirm: Option<(Vec<String>, scan::ConfigAction)>,
|
||||||
@@ -337,6 +352,19 @@ pub struct App {
|
|||||||
creds_dialog: Widget,
|
creds_dialog: Widget,
|
||||||
creds_user_input: Widget,
|
creds_user_input: Widget,
|
||||||
creds_pass_input: Widget,
|
creds_pass_input: Widget,
|
||||||
|
// Background access (lock-state) probe.
|
||||||
|
access_probe: Option<scan::AccessProbeHandle>,
|
||||||
|
// Background SSH PIC probe + its credentials dialog.
|
||||||
|
pic_probe: Option<scan::PicProbeHandle>,
|
||||||
|
pending_pic_targets: Vec<(String, String)>,
|
||||||
|
picssh_dialog: Widget,
|
||||||
|
picssh_user_input: Widget,
|
||||||
|
picssh_pass_input: Widget,
|
||||||
|
// Saved view presets + the Presets dialog widgets.
|
||||||
|
presets: Vec<crate::presets::Preset>,
|
||||||
|
presets_dialog: Widget,
|
||||||
|
presets_choice: Widget,
|
||||||
|
presets_name_input: Widget,
|
||||||
// The last action's result, kept on the status bar for a few ticks.
|
// The last action's result, kept on the status bar for a few ticks.
|
||||||
action_result: Option<String>,
|
action_result: Option<String>,
|
||||||
action_result_ticks: u8,
|
action_result_ticks: u8,
|
||||||
@@ -414,7 +442,7 @@ pub fn build(frame: Widget) -> App {
|
|||||||
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber);
|
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber);
|
||||||
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red);
|
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red);
|
||||||
let (card_paused, kpi_paused) = mk_card("Paused", ColorKind::Blue);
|
let (card_paused, kpi_paused) = mk_card("Paused", ColorKind::Blue);
|
||||||
let (_card_hashrate, kpi_hashrate) = mk_card("Hashrate", ColorKind::Accent);
|
let (_card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Accent);
|
||||||
let (_card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral);
|
let (_card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral);
|
||||||
drop(mk_card);
|
drop(mk_card);
|
||||||
// The 4 status cards double as quick-filters: clicking one narrows the
|
// The 4 status cards double as quick-filters: clicking one narrows the
|
||||||
@@ -446,6 +474,8 @@ pub fn build(frame: Widget) -> App {
|
|||||||
let stop_btn = Widget::media_button(panel, ID_STOP, 2, (226, 72, 60));
|
let stop_btn = Widget::media_button(panel, ID_STOP, 2, (226, 72, 60));
|
||||||
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||||
ctl.add_stretch(1);
|
ctl.add_stretch(1);
|
||||||
|
let presets_btn = Widget::button(panel, "Presets", ID_PRESETS);
|
||||||
|
ctl.add(presets_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||||
let filter_btn = Widget::button(panel, "Filter", ID_FILTER);
|
let filter_btn = Widget::button(panel, "Filter", ID_FILTER);
|
||||||
ctl.add(filter_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
ctl.add(filter_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||||
let columns_btn = Widget::button(panel, "Columns", ID_COLUMNS);
|
let columns_btn = Widget::button(panel, "Columns", ID_COLUMNS);
|
||||||
@@ -512,6 +542,7 @@ pub fn build(frame: Widget) -> App {
|
|||||||
action_is_power: false,
|
action_is_power: false,
|
||||||
action_total: 0,
|
action_total: 0,
|
||||||
action_done: 0,
|
action_done: 0,
|
||||||
|
action_targets: Vec::new(),
|
||||||
confirm_dialog: frame,
|
confirm_dialog: frame,
|
||||||
pending_confirm: None,
|
pending_confirm: None,
|
||||||
flash_confirm_dialog: frame,
|
flash_confirm_dialog: frame,
|
||||||
@@ -522,6 +553,16 @@ pub fn build(frame: Widget) -> App {
|
|||||||
creds_dialog: frame,
|
creds_dialog: frame,
|
||||||
creds_user_input: frame,
|
creds_user_input: frame,
|
||||||
creds_pass_input: frame,
|
creds_pass_input: frame,
|
||||||
|
access_probe: None,
|
||||||
|
pic_probe: None,
|
||||||
|
pending_pic_targets: Vec::new(),
|
||||||
|
picssh_dialog: frame,
|
||||||
|
picssh_user_input: frame,
|
||||||
|
picssh_pass_input: frame,
|
||||||
|
presets: crate::presets::load_presets(),
|
||||||
|
presets_dialog: frame,
|
||||||
|
presets_choice: frame,
|
||||||
|
presets_name_input: frame,
|
||||||
action_result: None,
|
action_result: None,
|
||||||
action_result_ticks: 0,
|
action_result_ticks: 0,
|
||||||
ranges_dialog: frame,
|
ranges_dialog: frame,
|
||||||
@@ -544,6 +585,10 @@ pub fn build(frame: Widget) -> App {
|
|||||||
filter_pending_op: None,
|
filter_pending_op: None,
|
||||||
filter_working: HashMap::new(),
|
filter_working: HashMap::new(),
|
||||||
};
|
};
|
||||||
|
// Boot with the first (Default) preset's column layout.
|
||||||
|
if let Some(p) = app.presets.first() {
|
||||||
|
app.view = p.view.to_view();
|
||||||
|
}
|
||||||
app.rebuild_table();
|
app.rebuild_table();
|
||||||
Widget::timer(TIMER_SCAN, 1000);
|
Widget::timer(TIMER_SCAN, 1000);
|
||||||
app
|
app
|
||||||
@@ -672,6 +717,10 @@ impl App {
|
|||||||
_ => continue,
|
_ => continue,
|
||||||
};
|
};
|
||||||
t.dvlc_set_cell(disp, ci, &encoded);
|
t.dvlc_set_cell(disp, ci, &encoded);
|
||||||
|
// The Errors cell gets the full message list as a hover tooltip.
|
||||||
|
if matches!(c, Column::Error) {
|
||||||
|
t.dvlc_set_cell_tooltip(disp, ci, &r.errors.join("\n"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(row) = top {
|
if let Some(row) = top {
|
||||||
@@ -698,7 +747,8 @@ impl App {
|
|||||||
self.kpi_slow.set_label(&k.slow.to_string());
|
self.kpi_slow.set_label(&k.slow.to_string());
|
||||||
self.kpi_not.set_label(&k.not_hashing.to_string());
|
self.kpi_not.set_label(&k.not_hashing.to_string());
|
||||||
self.kpi_paused.set_label(&k.paused.to_string());
|
self.kpi_paused.set_label(&k.paused.to_string());
|
||||||
self.kpi_hashrate.set_label(&format_si(k.total_hashrate_ths * 1e12, "H/s"));
|
// No "/s" suffix on the KPI (per UI request): "685 TH", "1.2 PH".
|
||||||
|
self.kpi_hashrate.set_label(&format_si(k.total_hashrate_ths * 1e12, "H"));
|
||||||
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
|
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -789,6 +839,12 @@ impl App {
|
|||||||
// Refresh is always offered for a non-empty selection, independent of
|
// Refresh is always offered for a non-empty selection, independent of
|
||||||
// the capability intersection below.
|
// the capability intersection below.
|
||||||
menu.menu_append(ID_CTX_REFRESH, "Refresh");
|
menu.menu_append(ID_CTX_REFRESH, "Refresh");
|
||||||
|
// Real PIC-vs-noPIC detection via an on-board SSH i2c probe (asic-rs
|
||||||
|
// cannot report it over the network); offered for any selection.
|
||||||
|
menu.menu_append(ID_CTX_PIC_PROBE, "Detect PIC (SSH)...");
|
||||||
|
// Real access/lock-state check (credentialed digest GET; uses the saved
|
||||||
|
// scan credentials).
|
||||||
|
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
|
||||||
// Config actions common to the whole selection (capability
|
// Config actions common to the whole selection (capability
|
||||||
// intersection): an action is offered only if every selected miner
|
// intersection): an action is offered only if every selected miner
|
||||||
// supports it.
|
// supports it.
|
||||||
@@ -861,6 +917,7 @@ impl App {
|
|||||||
old.stop();
|
old.stop();
|
||||||
}
|
}
|
||||||
let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len());
|
let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len());
|
||||||
|
self.action_targets = ips.clone();
|
||||||
self.action = Some(scan::start_config_action(ips, action));
|
self.action = Some(scan::start_config_action(ips, action));
|
||||||
wx_rs::set_status_text(&msg);
|
wx_rs::set_status_text(&msg);
|
||||||
}
|
}
|
||||||
@@ -884,6 +941,223 @@ impl App {
|
|||||||
wx_rs::set_status_text(&msg);
|
wx_rs::set_status_text(&msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build the SSH PIC-probe dialog: captures the selected miners, collects
|
||||||
|
/// SSH credentials (prefilled from the saved SSH login), and on OK runs the
|
||||||
|
/// on-board i2c probe. Returns None (no dialog) if nothing is selected or a
|
||||||
|
/// flash holds the exclusive lock.
|
||||||
|
fn build_pic_probe_dialog(&mut self) -> Option<Widget> {
|
||||||
|
if self.flashing {
|
||||||
|
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if self.pic_probe.is_some() {
|
||||||
|
wx_rs::set_status_text("a PIC probe is already running");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let targets: Vec<(String, String)> = self
|
||||||
|
.selected_rows()
|
||||||
|
.iter()
|
||||||
|
.map(|r| (r.ip.clone(), r.control_board.clone()))
|
||||||
|
.collect();
|
||||||
|
if targets.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.pending_pic_targets = targets;
|
||||||
|
let (saved_user, _) = credentials::load_ssh_credentials().unwrap_or_default();
|
||||||
|
let frame = Widget::main_frame();
|
||||||
|
let dlg = Widget::dialog(frame, "Detect PIC via SSH");
|
||||||
|
let root = Widget::box_sizer(true);
|
||||||
|
root.add(
|
||||||
|
Widget::static_text(
|
||||||
|
dlg,
|
||||||
|
&format!(
|
||||||
|
"Probe {} miner(s) over SSH (runs i2cdump on the control board). SSH login for the miner (root, etc.):",
|
||||||
|
self.pending_pic_targets.len()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
0,
|
||||||
|
sf::BORDER_ALL,
|
||||||
|
8,
|
||||||
|
);
|
||||||
|
let user_row = Widget::box_sizer(false);
|
||||||
|
user_row.add(Widget::static_text(dlg, "SSH user:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
|
||||||
|
let user_input = Widget::text_ctrl(dlg, false);
|
||||||
|
user_input.set_value(if saved_user.is_empty() { "root" } else { &saved_user });
|
||||||
|
user_input.set_min_size(180, -1);
|
||||||
|
user_row.add(user_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
|
||||||
|
root.add_sizer(user_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||||
|
let pass_row = Widget::box_sizer(false);
|
||||||
|
pass_row.add(Widget::static_text(dlg, "SSH password:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
|
||||||
|
let pass_input = Widget::text_ctrl(dlg, false);
|
||||||
|
pass_input.set_min_size(180, -1);
|
||||||
|
pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
|
||||||
|
root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||||
|
root.add(
|
||||||
|
Widget::static_text(dlg, "(Leave the password blank to use SSH key auth.)"),
|
||||||
|
0,
|
||||||
|
sf::BORDER_ALL,
|
||||||
|
6,
|
||||||
|
);
|
||||||
|
let btns = Widget::box_sizer(false);
|
||||||
|
btns.add_stretch(1);
|
||||||
|
btns.add(Widget::button(dlg, "Probe", ID_PICSSH_OK), 0, sf::BORDER_ALL, 6);
|
||||||
|
btns.add(Widget::button(dlg, "Cancel", ID_PICSSH_CANCEL), 0, sf::BORDER_ALL, 6);
|
||||||
|
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||||
|
root.set_sizer_on(dlg);
|
||||||
|
dlg.set_min_size(420, 210);
|
||||||
|
dlg.fit(dlg);
|
||||||
|
self.picssh_dialog = dlg;
|
||||||
|
self.picssh_user_input = user_input;
|
||||||
|
self.picssh_pass_input = pass_input;
|
||||||
|
Some(dlg)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the PIC probe with the SSH credentials just entered.
|
||||||
|
fn apply_pic_probe(&mut self) {
|
||||||
|
let user = self.picssh_user_input.get_value().trim().to_string();
|
||||||
|
if user.is_empty() {
|
||||||
|
wx_rs::set_status_text("enter an SSH user");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let pass = self.picssh_pass_input.get_value();
|
||||||
|
let _ = credentials::save_ssh_credentials(&user, &pass);
|
||||||
|
self.picssh_dialog.close(1);
|
||||||
|
let targets = std::mem::take(&mut self.pending_pic_targets);
|
||||||
|
let n = targets.len();
|
||||||
|
self.pic_probe = Some(scan::start_pic_probe(
|
||||||
|
targets,
|
||||||
|
crate::pic_probe::SshCreds { user, pass },
|
||||||
|
));
|
||||||
|
wx_rs::set_status_text(&format!("probing PIC on {n} miner(s) via SSH..."));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the access (lock-state) probe on the selected miners, using the
|
||||||
|
/// saved scan (web) credentials (defaulting to root/root if none are set).
|
||||||
|
fn start_access_probe(&mut self) {
|
||||||
|
if self.flashing {
|
||||||
|
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.access_probe.is_some() {
|
||||||
|
wx_rs::set_status_text("an access check is already running");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let targets: Vec<(String, String)> = self
|
||||||
|
.selected_rows()
|
||||||
|
.iter()
|
||||||
|
.map(|r| (r.ip.clone(), r.firmware.clone()))
|
||||||
|
.collect();
|
||||||
|
if targets.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
|
||||||
|
let n = targets.len();
|
||||||
|
self.access_probe = Some(scan::start_access_probe(targets, creds));
|
||||||
|
wx_rs::set_status_text(&format!("checking access on {n} miner(s)..."));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drain the running access probe: update each miner's write_locked as its
|
||||||
|
/// result arrives, and refresh the table + status when done.
|
||||||
|
fn drain_access_probe(&mut self) {
|
||||||
|
let Some(h) = &self.access_probe else { return };
|
||||||
|
let mut status: Option<String> = None;
|
||||||
|
let mut done = false;
|
||||||
|
let mut changed = false;
|
||||||
|
loop {
|
||||||
|
match h.rx.try_recv() {
|
||||||
|
Ok(scan::AccessProbeMsg::Started { total }) => {
|
||||||
|
status = Some(format!("access check: 0/{total}..."));
|
||||||
|
}
|
||||||
|
Ok(scan::AccessProbeMsg::Result { ip, locked, error }) => {
|
||||||
|
if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) {
|
||||||
|
if error.is_none() {
|
||||||
|
r.write_locked = locked;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status = Some(match (&locked, &error) {
|
||||||
|
(_, Some(e)) => format!("access {ip}: {e}"),
|
||||||
|
(Some(true), _) => format!("access {ip}: locked"),
|
||||||
|
(Some(false), _) => format!("access {ip}: unlocked"),
|
||||||
|
(None, _) => format!("access {ip}: indeterminate"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(scan::AccessProbeMsg::Done { total }) => {
|
||||||
|
status = Some(format!("access check done ({total} miner(s))"));
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(std::sync::mpsc::TryRecvError::Empty) => break,
|
||||||
|
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
|
self.fill_rows();
|
||||||
|
}
|
||||||
|
if done {
|
||||||
|
self.access_probe = None;
|
||||||
|
self.action_result = status.clone();
|
||||||
|
self.action_result_ticks = ACTION_RESULT_TICKS;
|
||||||
|
}
|
||||||
|
if let Some(s) = status {
|
||||||
|
wx_rs::set_status_text(&s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drain the running PIC probe: update each miner's pic_present as its result
|
||||||
|
/// arrives, and refresh the table + status when done.
|
||||||
|
fn drain_pic_probe(&mut self) {
|
||||||
|
let Some(h) = &self.pic_probe else { return };
|
||||||
|
let mut status: Option<String> = None;
|
||||||
|
let mut done = false;
|
||||||
|
let mut changed = false;
|
||||||
|
loop {
|
||||||
|
match h.rx.try_recv() {
|
||||||
|
Ok(scan::PicProbeMsg::Started { total }) => {
|
||||||
|
status = Some(format!("PIC probe: 0/{total}..."));
|
||||||
|
}
|
||||||
|
Ok(scan::PicProbeMsg::Result { ip, pic, error }) => {
|
||||||
|
if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) {
|
||||||
|
if error.is_none() {
|
||||||
|
r.pic_present = pic;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status = Some(match (&pic, &error) {
|
||||||
|
(_, Some(e)) => format!("PIC probe {ip}: {e}"),
|
||||||
|
(Some(true), _) => format!("PIC probe {ip}: PIC"),
|
||||||
|
(Some(false), _) => format!("PIC probe {ip}: noPIC"),
|
||||||
|
(None, _) => format!("PIC probe {ip}: indeterminate"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(scan::PicProbeMsg::Done { total }) => {
|
||||||
|
status = Some(format!("PIC probe done ({total} miner(s))"));
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(std::sync::mpsc::TryRecvError::Empty) => break,
|
||||||
|
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
|
self.fill_rows();
|
||||||
|
}
|
||||||
|
if done {
|
||||||
|
self.pic_probe = None;
|
||||||
|
self.action_result = status.clone();
|
||||||
|
self.action_result_ticks = ACTION_RESULT_TICKS;
|
||||||
|
}
|
||||||
|
if let Some(s) = status {
|
||||||
|
wx_rs::set_status_text(&s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A menu item was chosen. Direct actions start immediately; the value-input
|
/// A menu item was chosen. Direct actions start immediately; the value-input
|
||||||
/// actions (power limit / tuning %) return a prompt dialog to show modally.
|
/// actions (power limit / tuning %) return a prompt dialog to show modally.
|
||||||
fn on_menu_item(&mut self, id: i32) -> Option<Widget> {
|
fn on_menu_item(&mut self, id: i32) -> Option<Widget> {
|
||||||
@@ -897,6 +1171,8 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
|
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
|
||||||
|
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
|
||||||
|
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
|
||||||
ID_CTX_FLASH => {
|
ID_CTX_FLASH => {
|
||||||
// A flash needs exclusive hardware access; don't even prompt if
|
// A flash needs exclusive hardware access; don't even prompt if
|
||||||
// any scan / refresh / action is running (re-checked at confirm).
|
// any scan / refresh / action is running (re-checked at confirm).
|
||||||
@@ -1235,6 +1511,7 @@ impl App {
|
|||||||
}
|
}
|
||||||
if finished {
|
if finished {
|
||||||
self.action = None;
|
self.action = None;
|
||||||
|
let was_flash = self.flashing;
|
||||||
// Release the firmware-flash exclusive lock (harmless no-op for a
|
// Release the firmware-flash exclusive lock (harmless no-op for a
|
||||||
// plain config action, which never set it).
|
// plain config action, which never set it).
|
||||||
self.flashing = false;
|
self.flashing = false;
|
||||||
@@ -1242,6 +1519,13 @@ impl App {
|
|||||||
// action's outcome (incl. failures) isn't clobbered by the next tick.
|
// action's outcome (incl. failures) isn't clobbered by the next tick.
|
||||||
self.action_result = status.clone();
|
self.action_result = status.clone();
|
||||||
self.action_result_ticks = ACTION_RESULT_TICKS;
|
self.action_result_ticks = ACTION_RESULT_TICKS;
|
||||||
|
// Re-probe the miners the action touched so the table reflects the
|
||||||
|
// change (e.g. the identify light). Skip after a flash (the miner is
|
||||||
|
// rebooting and won't answer a refresh yet).
|
||||||
|
let targets = std::mem::take(&mut self.action_targets);
|
||||||
|
if !was_flash && !targets.is_empty() {
|
||||||
|
self.start_refresh(targets);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if let Some(s) = status {
|
if let Some(s) = status {
|
||||||
wx_rs::set_status_text(&s);
|
wx_rs::set_status_text(&s);
|
||||||
@@ -1376,9 +1660,14 @@ impl App {
|
|||||||
self.drain_scan();
|
self.drain_scan();
|
||||||
self.drain_action();
|
self.drain_action();
|
||||||
self.drain_refresh();
|
self.drain_refresh();
|
||||||
|
self.drain_pic_probe();
|
||||||
|
self.drain_access_probe();
|
||||||
if self.scanning {
|
if self.scanning {
|
||||||
return; // status already shows scan progress
|
return; // status already shows scan progress
|
||||||
}
|
}
|
||||||
|
if self.pic_probe.is_some() || self.access_probe.is_some() {
|
||||||
|
return; // a probe is in flight; keep its status
|
||||||
|
}
|
||||||
if self.action.is_some() {
|
if self.action.is_some() {
|
||||||
return; // a config action is in flight; keep its status
|
return; // a config action is in flight; keep its status
|
||||||
}
|
}
|
||||||
@@ -1645,6 +1934,115 @@ impl App {
|
|||||||
ALL_COLUMNS.iter().copied().filter(|c| *c != Column::Ip).collect()
|
ALL_COLUMNS.iter().copied().filter(|c| *c != Column::Ip).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build (but do not show) the view-presets dialog: load a saved view, save
|
||||||
|
/// the current columns/filters/sort as a named preset, or delete one.
|
||||||
|
fn build_presets_dialog(&mut self) -> Widget {
|
||||||
|
let frame = Widget::main_frame();
|
||||||
|
let dlg = Widget::dialog(frame, "View presets");
|
||||||
|
let root = Widget::box_sizer(true);
|
||||||
|
root.add(
|
||||||
|
Widget::static_text(
|
||||||
|
dlg,
|
||||||
|
"Load a saved view, or save the current columns, filters and sort as a new preset.",
|
||||||
|
),
|
||||||
|
0,
|
||||||
|
sf::BORDER_ALL,
|
||||||
|
8,
|
||||||
|
);
|
||||||
|
let choice = Widget::choice(dlg, ID_PRESET_CHOICE);
|
||||||
|
for p in &self.presets {
|
||||||
|
choice.choice_append(&p.name);
|
||||||
|
}
|
||||||
|
choice.choice_set_selection(0);
|
||||||
|
choice.set_min_size(220, -1);
|
||||||
|
root.add(choice, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
|
||||||
|
let row = Widget::box_sizer(false);
|
||||||
|
row.add(Widget::button(dlg, "Load", ID_PRESET_LOAD), 0, sf::BORDER_ALL, 4);
|
||||||
|
row.add(Widget::button(dlg, "Delete", ID_PRESET_DELETE), 0, sf::BORDER_ALL, 4);
|
||||||
|
root.add_sizer(row, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
|
||||||
|
let saverow = Widget::box_sizer(false);
|
||||||
|
saverow.add(
|
||||||
|
Widget::static_text(dlg, "Save current as:"),
|
||||||
|
0,
|
||||||
|
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL,
|
||||||
|
4,
|
||||||
|
);
|
||||||
|
let name = Widget::text_ctrl(dlg, false);
|
||||||
|
name.set_min_size(150, -1);
|
||||||
|
saverow.add(name, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||||
|
saverow.add(Widget::button(dlg, "Save", ID_PRESET_SAVE), 0, sf::BORDER_ALL, 4);
|
||||||
|
root.add_sizer(saverow, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
|
||||||
|
let btns = Widget::box_sizer(false);
|
||||||
|
btns.add_stretch(1);
|
||||||
|
btns.add(Widget::button(dlg, "Close", ID_PRESET_CLOSE), 0, sf::BORDER_ALL, 6);
|
||||||
|
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||||
|
root.set_sizer_on(dlg);
|
||||||
|
dlg.set_min_size(400, 220);
|
||||||
|
dlg.fit(dlg);
|
||||||
|
self.presets_dialog = dlg;
|
||||||
|
self.presets_choice = choice;
|
||||||
|
self.presets_name_input = name;
|
||||||
|
dlg
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the selected preset, replacing the current view (columns, filters,
|
||||||
|
/// sort) and rebuilding the table.
|
||||||
|
fn apply_preset_load(&mut self) {
|
||||||
|
let sel = self.presets_choice.choice_get_selection();
|
||||||
|
let Some(p) = usize::try_from(sel).ok().and_then(|i| self.presets.get(i)) else { return };
|
||||||
|
self.view = p.view.to_view();
|
||||||
|
self.presets_dialog.close(1);
|
||||||
|
self.rebuild_table();
|
||||||
|
self.update_headers();
|
||||||
|
self.resync_kpi_filter();
|
||||||
|
wx_rs::set_status_text("preset loaded");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save the current view as a new (or replaced) named preset.
|
||||||
|
fn apply_preset_save(&mut self) {
|
||||||
|
let name = self.presets_name_input.get_value().trim().to_string();
|
||||||
|
if name.is_empty() {
|
||||||
|
wx_rs::set_status_text("enter a preset name");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if name == "Default" {
|
||||||
|
wx_rs::set_status_text("\"Default\" is reserved");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let view = crate::presets::PresetView::from_view(&self.view);
|
||||||
|
let preset = crate::presets::Preset { name: name.clone(), view };
|
||||||
|
if let Some(existing) = self.presets.iter_mut().find(|p| p.name == name) {
|
||||||
|
*existing = preset;
|
||||||
|
} else {
|
||||||
|
self.presets.push(preset);
|
||||||
|
}
|
||||||
|
match crate::presets::save_presets(&self.presets) {
|
||||||
|
Ok(()) => {
|
||||||
|
self.presets_dialog.close(1);
|
||||||
|
wx_rs::set_status_text(&format!("saved preset \"{name}\""));
|
||||||
|
}
|
||||||
|
Err(e) => wx_rs::set_status_text(&format!("failed to save preset: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete the selected preset (the built-in "Default" can't be deleted).
|
||||||
|
fn apply_preset_delete(&mut self) {
|
||||||
|
let sel = self.presets_choice.choice_get_selection();
|
||||||
|
let Some(i) = usize::try_from(sel).ok().filter(|&i| i < self.presets.len()) else { return };
|
||||||
|
if self.presets[i].name == "Default" {
|
||||||
|
wx_rs::set_status_text("the Default preset can't be deleted");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let name = self.presets.remove(i).name;
|
||||||
|
match crate::presets::save_presets(&self.presets) {
|
||||||
|
Ok(()) => {
|
||||||
|
self.presets_dialog.close(1);
|
||||||
|
wx_rs::set_status_text(&format!("deleted preset \"{name}\""));
|
||||||
|
}
|
||||||
|
Err(e) => wx_rs::set_status_text(&format!("failed to save presets: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Build (but do not show) the columns chooser: a rearrangeable checklist of
|
/// Build (but do not show) the columns chooser: a rearrangeable checklist of
|
||||||
/// every scannable metric. Check to show; drag or use the up/down arrows to
|
/// every scannable metric. Check to show; drag or use the up/down arrows to
|
||||||
/// reorder. IP is always the first column and is not listed here.
|
/// reorder. IP is always the first column and is not listed here.
|
||||||
@@ -2025,6 +2423,16 @@ impl App {
|
|||||||
ID_COLUMNS => return Some(self.build_columns_dialog()),
|
ID_COLUMNS => return Some(self.build_columns_dialog()),
|
||||||
ID_COLUMNS_OK => self.apply_columns(),
|
ID_COLUMNS_OK => self.apply_columns(),
|
||||||
ID_COLUMNS_CANCEL => self.columns_dialog.close(0),
|
ID_COLUMNS_CANCEL => self.columns_dialog.close(0),
|
||||||
|
ID_PRESETS => return Some(self.build_presets_dialog()),
|
||||||
|
ID_PICSSH_OK => self.apply_pic_probe(),
|
||||||
|
ID_PICSSH_CANCEL => {
|
||||||
|
self.pending_pic_targets.clear();
|
||||||
|
self.picssh_dialog.close(0);
|
||||||
|
}
|
||||||
|
ID_PRESET_LOAD => self.apply_preset_load(),
|
||||||
|
ID_PRESET_SAVE => self.apply_preset_save(),
|
||||||
|
ID_PRESET_DELETE => self.apply_preset_delete(),
|
||||||
|
ID_PRESET_CLOSE => self.presets_dialog.close(0),
|
||||||
ID_FILTER => return Some(self.build_filter_dialog()),
|
ID_FILTER => return Some(self.build_filter_dialog()),
|
||||||
ID_FILTER_OK => self.apply_filter(),
|
ID_FILTER_OK => self.apply_filter(),
|
||||||
ID_FILTER_CANCEL => self.filter_dialog.close(0),
|
ID_FILTER_CANCEL => self.filter_dialog.close(0),
|
||||||
@@ -2125,7 +2533,7 @@ impl App {
|
|||||||
(self.kpi_slow, "Slow", "1"),
|
(self.kpi_slow, "Slow", "1"),
|
||||||
(self.kpi_not, "Not hashing", "1"),
|
(self.kpi_not, "Not hashing", "1"),
|
||||||
(self.kpi_paused, "Paused", "1"),
|
(self.kpi_paused, "Paused", "1"),
|
||||||
(self.kpi_hashrate, "Hashrate", "685 TH/s"),
|
(self.kpi_hashrate, "SHA-256 Hashrate", "685 TH"),
|
||||||
(self.kpi_power, "Est. power", "21.3 kW"),
|
(self.kpi_power, "Est. power", "21.3 kW"),
|
||||||
];
|
];
|
||||||
for (w, name, want) in want_kpis {
|
for (w, name, want) in want_kpis {
|
||||||
|
|||||||
+9
-1
@@ -10,7 +10,7 @@
|
|||||||
+pub use widgets::*;
|
+pub use widgets::*;
|
||||||
--- a/src/widgets.rs
|
--- a/src/widgets.rs
|
||||||
+++ b/src/widgets.rs
|
+++ b/src/widgets.rs
|
||||||
@@ -0,0 +1,720 @@
|
@@ -0,0 +1,728 @@
|
||||||
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
|
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
|
||||||
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
|
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
|
||||||
+// wxWidgets object tree (parents own children; nothing to free in Rust).
|
+// wxWidgets object tree (parents own children; nothing to free in Rust).
|
||||||
@@ -71,6 +71,7 @@
|
|||||||
+ pub fn wxbr_dvlc_clear(win: *mut c_void);
|
+ pub fn wxbr_dvlc_clear(win: *mut c_void);
|
||||||
+ pub fn wxbr_dvlc_row_count(win: *mut c_void) -> c_int;
|
+ pub fn wxbr_dvlc_row_count(win: *mut c_void) -> c_int;
|
||||||
+ pub fn wxbr_dvlc_set_cell(win: *mut c_void, row: usize, col: usize, value: *const c_char);
|
+ pub fn wxbr_dvlc_set_cell(win: *mut c_void, row: usize, col: usize, value: *const c_char);
|
||||||
|
+ pub fn wxbr_dvlc_set_cell_tooltip(win: *mut c_void, row: usize, col: usize, text: *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_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_col_count(win: *mut c_void) -> c_int;
|
||||||
+ pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
|
+ pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
|
||||||
@@ -495,6 +496,13 @@
|
|||||||
+ unsafe { notsafe::wxbr_dvlc_set_cell(self.0, row, col, c.as_ptr()) }
|
+ unsafe { notsafe::wxbr_dvlc_set_cell(self.0, row, col, c.as_ptr()) }
|
||||||
+ }
|
+ }
|
||||||
+
|
+
|
||||||
|
+ /// Set the hover tooltip for one cell (empty clears it). GTK only; a no-op
|
||||||
|
+ /// on other platforms until they gain per-cell tooltip support.
|
||||||
|
+ pub fn dvlc_set_cell_tooltip(&self, row: usize, col: usize, text: &str) {
|
||||||
|
+ let c = CString::new(text).unwrap_or_default();
|
||||||
|
+ unsafe { notsafe::wxbr_dvlc_set_cell_tooltip(self.0, row, col, c.as_ptr()) }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
+ pub fn dvlc_get_cell(&self, row: usize, col: usize) -> Option<String> {
|
+ pub fn dvlc_get_cell(&self, row: usize, col: usize) -> Option<String> {
|
||||||
+ let mut buf = vec![0i8; 4096];
|
+ let mut buf = vec![0i8; 4096];
|
||||||
+ let n = unsafe {
|
+ let n = unsafe {
|
||||||
|
|||||||
+102
-8
@@ -1,6 +1,6 @@
|
|||||||
--- a/cpp_src/widgets_bridge.cpp
|
--- a/cpp_src/widgets_bridge.cpp
|
||||||
+++ b/cpp_src/widgets_bridge.cpp
|
+++ b/cpp_src/widgets_bridge.cpp
|
||||||
@@ -0,0 +1,989 @@
|
@@ -0,0 +1,1083 @@
|
||||||
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
|
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
|
||||||
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
|
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
|
||||||
+// render-callback bridge (which is kept untouched).
|
+// render-callback bridge (which is kept untouched).
|
||||||
@@ -36,12 +36,21 @@
|
|||||||
+#include <cstdio>
|
+#include <cstdio>
|
||||||
+#include <map>
|
+#include <map>
|
||||||
+#include <vector>
|
+#include <vector>
|
||||||
|
+#ifdef __WXGTK__
|
||||||
|
+// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
|
||||||
|
+// enable and which cannot be done via wx mouse events on GTK (the native widget
|
||||||
|
+// grabs the pointer during a drag). Guarded so non-GTK builds are unaffected.
|
||||||
|
+#include <gtk/gtk.h>
|
||||||
|
+#endif
|
||||||
+
|
+
|
||||||
+typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
+typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
||||||
+static WxWidgetEventFn g_widget_event = nullptr;
|
+static WxWidgetEventFn g_widget_event = nullptr;
|
||||||
+
|
+
|
||||||
+// Anchor row per data-view control for rubber-band (click-drag) range select.
|
+#ifndef __WXGTK__
|
||||||
|
+// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
|
||||||
|
+// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
|
||||||
+static std::map<wxDataViewCtrl*, int> g_drag_anchor;
|
+static std::map<wxDataViewCtrl*, int> g_drag_anchor;
|
||||||
|
+#endif
|
||||||
+
|
+
|
||||||
+// Event kinds (must match Rust WxEventKind in src/widgets.rs)
|
+// Event kinds (must match Rust WxEventKind in src/widgets.rs)
|
||||||
+enum WxWidgetEventKind {
|
+enum WxWidgetEventKind {
|
||||||
@@ -71,6 +80,9 @@
|
|||||||
+ public:
|
+ public:
|
||||||
+ std::vector<wxColour> row_fg;
|
+ std::vector<wxColour> row_fg;
|
||||||
+ wxColour zebra; // odd-row background; unset (=off) unless the app sets it
|
+ wxColour zebra; // odd-row background; unset (=off) unless the app sets it
|
||||||
|
+ // Per-cell hover tooltip text, keyed by (row, model column). Used for the
|
||||||
|
+ // Errors column's full-message tooltip (see the GTK query-tooltip handler).
|
||||||
|
+ std::map<std::pair<unsigned, unsigned>, wxString> cell_tip;
|
||||||
+ bool GetAttrByRow(unsigned int row, unsigned int col,
|
+ bool GetAttrByRow(unsigned int row, unsigned int col,
|
||||||
+ wxDataViewItemAttr& attr) const override {
|
+ wxDataViewItemAttr& attr) const override {
|
||||||
+ (void)col;
|
+ (void)col;
|
||||||
@@ -453,6 +465,36 @@
|
|||||||
+ return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
|
+ return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
|
||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
|
+#ifdef __WXGTK__
|
||||||
|
+// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
|
||||||
|
+// (row, model column) under the pointer (used by the Errors column). wx does
|
||||||
|
+// not surface per-cell tooltips on wxDataViewCtrl, and mouse-motion events are
|
||||||
|
+// not delivered to wx handlers on the native GTK control, so this hooks the
|
||||||
|
+// native signal directly.
|
||||||
|
+static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keyboard,
|
||||||
|
+ GtkTooltip* tooltip, gpointer user_data) {
|
||||||
|
+ (void)keyboard;
|
||||||
|
+ wxDataViewCtrl* dv = static_cast<wxDataViewCtrl*>(user_data);
|
||||||
|
+ gint bx = 0, by = 0;
|
||||||
|
+ gtk_tree_view_convert_widget_to_bin_window_coords(GTK_TREE_VIEW(tv), x, y, &bx, &by);
|
||||||
|
+ GtkTreePath* path = nullptr;
|
||||||
|
+ GtkTreeViewColumn* gcol = nullptr;
|
||||||
|
+ if (!gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(tv), bx, by, &path, &gcol, nullptr, nullptr))
|
||||||
|
+ return FALSE;
|
||||||
|
+ gint* idx = gtk_tree_path_get_indices(path);
|
||||||
|
+ int row = idx ? idx[0] : -1;
|
||||||
|
+ gtk_tree_path_free(path);
|
||||||
|
+ if (row < 0 || !gcol) return FALSE;
|
||||||
|
+ wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
|
||||||
|
+ if (!wxcol) return FALSE;
|
||||||
|
+ AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
|
||||||
|
+ auto it = store->cell_tip.find({(unsigned)row, wxcol->GetModelColumn()});
|
||||||
|
+ if (it == store->cell_tip.end() || it->second.IsEmpty()) return FALSE;
|
||||||
|
+ gtk_tooltip_set_text(tooltip, it->second.utf8_str());
|
||||||
|
+ return TRUE;
|
||||||
|
+}
|
||||||
|
+#endif
|
||||||
|
+
|
||||||
+void* wxbr_dvlc(void* parent) {
|
+void* wxbr_dvlc(void* parent) {
|
||||||
+ // Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
|
+ // Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
|
||||||
+ // checkbox column. A custom AttrListStore backs it so rows can be coloured by
|
+ // checkbox column. A custom AttrListStore backs it so rows can be coloured by
|
||||||
@@ -490,10 +532,25 @@
|
|||||||
+ dv->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) {
|
+ dv->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) {
|
||||||
+ if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0);
|
+ if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0);
|
||||||
+ });
|
+ });
|
||||||
+ // Rubber-band (click-drag) range selection: wxDataViewCtrl has none natively
|
+ // Rubber-band (click-drag) range selection. wxDataViewCtrl has none natively.
|
||||||
+ // (only ctrl/shift-click), so track it here. LEFT_DOWN records the anchor row
|
+#ifdef __WXGTK__
|
||||||
+ // (and lets the native handler select it); dragging with the button down
|
+ // On GTK the control wraps a GtkTreeView, which supports native rubber-band
|
||||||
+ // extends the selection to the row under the cursor.
|
+ // selection -- just not enabled by wx. Enable it directly. (wx delivers no
|
||||||
|
+ // MOTION events during the native drag, so the mouse-event fallback below is
|
||||||
|
+ // inapplicable on GTK.)
|
||||||
|
+ {
|
||||||
|
+ GtkWidget* tv = dv->GtkGetTreeView();
|
||||||
|
+ if (tv) {
|
||||||
|
+ gtk_tree_view_set_rubber_banding(GTK_TREE_VIEW(tv), TRUE);
|
||||||
|
+ // Per-cell hover tooltips (Errors column) via the native signal.
|
||||||
|
+ gtk_widget_set_has_tooltip(tv, TRUE);
|
||||||
|
+ g_signal_connect(tv, "query-tooltip", G_CALLBACK(dvlc_query_tooltip), dv);
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+#else
|
||||||
|
+ // Non-GTK fallback: track a drag anchor and extend the selection to the row
|
||||||
|
+ // under the cursor. LEFT_DOWN records the anchor (and lets the native handler
|
||||||
|
+ // select it); dragging with the button down selects the inclusive range.
|
||||||
+ dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
|
+ dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
|
||||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||||
+ if (!dv) { e.Skip(); return; }
|
+ if (!dv) { e.Skip(); return; }
|
||||||
@@ -534,6 +591,7 @@
|
|||||||
+ if (dv) g_drag_anchor.erase(dv);
|
+ if (dv) g_drag_anchor.erase(dv);
|
||||||
+ e.Skip();
|
+ e.Skip();
|
||||||
+ });
|
+ });
|
||||||
|
+#endif
|
||||||
+ // Row activation (double-click / Enter): report the row + column so the app
|
+ // Row activation (double-click / Enter): report the row + column so the app
|
||||||
+ // can, e.g., open the miner's IP in a browser.
|
+ // can, e.g., open the miner's IP in a browser.
|
||||||
+ dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
|
+ dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
|
||||||
@@ -605,6 +663,18 @@
|
|||||||
+ AttrListStore* store = dvlc_store(win);
|
+ AttrListStore* store = dvlc_store(win);
|
||||||
+ store->DeleteAllItems();
|
+ store->DeleteAllItems();
|
||||||
+ store->row_fg.clear();
|
+ store->row_fg.clear();
|
||||||
|
+ store->cell_tip.clear();
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// Set (or clear, with an empty string) the hover tooltip for one cell,
|
||||||
|
+// addressed by (row, model column). Used for the Errors column's full text.
|
||||||
|
+void wxbr_dvlc_set_cell_tooltip(void* win, unsigned row, unsigned col, const char* text) {
|
||||||
|
+ AttrListStore* store = dvlc_store(win);
|
||||||
|
+ if (text && text[0]) {
|
||||||
|
+ store->cell_tip[{row, col}] = wxString::FromUTF8(text);
|
||||||
|
+ } else {
|
||||||
|
+ store->cell_tip.erase({row, col});
|
||||||
|
+ }
|
||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
+// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
|
+// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
|
||||||
@@ -631,9 +701,11 @@
|
|||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
+// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
|
+// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
|
||||||
+// scroll position after a refill). Out-of-range rows are ignored.
|
+// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
|
||||||
|
+// itself asserts on row >= count, so the bound MUST be checked before calling.
|
||||||
+void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
|
+void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
|
||||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
|
+ if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
|
||||||
+ wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
|
+ wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
|
||||||
+ if (item.IsOk()) dv->EnsureVisible(item);
|
+ if (item.IsOk()) dv->EnsureVisible(item);
|
||||||
+}
|
+}
|
||||||
@@ -705,6 +777,25 @@
|
|||||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
+ unsigned n = dv->GetColumnCount();
|
+ unsigned n = dv->GetColumnCount();
|
||||||
+ if (pos < 0 || (unsigned)pos >= n) return -1;
|
+ if (pos < 0 || (unsigned)pos >= n) return -1;
|
||||||
|
+#ifdef __WXGTK__
|
||||||
|
+ // wxGTK's GetColumnPosition() does NOT reflect a native GtkTreeView column
|
||||||
|
+ // drag, so after the user reorders columns it reports the creation order and
|
||||||
|
+ // the reorder is silently lost. Read the real display order from the
|
||||||
|
+ // GtkTreeView instead, then map the column back to its wx creation index.
|
||||||
|
+ GtkWidget* tvw = dv->GtkGetTreeView();
|
||||||
|
+ if (tvw) {
|
||||||
|
+ GList* cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(tvw)); // display order
|
||||||
|
+ GtkTreeViewColumn* gcol = (GtkTreeViewColumn*)g_list_nth_data(cols, (guint)pos);
|
||||||
|
+ g_list_free(cols);
|
||||||
|
+ if (gcol) {
|
||||||
|
+ wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
|
||||||
|
+ for (unsigned i = 0; i < n; i++) {
|
||||||
|
+ if (dv->GetColumn(i) == wxcol) return (int)i;
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ return -1;
|
||||||
|
+ }
|
||||||
|
+#endif
|
||||||
+ for (unsigned i = 0; i < n; i++) {
|
+ for (unsigned i = 0; i < n; i++) {
|
||||||
+ wxDataViewColumn* c = dv->GetColumn(i);
|
+ wxDataViewColumn* c = dv->GetColumn(i);
|
||||||
+ if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
|
+ if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
|
||||||
@@ -736,9 +827,11 @@
|
|||||||
+void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
|
+void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
|
||||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||||
|
+ int count = (int)dvlc_store(win)->GetItemCount();
|
||||||
+ dv->UnselectAll();
|
+ dv->UnselectAll();
|
||||||
+ for (int i = 0; i < n; i++) {
|
+ for (int i = 0; i < n; i++) {
|
||||||
+ if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
|
+ // GetItem() asserts on an out-of-range row, so bound both ends.
|
||||||
|
+ if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
|
||||||
+ }
|
+ }
|
||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
@@ -757,6 +850,7 @@
|
|||||||
+ if (row < 0) return;
|
+ if (row < 0) return;
|
||||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||||
|
+ if (row >= (long)dvlc_store(win)->GetItemCount()) return;
|
||||||
+ dv->Select(m->GetItem((unsigned)row));
|
+ dv->Select(m->GetItem((unsigned)row));
|
||||||
+}
|
+}
|
||||||
+
|
+
|
||||||
|
|||||||
+101
-7
@@ -33,12 +33,21 @@
|
|||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
#ifdef __WXGTK__
|
||||||
|
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
|
||||||
|
// enable and which cannot be done via wx mouse events on GTK (the native widget
|
||||||
|
// grabs the pointer during a drag). Guarded so non-GTK builds are unaffected.
|
||||||
|
#include <gtk/gtk.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
||||||
static WxWidgetEventFn g_widget_event = nullptr;
|
static WxWidgetEventFn g_widget_event = nullptr;
|
||||||
|
|
||||||
// Anchor row per data-view control for rubber-band (click-drag) range select.
|
#ifndef __WXGTK__
|
||||||
|
// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
|
||||||
|
// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
|
||||||
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
|
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
|
||||||
|
#endif
|
||||||
|
|
||||||
// Event kinds (must match Rust WxEventKind in src/widgets.rs)
|
// Event kinds (must match Rust WxEventKind in src/widgets.rs)
|
||||||
enum WxWidgetEventKind {
|
enum WxWidgetEventKind {
|
||||||
@@ -68,6 +77,9 @@ class AttrListStore : public wxDataViewListStore {
|
|||||||
public:
|
public:
|
||||||
std::vector<wxColour> row_fg;
|
std::vector<wxColour> row_fg;
|
||||||
wxColour zebra; // odd-row background; unset (=off) unless the app sets it
|
wxColour zebra; // odd-row background; unset (=off) unless the app sets it
|
||||||
|
// Per-cell hover tooltip text, keyed by (row, model column). Used for the
|
||||||
|
// Errors column's full-message tooltip (see the GTK query-tooltip handler).
|
||||||
|
std::map<std::pair<unsigned, unsigned>, wxString> cell_tip;
|
||||||
bool GetAttrByRow(unsigned int row, unsigned int col,
|
bool GetAttrByRow(unsigned int row, unsigned int col,
|
||||||
wxDataViewItemAttr& attr) const override {
|
wxDataViewItemAttr& attr) const override {
|
||||||
(void)col;
|
(void)col;
|
||||||
@@ -450,6 +462,36 @@ static AttrListStore* dvlc_store(void* win) {
|
|||||||
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
|
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#ifdef __WXGTK__
|
||||||
|
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
|
||||||
|
// (row, model column) under the pointer (used by the Errors column). wx does
|
||||||
|
// not surface per-cell tooltips on wxDataViewCtrl, and mouse-motion events are
|
||||||
|
// not delivered to wx handlers on the native GTK control, so this hooks the
|
||||||
|
// native signal directly.
|
||||||
|
static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keyboard,
|
||||||
|
GtkTooltip* tooltip, gpointer user_data) {
|
||||||
|
(void)keyboard;
|
||||||
|
wxDataViewCtrl* dv = static_cast<wxDataViewCtrl*>(user_data);
|
||||||
|
gint bx = 0, by = 0;
|
||||||
|
gtk_tree_view_convert_widget_to_bin_window_coords(GTK_TREE_VIEW(tv), x, y, &bx, &by);
|
||||||
|
GtkTreePath* path = nullptr;
|
||||||
|
GtkTreeViewColumn* gcol = nullptr;
|
||||||
|
if (!gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(tv), bx, by, &path, &gcol, nullptr, nullptr))
|
||||||
|
return FALSE;
|
||||||
|
gint* idx = gtk_tree_path_get_indices(path);
|
||||||
|
int row = idx ? idx[0] : -1;
|
||||||
|
gtk_tree_path_free(path);
|
||||||
|
if (row < 0 || !gcol) return FALSE;
|
||||||
|
wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
|
||||||
|
if (!wxcol) return FALSE;
|
||||||
|
AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
|
||||||
|
auto it = store->cell_tip.find({(unsigned)row, wxcol->GetModelColumn()});
|
||||||
|
if (it == store->cell_tip.end() || it->second.IsEmpty()) return FALSE;
|
||||||
|
gtk_tooltip_set_text(tooltip, it->second.utf8_str());
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
void* wxbr_dvlc(void* parent) {
|
void* wxbr_dvlc(void* parent) {
|
||||||
// Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
|
// Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
|
||||||
// checkbox column. A custom AttrListStore backs it so rows can be coloured by
|
// checkbox column. A custom AttrListStore backs it so rows can be coloured by
|
||||||
@@ -487,10 +529,25 @@ void* wxbr_dvlc(void* parent) {
|
|||||||
dv->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) {
|
dv->Bind(wxEVT_DATAVIEW_COLUMN_REORDERED, [](wxDataViewEvent&) {
|
||||||
if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0);
|
if (g_widget_event) g_widget_event(WxEV_DVLC_REORDERED, 0, 0);
|
||||||
});
|
});
|
||||||
// Rubber-band (click-drag) range selection: wxDataViewCtrl has none natively
|
// Rubber-band (click-drag) range selection. wxDataViewCtrl has none natively.
|
||||||
// (only ctrl/shift-click), so track it here. LEFT_DOWN records the anchor row
|
#ifdef __WXGTK__
|
||||||
// (and lets the native handler select it); dragging with the button down
|
// On GTK the control wraps a GtkTreeView, which supports native rubber-band
|
||||||
// extends the selection to the row under the cursor.
|
// selection -- just not enabled by wx. Enable it directly. (wx delivers no
|
||||||
|
// MOTION events during the native drag, so the mouse-event fallback below is
|
||||||
|
// inapplicable on GTK.)
|
||||||
|
{
|
||||||
|
GtkWidget* tv = dv->GtkGetTreeView();
|
||||||
|
if (tv) {
|
||||||
|
gtk_tree_view_set_rubber_banding(GTK_TREE_VIEW(tv), TRUE);
|
||||||
|
// Per-cell hover tooltips (Errors column) via the native signal.
|
||||||
|
gtk_widget_set_has_tooltip(tv, TRUE);
|
||||||
|
g_signal_connect(tv, "query-tooltip", G_CALLBACK(dvlc_query_tooltip), dv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
// Non-GTK fallback: track a drag anchor and extend the selection to the row
|
||||||
|
// under the cursor. LEFT_DOWN records the anchor (and lets the native handler
|
||||||
|
// select it); dragging with the button down selects the inclusive range.
|
||||||
dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
|
dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
|
||||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||||
if (!dv) { e.Skip(); return; }
|
if (!dv) { e.Skip(); return; }
|
||||||
@@ -531,6 +588,7 @@ void* wxbr_dvlc(void* parent) {
|
|||||||
if (dv) g_drag_anchor.erase(dv);
|
if (dv) g_drag_anchor.erase(dv);
|
||||||
e.Skip();
|
e.Skip();
|
||||||
});
|
});
|
||||||
|
#endif
|
||||||
// Row activation (double-click / Enter): report the row + column so the app
|
// Row activation (double-click / Enter): report the row + column so the app
|
||||||
// can, e.g., open the miner's IP in a browser.
|
// can, e.g., open the miner's IP in a browser.
|
||||||
dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
|
dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
|
||||||
@@ -602,6 +660,18 @@ void wxbr_dvlc_clear(void* win) {
|
|||||||
AttrListStore* store = dvlc_store(win);
|
AttrListStore* store = dvlc_store(win);
|
||||||
store->DeleteAllItems();
|
store->DeleteAllItems();
|
||||||
store->row_fg.clear();
|
store->row_fg.clear();
|
||||||
|
store->cell_tip.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set (or clear, with an empty string) the hover tooltip for one cell,
|
||||||
|
// addressed by (row, model column). Used for the Errors column's full text.
|
||||||
|
void wxbr_dvlc_set_cell_tooltip(void* win, unsigned row, unsigned col, const char* text) {
|
||||||
|
AttrListStore* store = dvlc_store(win);
|
||||||
|
if (text && text[0]) {
|
||||||
|
store->cell_tip[{row, col}] = wxString::FromUTF8(text);
|
||||||
|
} else {
|
||||||
|
store->cell_tip.erase({row, col});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
|
// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
|
||||||
@@ -628,9 +698,11 @@ int wxbr_dvlc_get_top_row(void* win) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
|
// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
|
||||||
// scroll position after a refill). Out-of-range rows are ignored.
|
// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
|
||||||
|
// itself asserts on row >= count, so the bound MUST be checked before calling.
|
||||||
void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
|
void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
|
||||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
|
if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
|
||||||
wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
|
wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
|
||||||
if (item.IsOk()) dv->EnsureVisible(item);
|
if (item.IsOk()) dv->EnsureVisible(item);
|
||||||
}
|
}
|
||||||
@@ -702,6 +774,25 @@ int wxbr_dvlc_col_at_pos(void* win, int pos) {
|
|||||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
unsigned n = dv->GetColumnCount();
|
unsigned n = dv->GetColumnCount();
|
||||||
if (pos < 0 || (unsigned)pos >= n) return -1;
|
if (pos < 0 || (unsigned)pos >= n) return -1;
|
||||||
|
#ifdef __WXGTK__
|
||||||
|
// wxGTK's GetColumnPosition() does NOT reflect a native GtkTreeView column
|
||||||
|
// drag, so after the user reorders columns it reports the creation order and
|
||||||
|
// the reorder is silently lost. Read the real display order from the
|
||||||
|
// GtkTreeView instead, then map the column back to its wx creation index.
|
||||||
|
GtkWidget* tvw = dv->GtkGetTreeView();
|
||||||
|
if (tvw) {
|
||||||
|
GList* cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(tvw)); // display order
|
||||||
|
GtkTreeViewColumn* gcol = (GtkTreeViewColumn*)g_list_nth_data(cols, (guint)pos);
|
||||||
|
g_list_free(cols);
|
||||||
|
if (gcol) {
|
||||||
|
wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
|
||||||
|
for (unsigned i = 0; i < n; i++) {
|
||||||
|
if (dv->GetColumn(i) == wxcol) return (int)i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
for (unsigned i = 0; i < n; i++) {
|
for (unsigned i = 0; i < n; i++) {
|
||||||
wxDataViewColumn* c = dv->GetColumn(i);
|
wxDataViewColumn* c = dv->GetColumn(i);
|
||||||
if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
|
if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
|
||||||
@@ -733,9 +824,11 @@ int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
|
|||||||
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
|
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
|
||||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||||
|
int count = (int)dvlc_store(win)->GetItemCount();
|
||||||
dv->UnselectAll();
|
dv->UnselectAll();
|
||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
|
// GetItem() asserts on an out-of-range row, so bound both ends.
|
||||||
|
if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -754,6 +847,7 @@ void wxbr_dvlc_select_row(void* win, long row) {
|
|||||||
if (row < 0) return;
|
if (row < 0) return;
|
||||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||||
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||||
|
if (row >= (long)dvlc_store(win)->GetItemCount()) return;
|
||||||
dv->Select(m->GetItem((unsigned)row));
|
dv->Select(m->GetItem((unsigned)row));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ mod notsafe {
|
|||||||
pub fn wxbr_dvlc_clear(win: *mut c_void);
|
pub fn wxbr_dvlc_clear(win: *mut c_void);
|
||||||
pub fn wxbr_dvlc_row_count(win: *mut c_void) -> c_int;
|
pub fn wxbr_dvlc_row_count(win: *mut c_void) -> c_int;
|
||||||
pub fn wxbr_dvlc_set_cell(win: *mut c_void, row: usize, col: usize, value: *const c_char);
|
pub fn wxbr_dvlc_set_cell(win: *mut c_void, row: usize, col: usize, value: *const c_char);
|
||||||
|
pub fn wxbr_dvlc_set_cell_tooltip(win: *mut c_void, row: usize, col: usize, text: *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_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_col_count(win: *mut c_void) -> c_int;
|
||||||
pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
|
pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
|
||||||
@@ -482,6 +483,13 @@ impl Widget {
|
|||||||
unsafe { notsafe::wxbr_dvlc_set_cell(self.0, row, col, c.as_ptr()) }
|
unsafe { notsafe::wxbr_dvlc_set_cell(self.0, row, col, c.as_ptr()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set the hover tooltip for one cell (empty clears it). GTK only; a no-op
|
||||||
|
/// on other platforms until they gain per-cell tooltip support.
|
||||||
|
pub fn dvlc_set_cell_tooltip(&self, row: usize, col: usize, text: &str) {
|
||||||
|
let c = CString::new(text).unwrap_or_default();
|
||||||
|
unsafe { notsafe::wxbr_dvlc_set_cell_tooltip(self.0, row, col, c.as_ptr()) }
|
||||||
|
}
|
||||||
|
|
||||||
pub fn dvlc_get_cell(&self, row: usize, col: usize) -> Option<String> {
|
pub fn dvlc_get_cell(&self, row: usize, col: usize) -> Option<String> {
|
||||||
let mut buf = vec![0i8; 4096];
|
let mut buf = vec![0i8; 4096];
|
||||||
let n = unsafe {
|
let n = unsafe {
|
||||||
|
|||||||
Reference in New Issue
Block a user