Compare commits

...
4 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 9b5d811b1e GUI round 9 (batch 2): KPI box layout, bottom-right error indicator, algorithm filter + hashrate cycling
Round-9 UI items #5, #6, #7 and the #9 algorithm-cycle follow-on.

#6 KPI boxes: switch the header from a wrap sizer to a horizontal box
sizer with every card at proportion 1 + EXPAND, so the cards are always
equal width and grow to span the full window; a per-card min size
(116x62) floors them at their largest content. Fix the filter-alignment
drift by re-running each card's sizer in refresh_kpis after set_label
(the centring spacers now recompute around the new value width). The
active-filter highlight now paints the card panel and both its texts, so
the whole box tints instead of only the strip behind the text. Bind the
card click on the value and label static texts too (a click on the number
or caption registers the quick-filter, not just the card gap).

#5 error indicator: add a second, colour-tinted status-bar field pinned
to the bottom-right corner (wxbr_status_indicator_init/set in the widget
bridge; a wxStaticText repositioned into the right field on resize). Scan
and apply outcomes route here without overwriting the left scan-status
text: a total apply failure and a scan failure show red, a partial apply
failure amber, full success clears it; a new scan/action clears any stale
message.

#7 algorithm filter: the Filter dialog now offers every column (via a new
ViewState::filter_columns) rather than only the visible ones, so Algorithm
-- and any other hidden metric -- can be filtered without first un-hiding
its column. Filters already match on the plain model cell, independent of
visibility.

#9 hashrate cycling: compute per-algorithm hashrate totals in compute_kpis
(Kpis::hashrate_by_algo, ordered by total). The hashrate KPI card shows
the selected algorithm's total under a "<Algo> Hashrate" caption and
cycles through the running algorithms when clicked (a no-op with a single
algorithm). SHA256 renders as "SHA-256".

Bridge provenance patches 0002/0003 regenerated to match the -patched tree.
Compile-checked (release + tests); 74 offline tests pass; headless
self-test PASS; screenshot-verified equal-width cards, full-box highlight,
click-through-text, and centred values after filtering.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-18 11:09:50 -06:00
noahandClaude Opus 4.8 77399bdd06 GUI round 9 (batch 1): column-reorder persistence, post-action refresh, algorithm column, hashrate KPI label
- #1 Column reorder now persists (incl. after sorting a moved column). On wxGTK,
  GetColumnPosition() does not reflect a native GtkTreeView column drag, so the
  reorder was read as a no-op and the rebuild snapped columns back. dvlc_col_at_pos
  now reads the real display order from the GtkTreeView (gtk_tree_view_get_columns
  + GTKColumnToWX) on __WXGTK__, falling back to GetColumnPosition elsewhere.
- #2 A right-click config action (e.g. Flash lights) now re-probes the miners it
  targeted when it finishes, so the change shows in the table (skipped after a
  flash, since the unit is rebooting). New App.action_targets.
- #7 New Algorithm column (from asic-rs hashrate.algo: SHA256/Scrypt/Equihash/...),
  categorical so it is filterable via the value checklist.
- #9 SHA-256 Hashrate KPI: card relabelled "SHA-256 Hashrate" and the value drops
  the "/s" ("685 TH", "1.2 PH"). (Per-algorithm click-cycling deferred.)

Note on #8 (Z15 shows T not k): our formatting already derives the SI prefix from
the base value (si_mantissa), so a wrong 'T' means asic-rs reports the wrong unit
for that Equihash model -- an asic-rs backend fix that needs a live Z15 to verify.

cargo check --release --tests clean; patch 0003 regenerated + validated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-18 10:41:21 -06:00
noahandClaude Opus 4.8 408b7d12b4 GUI: real access/lock-state detection via credentialed digest probe
asic-rs has no lock-state signal (a wrong-password miner just silently returns
fewer fields, because the collector drops the 401). This builds the real check
ON TOP of asic-rs:

- access_probe.rs: a NON-mutating, digest-authenticated GET to a privileged
  endpoint (Antminer get_miner_conf.cgi, read-only). The HTTP status is decisive
  -- 200 = credentials authenticate (writable -> unlocked), 401/403 = rejected
  (view-only -> locked); anything else -> indeterminate. Pure classifier +
  unit tests; shells out to curl --digest (no HTTP crate) so the offline build
  is unaffected.
- Right-click "Check access (auth)" on the selected miners runs start_access_probe
  on a background thread using the saved scan (web) credentials (default root/root),
  updating write_locked in the rows as results arrive. Fake-scan mode returns
  deterministic demo results. Guarded against a flash / concurrent probe.

Replaces the previous capability-based inference for the miners the user
explicitly checks. cargo check --release --tests clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-18 10:32:44 -06:00
noahandClaude Opus 4.8 50cd463bee GUI fix: guard out-of-range dvlc GetItem (crash selecting rows after refresh)
Round-9 #10: selecting miners could trip
`datavcmn.cpp: assert "row < m_hash.GetCount()" failed in GetItem(): invalid
index` and crash. wxDataViewIndexListModel::GetItem() asserts on an out-of-range
row, and three bridge helpers called it with an index that can go stale when the
row set shrinks (a filter, or a scan that returns fewer rows): wxbr_dvlc_
ensure_visible (the round-8 scroll-hold, unguarded), wxbr_dvlc_select_rows and
wxbr_dvlc_select_row (only lower-bounded). All three now bound the row against
the store's item count before calling GetItem, so a stale/empty index is a
no-op instead of a crash.

Local wx-rs bridge compile clean; patch 0003 regenerated + validated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-18 10:29:14 -06:00
10 changed files with 677 additions and 36 deletions
+115
View File
@@ -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);
}
}
+2 -1
View File
@@ -106,8 +106,9 @@ impl Board {
tuning: self.mining,
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).
algorithm: "SHA256".to_string(),
control_board: if self.model.contains("S17") {
"Xilinx".to_string()
} else if self.model.contains("S19j") || self.model.contains("S19k") {
+1
View File
@@ -1,6 +1,7 @@
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
mod access_probe;
mod credentials;
mod fixtures;
mod model;
+39 -1
View File
@@ -243,6 +243,8 @@ pub struct MinerRow {
pub firmware: String,
pub api_version: 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
/// the network, so it is a best-effort inference (model-string heuristic):
/// `None` = unknown, `Some(true)` = PIC, `Some(false)` = noPIC. True
@@ -369,6 +371,7 @@ pub enum Column {
Serial,
ApiVersion,
ControlBoard,
Algorithm,
Pic,
Locked,
Error,
@@ -389,7 +392,7 @@ pub enum Column {
/// Every column, in registry order. Ip first, then the default-visible set
/// (UI-SPEC order), then all remaining metrics.
pub const ALL_COLUMNS: [Column; 38] = [
pub const ALL_COLUMNS: [Column; 39] = [
Column::Ip,
Column::Hashrate,
Column::Power,
@@ -412,6 +415,7 @@ pub const ALL_COLUMNS: [Column; 38] = [
Column::Serial,
Column::ApiVersion,
Column::ControlBoard,
Column::Algorithm,
Column::Pic,
Column::Locked,
Column::Error,
@@ -467,6 +471,7 @@ impl Column {
Column::Serial => "Serial",
Column::ApiVersion => "API ver",
Column::ControlBoard => "Control board",
Column::Algorithm => "Algorithm",
Column::Pic => "PIC",
Column::Locked => "Access",
Column::Error => "Errors",
@@ -503,6 +508,7 @@ impl Column {
Column::Mac | Column::Hostname | Column::Serial => 150,
Column::ApiVersion | Column::Light => 90,
Column::ControlBoard => 130,
Column::Algorithm => 100,
Column::Pic => 70,
Column::Locked => 90,
Column::Error => 160,
@@ -644,6 +650,7 @@ impl Column {
Column::Serial => r.serial.clone(),
Column::ApiVersion => r.api_version.clone(),
Column::ControlBoard => r.control_board.clone(),
Column::Algorithm => r.algorithm.clone(),
Column::Pic => match r.pic_present {
Some(true) => "PIC".to_string(),
Some(false) => "noPIC".to_string(),
@@ -783,6 +790,16 @@ impl ViewState {
.collect()
}
/// Every column available to filter on, independent of visibility: a filter
/// matches a row by that column's cell text whether or not the column is
/// shown, so (e.g.) Algorithm can be filtered without first un-hiding it.
/// Ip first, then the registry order.
pub fn filter_columns(&self) -> Vec<Column> {
let mut v = vec![Column::Ip];
v.extend(self.order.iter().copied().filter(|c| *c != Column::Ip));
v
}
pub fn is_fixed(&self, c: Column) -> bool {
c == Column::Ip
}
@@ -852,6 +869,11 @@ pub struct Kpis {
pub paused: usize,
pub total_hashrate_ths: f64,
pub total_power_w: f64,
/// Per-algorithm hashrate totals (algorithm name, total TH/s), only for
/// algorithms actually producing hashrate, ordered by total descending then
/// name. The hashrate KPI card cycles through these when more than one
/// algorithm is running in the fleet.
pub hashrate_by_algo: Vec<(String, f64)>,
}
pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
@@ -863,7 +885,11 @@ pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
paused: 0,
total_hashrate_ths: 0.0,
total_power_w: 0.0,
hashrate_by_algo: Vec::new(),
};
// Accumulate per-algorithm totals in an insertion-ordered list (fleets have
// a handful of algorithms at most, so a linear scan is cheaper than a map).
let mut by_algo: Vec<(String, f64)> = Vec::new();
for &i in view_idx {
let r = &rows[i];
// Bucket by the same precedence status() uses, so the KPI header can
@@ -876,7 +902,19 @@ pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
}
k.total_hashrate_ths += r.hashrate_ths;
k.total_power_w += r.power_w;
if r.hashrate_ths > 0.0 {
// Fall back to "SHA256" when a miner didn't report its algorithm, so
// a producing miner is never dropped from the per-algorithm cycle.
let algo = if r.algorithm.is_empty() { "SHA256" } else { r.algorithm.as_str() };
match by_algo.iter_mut().find(|(a, _)| a == algo) {
Some((_, t)) => *t += r.hashrate_ths,
None => by_algo.push((algo.to_string(), r.hashrate_ths)),
}
}
}
// Stable order: largest total first, ties broken alphabetically.
by_algo.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
k.hashrate_by_algo = by_algo;
k
}
+80
View File
@@ -498,6 +498,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.iter()
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
.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 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();
@@ -525,6 +526,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
ip: data.ip.to_string(),
selected: false,
caps,
algorithm,
pic_present,
write_locked,
errors,
@@ -988,6 +990,84 @@ pub fn start_pic_probe(
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)]
mod tests {
use super::*;
+252 -28
View File
@@ -40,6 +40,8 @@ const ID_KPI_HASHING: i32 = 150;
const ID_KPI_SLOW: i32 = 151;
const ID_KPI_NOT: i32 = 152;
const ID_KPI_PAUSED: i32 = 153;
// Click the hashrate KPI card to cycle through per-algorithm hashrate totals.
const ID_KPI_HASHRATE: i32 = 154;
// Right-click context-menu item ids.
const ID_CTX_OPEN: i32 = 720;
const ID_CTX_REFRESH: i32 = 732;
@@ -53,6 +55,7 @@ const ID_CTX_TUNING: i32 = 727;
const ID_CTX_POWER: i32 = 728;
const ID_CTX_RESTART: i32 = 729;
const ID_CTX_PIC_PROBE: i32 = 730;
const ID_CTX_ACCESS_PROBE: i32 = 731;
// SSH PIC-probe credentials dialog.
const ID_PICSSH_OK: i32 = 780;
const ID_PICSSH_CANCEL: i32 = 781;
@@ -107,6 +110,15 @@ fn luminance(c: (u8, u8, u8)) -> f32 {
0.299 * c.0 as f32 + 0.587 * c.1 as f32 + 0.114 * c.2 as f32
}
/// Human-facing algorithm name for the hashrate KPI label. asic-rs renders the
/// SHA-256 variant as "SHA256"; everything else already reads well as-is.
fn pretty_algo(algo: &str) -> String {
match algo {
"SHA256" => "SHA-256".to_string(),
other => other.to_string(),
}
}
fn nudge(c: (u8, u8, u8), d: i32) -> (u8, u8, u8) {
let f = |v: u8| (v as i32 + d).clamp(0, 255) as u8;
(f(c.0), f(c.1), f(c.2))
@@ -285,6 +297,13 @@ pub struct App {
kpi_not: Widget,
kpi_paused: Widget,
kpi_hashrate: Widget,
// The hashrate card's caption label, retitled to "<Algo> Hashrate" as the
// per-algorithm cycle advances (the card itself is re-laid-out with the rest
// in refresh_kpis).
kpi_hashrate_lbl: Widget,
// Which per-algorithm total the hashrate card is currently showing; clicking
// the card advances it, wrapping around the fleet's running algorithms.
hashrate_algo_idx: usize,
kpi_power: Widget,
progress: Widget,
pub table: Option<Widget>,
@@ -309,10 +328,11 @@ pub struct App {
pal: Palette,
kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)>,
// The 4 status KPI cards that double as quick-filters: (status text, its
// ButtonClicked id, its card panel -- for binding the click and for
// tinting the active one). `active_kpi_filter` is set iff view.filters
// holds exactly that single-value Status filter.
kpi_filter_cards: [(&'static str, i32, Widget); 4],
// ButtonClicked id, card panel, value text, label text). The three widgets
// are all painted for the active-filter highlight (so the whole box tints,
// not just the panel behind the text). `active_kpi_filter` is set iff
// view.filters holds exactly that single-value Status filter.
kpi_filter_cards: [(&'static str, i32, Widget, Widget, Widget); 4],
active_kpi_filter: Option<&'static str>,
// A context menu built on right-click, popped up outside the App borrow.
pending_popup: Option<(Widget, Widget)>,
@@ -326,6 +346,9 @@ pub struct App {
action_is_power: bool,
action_total: usize,
action_done: usize,
// IPs the current config action targets, re-probed after it completes so the
// table reflects the change (e.g. the identify light toggling).
action_targets: Vec<String>,
// A confirmation dialog for disruptive actions, plus its pending target.
confirm_dialog: Widget,
pending_confirm: Option<(Vec<String>, scan::ConfigAction)>,
@@ -348,6 +371,8 @@ pub struct App {
creds_dialog: Widget,
creds_user_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)>,
@@ -392,17 +417,18 @@ pub fn build(frame: Widget) -> App {
// KPI header: a row of equal-width cards, each a big value over a small
// label. Health KPIs are colour-coded (green/amber/red); hashrate uses the
// accent colour so totals stand apart from counts.
// wrap_sizer (not box_sizer): at phone-ish widths the cards reflow onto a
// second line instead of squeezing/clipping.
let kpi_row = Widget::wrap_sizer(false);
// Horizontal box sizer with every card at proportion 1 + EXPAND, so the
// cards are always equal width AND grow to span the full window; a per-card
// min size floors them at their largest content's width.
let kpi_row = Widget::box_sizer(false);
let mut kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)> = Vec::new();
let mut mk_card = |label: &str, kind: ColorKind| -> (Widget, Widget) {
let vc = kind_color(&pal, kind);
let card = Widget::panel(panel);
card.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
// Uniform size so every KPI box is identical regardless of its content
// (wide enough for the largest value, e.g. "685 TH/s" / "21.3 kW").
card.set_min_size(150, 62);
// Min-content floor (the widest label/value); cards grow equally past
// this to fill the window (proportion 1 + EXPAND on add).
card.set_min_size(116, 62);
let cs = Widget::box_sizer(true);
let value = Widget::static_text(card, "0");
value.set_font_size(19);
@@ -427,7 +453,7 @@ pub fn build(frame: Widget) -> App {
cs.add_sizer(centre(lbl), 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_BOTTOM | sf::BORDER_RIGHT, 8);
cs.add_stretch(1);
cs.set_sizer_on(card);
kpi_row.add(card, 0, sf::BORDER_ALL, 4);
kpi_row.add(card, 1, sf::EXPAND | sf::BORDER_ALL, 4);
kpi_cards.push((card, value, lbl, kind));
(card, value)
};
@@ -436,19 +462,37 @@ pub fn build(frame: Widget) -> App {
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber);
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red);
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);
drop(mk_card);
// The 4 status cards double as quick-filters: clicking one narrows the
// table to that status (see `toggle_kpi_filter`).
let kpi_filter_cards: [(&'static str, i32, Widget); 4] = [
("hashing", ID_KPI_HASHING, card_hashing),
("slow", ID_KPI_SLOW, card_slow),
("not hashing", ID_KPI_NOT, card_not),
("paused", ID_KPI_PAUSED, card_paused),
let _ = (card_hashing, card_slow, card_not, card_paused);
// The hashrate card is kpi_cards[5] in build order (Total, Hashing, Slow,
// Not, Paused, Hashrate, Power); its caption is retitled per algorithm.
let kpi_hashrate_lbl = kpi_cards[5].2;
// The hashrate card cycles per-algorithm totals on click; bind the card and
// both its texts (so a click on the number or the label registers too).
card_hashrate.bind_click(ID_KPI_HASHRATE);
kpi_hashrate.bind_click(ID_KPI_HASHRATE);
kpi_hashrate_lbl.bind_click(ID_KPI_HASHRATE);
// The 4 status cards double as quick-filters: clicking one narrows the table
// to that status (see `toggle_kpi_filter`). They are kpi_cards[1..=4] in this
// order. Bind the click on the card AND its value/label texts (a click on the
// text must register too), and keep all three widgets so the highlight can
// fill the whole box, not just the panel behind the text.
let filter_ids = [
("hashing", ID_KPI_HASHING),
("slow", ID_KPI_SLOW),
("not hashing", ID_KPI_NOT),
("paused", ID_KPI_PAUSED),
];
for &(_, id, card) in &kpi_filter_cards {
let mut kpi_filter_cards: [(&'static str, i32, Widget, Widget, Widget); 4] =
[("", 0, panel, panel, panel); 4];
for (i, &(status, id)) in filter_ids.iter().enumerate() {
let (card, value, lbl, _) = kpi_cards[i + 1];
card.bind_click(id);
value.bind_click(id);
lbl.bind_click(id);
kpi_filter_cards[i] = (status, id, card, value, lbl);
}
root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6);
@@ -492,8 +536,11 @@ pub fn build(frame: Widget) -> App {
frame_sizer.set_sizer_on(frame);
frame.set_min_size(640, 480);
// A status bar carries scan state (was an inline label).
// A status bar carries scan state (was an inline label). A second,
// colour-tinted field pinned to the bottom-right corner carries scan/apply
// errors (red) and warnings (amber) so they don't overwrite the scan state.
wx_rs::create_status_bar();
wx_rs::status_indicator_init(frame);
wx_rs::set_status_text("starting scan...");
// Repaint custom-coloured widgets when the OS switches light/dark.
@@ -510,6 +557,8 @@ pub fn build(frame: Widget) -> App {
kpi_not,
kpi_paused,
kpi_hashrate,
kpi_hashrate_lbl,
hashrate_algo_idx: 0,
kpi_power,
progress,
table: None,
@@ -536,6 +585,7 @@ pub fn build(frame: Widget) -> App {
action_is_power: false,
action_total: 0,
action_done: 0,
action_targets: Vec::new(),
confirm_dialog: frame,
pending_confirm: None,
flash_confirm_dialog: frame,
@@ -546,6 +596,7 @@ pub fn build(frame: Widget) -> App {
creds_dialog: frame,
creds_user_input: frame,
creds_pass_input: frame,
access_probe: None,
pic_probe: None,
pending_pic_targets: Vec::new(),
picssh_dialog: frame,
@@ -739,8 +790,44 @@ impl App {
self.kpi_slow.set_label(&k.slow.to_string());
self.kpi_not.set_label(&k.not_hashing.to_string());
self.kpi_paused.set_label(&k.paused.to_string());
self.kpi_hashrate.set_label(&format_si(k.total_hashrate_ths * 1e12, "H/s"));
// Hashrate KPI: no "/s" suffix (per UI request) -> "685 TH", "1.2 PH".
// With a single algorithm running (the common case) the card shows that
// algorithm's total under a "<Algo> Hashrate" caption; when several are
// running, clicking the card cycles `hashrate_algo_idx` through them.
let (algo_label, algo_ths) = if k.hashrate_by_algo.is_empty() {
("SHA-256".to_string(), 0.0)
} else {
let i = self.hashrate_algo_idx % k.hashrate_by_algo.len();
let (a, t) = &k.hashrate_by_algo[i];
(pretty_algo(a), *t)
};
self.kpi_hashrate.set_label(&format_si(algo_ths * 1e12, "H"));
self.kpi_hashrate_lbl.set_label(&format!("{algo_label} Hashrate"));
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
// set_label resizes the static text; re-run each card's sizer so the
// centring spacers recompute around the new width (otherwise the value
// drifts off-centre when a filter changes a count's digit width).
for (card, _, _, _) in &self.kpi_cards {
card.layout();
}
}
/// Show a scan/apply error (red) in the bottom-right status indicator,
/// separate from the left-hand scan-status text.
fn set_error_indicator(&self, msg: &str) {
let c = self.pal.red;
wx_rs::status_indicator_set(msg, c.0, c.1, c.2);
}
/// Show a scan/apply warning (amber) in the bottom-right status indicator.
fn set_warning_indicator(&self, msg: &str) {
let c = self.pal.amber;
wx_rs::status_indicator_set(msg, c.0, c.1, c.2);
}
/// Clear the bottom-right status indicator.
fn clear_indicator(&self) {
wx_rs::status_indicator_set("", 0, 0, 0);
}
/// Re-apply the theme palette to the KPI cards and table rows after the OS
@@ -767,13 +854,29 @@ impl App {
/// so the active quick-filter is visible at a glance; every other status
/// card resets to the normal card background.
fn highlight_kpi_filter(&self) {
for &(status, _, card) in &self.kpi_filter_cards {
for &(status, _, card, value, lbl) in &self.kpi_filter_cards {
let bg = if Some(status) == self.active_kpi_filter {
tint_toward(self.pal.card_bg, status_kind_color(&self.pal, status), 0.35)
} else {
self.pal.card_bg
};
// Paint the panel and both static texts so the whole box tints; a
// static_text keeps its own background, so tinting only the card
// would leave an untinted rectangle behind the number and label.
card.set_bg(bg.0, bg.1, bg.2);
value.set_bg(bg.0, bg.1, bg.2);
lbl.set_bg(bg.0, bg.1, bg.2);
}
}
/// Click on the hashrate KPI card: advance to the next running algorithm's
/// total (wrapping around). A no-op when fewer than two algorithms are
/// running, since there is nothing to cycle to.
fn cycle_hashrate_algo(&mut self) {
let n = compute_kpis(&self.rows, &self.view_idx).hashrate_by_algo.len();
if n > 1 {
self.hashrate_algo_idx = (self.hashrate_algo_idx + 1) % n;
self.refresh_kpis();
}
}
@@ -799,7 +902,7 @@ impl App {
self.active_kpi_filter = match self.view.filters.get(&Column::Status) {
Some(ColFilter::Values(set)) if set.len() == 1 => {
let v = set.iter().next().map(String::as_str);
self.kpi_filter_cards.iter().map(|&(s, _, _)| s).find(|&s| Some(s) == v)
self.kpi_filter_cards.iter().map(|&(s, _, _, _, _)| s).find(|&s| Some(s) == v)
}
_ => None,
};
@@ -833,6 +936,9 @@ impl App {
// 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
// intersection): an action is offered only if every selected miner
// supports it.
@@ -905,7 +1011,11 @@ impl App {
old.stop();
}
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));
// Clear any stale error/warning from a previous operation; the new
// outcome repopulates the indicator when this action finishes.
self.clear_indicator();
wx_rs::set_status_text(&msg);
}
@@ -1018,6 +1128,82 @@ impl App {
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) {
@@ -1083,6 +1269,7 @@ impl App {
}
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_FLASH => {
// A flash needs exclusive hardware access; don't even prompt if
// any scan / refresh / action is running (re-checked at confirm).
@@ -1386,6 +1573,9 @@ impl App {
let Some(h) = &self.action else { return };
let mut status: Option<String> = None;
let mut finished = false;
// Bottom-right indicator to apply after the `h` borrow is released:
// None = leave as-is, Some(None) = clear, Some(Some((is_error, msg))).
let mut indicator: Option<Option<(bool, String)>> = None;
loop {
match h.rx.try_recv() {
Ok(scan::ActionMsg::Started { total }) => {
@@ -1408,6 +1598,15 @@ impl App {
} else {
format!("applied to {ok}/{total} miner(s), {} failed", total - ok)
});
// Surface the outcome in the bottom-right indicator: a total
// failure is red, a partial failure amber, full success clears.
indicator = Some(if total == 0 || ok == total {
None
} else if ok == 0 {
Some((true, format!("apply failed on all {total} miner(s)")))
} else {
Some((false, format!("apply: {}/{total} miner(s) failed", total - ok)))
});
finished = true;
break;
}
@@ -1421,6 +1620,7 @@ impl App {
}
if finished {
self.action = None;
let was_flash = self.flashing;
// Release the firmware-flash exclusive lock (harmless no-op for a
// plain config action, which never set it).
self.flashing = false;
@@ -1428,6 +1628,21 @@ impl App {
// action's outcome (incl. failures) isn't clobbered by the next tick.
self.action_result = status.clone();
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);
}
}
// Apply the captured indicator now the `h` borrow is gone.
if let Some(ind) = indicator {
match ind {
None => self.clear_indicator(),
Some((true, msg)) => self.set_error_indicator(&msg),
Some((false, msg)) => self.set_warning_indicator(&msg),
}
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
@@ -1502,6 +1717,8 @@ impl App {
self.progress.gauge_set_value(0);
self.progress.show(true);
self.table_parent.layout();
// A fresh scan supersedes any prior error/warning.
wx_rs::status_indicator_set("", 0, 0, 0);
wx_rs::set_status_text(&format!("scanning {total} addresses..."));
}
Ok(ScanMsg::Progress { done, total, ip }) => {
@@ -1533,6 +1750,9 @@ impl App {
self.progress.show(false);
self.table_parent.layout();
wx_rs::set_status_text(&format!("scan failed: {e}"));
// Surface the failure in the bottom-right indicator (red).
let c = self.pal.red;
wx_rs::status_indicator_set(&format!("scan failed: {e}"), c.0, c.1, c.2);
self.countdown = if self.playing { self.auto_secs } else { 0 };
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
@@ -1563,11 +1783,12 @@ impl App {
self.drain_action();
self.drain_refresh();
self.drain_pic_probe();
self.drain_access_probe();
if self.scanning {
return; // status already shows scan progress
}
if self.pic_probe.is_some() {
return; // a PIC probe is in flight; keep its status
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() {
return; // a config action is in flight; keep its status
@@ -2056,7 +2277,9 @@ impl App {
let dlg = Widget::dialog(frame, "Filter");
let root = Widget::box_sizer(true);
self.filter_cols = self.view.display_columns();
// Offer every column (not just the visible ones) so any metric --
// Algorithm included -- can be filtered without first un-hiding it.
self.filter_cols = self.view.filter_columns();
self.filter_working = self.view.filters.clone();
self.filter_cur = 0;
@@ -2363,6 +2586,7 @@ impl App {
ID_KPI_SLOW => self.toggle_kpi_filter("slow"),
ID_KPI_NOT => self.toggle_kpi_filter("not hashing"),
ID_KPI_PAUSED => self.toggle_kpi_filter("paused"),
ID_KPI_HASHRATE => self.cycle_hashrate_algo(),
ID_PLAY => {
// Resume/start the scan loop: scan now (unless one is
// already running) + auto-rescan on.
@@ -2434,7 +2658,7 @@ impl App {
(self.kpi_slow, "Slow", "1"),
(self.kpi_not, "Not hashing", "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"),
];
for (w, name, want) in want_kpis {
+18 -1
View File
@@ -10,7 +10,7 @@
+pub use widgets::*;
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -0,0 +1,728 @@
@@ -0,0 +1,745 @@
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
+// wxWidgets object tree (parents own children; nothing to free in Rust).
@@ -116,6 +116,8 @@
+ pub fn wxbr_destroy(win: *mut c_void);
+ pub fn wxbr_destroy_children(win: *mut c_void);
+ pub fn wxbr_call_after(id: c_int);
+ pub fn wxbr_status_indicator_init(frame: *mut c_void);
+ pub fn wxbr_status_indicator_set(text: *const c_char, r: c_int, g: c_int, b: c_int);
+ }
+}
+
@@ -188,6 +190,21 @@
+ unsafe { notsafe::wxbr_call_after(id as c_int) }
+}
+
+/// Reconfigure the frame's status bar to two fields and attach a colour-tinted
+/// label pinned to the right-hand field (bottom-right corner). Call once after
+/// `create_status_bar()`. The main scan status keeps using the left field via
+/// the upstream `set_status_text` path.
+pub fn status_indicator_init(frame: Widget) {
+ unsafe { notsafe::wxbr_status_indicator_init(frame.0) }
+}
+
+/// Set the bottom-right status indicator's text and colour (an empty string
+/// clears it). Used for scan/apply errors (red) and warnings (amber).
+pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) {
+ let c = CString::new(text).unwrap_or_default();
+ unsafe { notsafe::wxbr_status_indicator_set(c.as_ptr(), r as c_int, g as c_int, b as c_int) }
+}
+
+/// Open a URL in the system default browser. Returns true on success.
+pub fn launch_browser(url: &str) -> bool {
+ let c = CString::new(url).unwrap_or_default();
+77 -3
View File
@@ -1,6 +1,6 @@
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -0,0 +1,1059 @@
@@ -0,0 +1,1133 @@
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
+// render-callback bridge (which is kept untouched).
@@ -32,6 +32,7 @@
+#include <wx/graphics.h>
+#include <wx/wrapsizer.h>
+#include <wx/filedlg.h>
+#include <wx/statusbr.h>
+#include <cstring>
+#include <cstdio>
+#include <map>
@@ -701,9 +702,11 @@
+}
+
+// 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) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
+ wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
+ if (item.IsOk()) dv->EnsureVisible(item);
+}
@@ -775,6 +778,25 @@
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ unsigned n = dv->GetColumnCount();
+ 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++) {
+ wxDataViewColumn* c = dv->GetColumn(i);
+ if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
@@ -806,9 +828,11 @@
+void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ int count = (int)dvlc_store(win)->GetItemCount();
+ dv->UnselectAll();
+ 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]));
+ }
+}
+
@@ -827,6 +851,7 @@
+ if (row < 0) return;
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ if (row >= (long)dvlc_store(win)->GetItemCount()) return;
+ dv->Select(m->GetItem((unsigned)row));
+}
+
@@ -1051,6 +1076,55 @@
+ }
+}
+
+// ---- status-bar error/warning indicator -------------------------------------
+// A colour-tinted static text pinned to the RIGHT-hand field of the frame's
+// status bar, so scan/apply errors surface in the bottom-right corner without
+// overwriting the main (left) scan-status text. The status bar is reconfigured
+// to two fields: field 0 (stretch) carries the scan status set via the upstream
+// SetStatusText path; field 1 (fixed) hosts this coloured label, which we
+// reposition into that field's rect whenever the bar is resized.
+static wxStaticText* g_status_indicator = nullptr;
+
+static void reposition_status_indicator() {
+ if (!g_status_indicator) return;
+ wxStatusBar* sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar);
+ if (!sb) return;
+ wxRect r;
+ if (!sb->GetFieldRect(1, r)) return;
+ wxSize best = g_status_indicator->GetBestSize();
+ int h = best.GetHeight();
+ int y = r.y + (r.height - h) / 2;
+ g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h);
+}
+
+void wxbr_status_indicator_init(void* frame_ptr) {
+ wxFrame* frame = (wxFrame*)frame_ptr;
+ wxStatusBar* sb = frame->GetStatusBar();
+ if (!sb) sb = frame->CreateStatusBar();
+ int widths[2] = { -1, 340 };
+ sb->SetFieldsCount(2);
+ sb->SetStatusWidths(2, widths);
+ if (!g_status_indicator) {
+ g_status_indicator = new wxStaticText(sb, wxID_ANY, wxEmptyString,
+ wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE);
+ sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) {
+ reposition_status_indicator();
+ ev.Skip();
+ });
+ }
+ reposition_status_indicator();
+}
+
+// Set the bottom-right indicator text and its colour. An empty string clears it.
+void wxbr_status_indicator_set(const char* text, int r, int g, int b) {
+ if (!g_status_indicator) return;
+ g_status_indicator->SetLabel(wxString::FromUTF8(text ? text : ""));
+ g_status_indicator->SetForegroundColour(
+ wxColour((unsigned char)r, (unsigned char)g, (unsigned char)b));
+ reposition_status_indicator();
+ g_status_indicator->Refresh();
+}
+
+// ---- deferred destroy (safe from event handlers) ----------------------------
+
+void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
@@ -29,6 +29,7 @@
#include <wx/graphics.h>
#include <wx/wrapsizer.h>
#include <wx/filedlg.h>
#include <wx/statusbr.h>
#include <cstring>
#include <cstdio>
#include <map>
@@ -698,9 +699,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 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) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
if (item.IsOk()) dv->EnsureVisible(item);
}
@@ -772,6 +775,25 @@ int wxbr_dvlc_col_at_pos(void* win, int pos) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned n = dv->GetColumnCount();
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++) {
wxDataViewColumn* c = dv->GetColumn(i);
if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
@@ -803,9 +825,11 @@ int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
int count = (int)dvlc_store(win)->GetItemCount();
dv->UnselectAll();
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]));
}
}
@@ -824,6 +848,7 @@ void wxbr_dvlc_select_row(void* win, long row) {
if (row < 0) return;
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
if (row >= (long)dvlc_store(win)->GetItemCount()) return;
dv->Select(m->GetItem((unsigned)row));
}
@@ -1048,6 +1073,55 @@ void wxbr_call_after(int id) {
}
}
// ---- status-bar error/warning indicator -------------------------------------
// A colour-tinted static text pinned to the RIGHT-hand field of the frame's
// status bar, so scan/apply errors surface in the bottom-right corner without
// overwriting the main (left) scan-status text. The status bar is reconfigured
// to two fields: field 0 (stretch) carries the scan status set via the upstream
// SetStatusText path; field 1 (fixed) hosts this coloured label, which we
// reposition into that field's rect whenever the bar is resized.
static wxStaticText* g_status_indicator = nullptr;
static void reposition_status_indicator() {
if (!g_status_indicator) return;
wxStatusBar* sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar);
if (!sb) return;
wxRect r;
if (!sb->GetFieldRect(1, r)) return;
wxSize best = g_status_indicator->GetBestSize();
int h = best.GetHeight();
int y = r.y + (r.height - h) / 2;
g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h);
}
void wxbr_status_indicator_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[2] = { -1, 340 };
sb->SetFieldsCount(2);
sb->SetStatusWidths(2, widths);
if (!g_status_indicator) {
g_status_indicator = new wxStaticText(sb, wxID_ANY, wxEmptyString,
wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE);
sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) {
reposition_status_indicator();
ev.Skip();
});
}
reposition_status_indicator();
}
// Set the bottom-right indicator text and its colour. An empty string clears it.
void wxbr_status_indicator_set(const char* text, int r, int g, int b) {
if (!g_status_indicator) return;
g_status_indicator->SetLabel(wxString::FromUTF8(text ? text : ""));
g_status_indicator->SetForegroundColour(
wxColour((unsigned char)r, (unsigned char)g, (unsigned char)b));
reposition_status_indicator();
g_status_indicator->Refresh();
}
// ---- deferred destroy (safe from event handlers) ----------------------------
void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
+17
View File
@@ -103,6 +103,8 @@ mod notsafe {
pub fn wxbr_destroy(win: *mut c_void);
pub fn wxbr_destroy_children(win: *mut c_void);
pub fn wxbr_call_after(id: c_int);
pub fn wxbr_status_indicator_init(frame: *mut c_void);
pub fn wxbr_status_indicator_set(text: *const c_char, r: c_int, g: c_int, b: c_int);
}
}
@@ -175,6 +177,21 @@ pub fn call_after(id: i32) {
unsafe { notsafe::wxbr_call_after(id as c_int) }
}
/// Reconfigure the frame's status bar to two fields and attach a colour-tinted
/// label pinned to the right-hand field (bottom-right corner). Call once after
/// `create_status_bar()`. The main scan status keeps using the left field via
/// the upstream `set_status_text` path.
pub fn status_indicator_init(frame: Widget) {
unsafe { notsafe::wxbr_status_indicator_init(frame.0) }
}
/// Set the bottom-right status indicator's text and colour (an empty string
/// clears it). Used for scan/apply errors (red) and warnings (amber).
pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) {
let c = CString::new(text).unwrap_or_default();
unsafe { notsafe::wxbr_status_indicator_set(c.as_ptr(), r as c_int, g as c_int, b as c_int) }
}
/// Open a URL in the system default browser. Returns true on success.
pub fn launch_browser(url: &str) -> bool {
let c = CString::new(url).unwrap_or_default();