Compare commits

...
5 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 86e4761316 GUI round 7: code-review remediation (flash safety, unknown-actual colour, credentials, coverage)
Fixes the Critical/High findings from the round-6 review (6 parallel dimension
reviewers + adversarial verify), plus the cheap high-value non-blocking ones.
Full write-up in code-review-report.md.

Firmware-flash safety (the one irreversible, hardware-destroying action):
- Critical: re-triggering an action no longer races the previous one. A flash
  now takes an exclusive lock (new App.flashing): it will not start while any
  scan / refresh / config action is running, and none of those (nor another
  flash) start while it runs. begin_scan, start_action, start_refresh and
  apply_flash_confirm all gate on it, and the context menu offers only the
  read-only "Open in browser" while flashing. This removes the two overlapping-
  network-operation paths that could interrupt/corrupt an upload and brick a
  miner (old.stop() never joined the in-flight upload).
- High: the flash confirm dialog now lists every target IP + model and warns
  loudly when the batch spans more than one model (a single image is rarely
  valid for all), instead of showing only a bare count.

Correctness:
- High: combined columns no longer paint the "-" placeholder solid red when the
  actual is unknown but the expected is known (an idle/paused/booting miner of a
  recognised model looked like a 0% catastrophic failure). fill_rows now gates
  the ratio on the actual being known; unknown-actual falls to the plain,
  uncoloured segment. Was masked by the all-zero-expected fixtures.
- compute_kpis buckets by status() instead of re-deriving the precedence from
  raw flags (KPI header can no longer disagree with a row's status; offline
  folds into not_hashing).

Security:
- credentials file is created at 0600 up front (OpenOptions::mode) and
  re-tightened while still empty, so the plaintext password is never on disk
  under a looser mode (was create-0644 then chmod-0600).
- the "Set scan credentials" dialog no longer pre-fills the saved password in
  plaintext; a blank Password field keeps the stored one.

Robustness / API:
- the fake-scan branches of the config-action / refresh / flash background
  threads now honour the cancel flag (were ignored, so stop() was a no-op).
- MinerRow.online -> offline (default false = online), removing the footgun
  where a struct-update literal that forgot `online: true` read back offline.

Tests (the review's primary focus -- these paths had zero coverage):
- scan.rs fake_mode_background_actions: start_scan offline-row emission,
  start_refresh (Row/Failed/Done), start_firmware_flash_action, and that a
  cancelled run still terminates with Done rather than hanging.
- model.rs: flash_confirmed (exact/case/prefix/whitespace), compute_kpis vs
  status() consistency, Default-is-online.
- new ui::tests: ratio_color/fan_color/tint_toward stops+clamping+blends, and
  the combined-cell unknown-actual and cooling-cell encodings.
- credentials.rs: configured_factory smoke (both branches) + pre-existing-0644
  re-tighten.
- self-test: offline row (.199) spot-check, KPI quick-filter toggle on/off, and
  a numeric (not lexical) IP-sort assertion via model::ip_to_u32.

Deferred (non-blocking, tracked in code-review-report.md): start_* boilerplate
extraction; per-model firmware image-compatibility check; scoping saved
credentials to a chosen backend; a masked password field (needs a wx-rs
TE_PASSWORD binding); flash-specific status text; a segment-encode microbench.

Verified: cargo check --release --tests is clean; unit tests + benches + the
headless self-test run in CI (local release link is OOM-blocked on this
desktop).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 14:06:03 -06:00
noahandClaude Opus 4.8 c1234f6df7 GUI round 6 self-test fix: decode combined-column cells in spot-checks
The round-6 combined columns (Hashrate/Hashboards/TotalChips/Cooling) now
store colour-segment-encoded strings in the data view, so the headless
self-test's per-IP spot-checks read raw encoded bytes instead of plain text.
Two checks failed in CI as a result:
- S21 Pro (.149) hashrate read "B95E18<US>60.0 TH/s / 200 TH/s" (colour hex
  prefix + encoded combined text) rather than the plain value.
- S17 (.112) blank-hashrate read an encoded empty cell (invisible control
  chars), so is_empty() was false.

Fix: the spot-check `cell` closure now runs dvlc_get_cell output through
decode_segments_plain (a no-op for plain cells), and the S21 hashrate check
expects the combined "60.0 TH/s / 200 TH/s" form. The "every cell matches the
model" loop already decoded, so it was unaffected.

Verified: cargo check --release --tests is clean; the self-test itself is a
CI gate (local release link is OOM-blocked on this desktop).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 13:27:54 -06:00
noahandClaude Opus 4.8 b6afe08a5f GUI round 6: offline detection, combined columns, per-cell colours, paused status, credentials, refresh, firmware flash
Large round implemented via a research workflow (6 parallel readers) then a
file-partitioned implementation workflow (model/scan/bridge/ui/fixtures), all to
one shared contract.

Table / model:
- Offline recognition fix: the scan loop now emits a row for EVERY probed IP -
  non-responders become an "offline" row (new MinerRow.online flag +
  MinerRow::offline()), so unreachable miners show up (offline, red) instead of
  vanishing. Previously only responders got a row.
- Not-hashing rows are now RED (were grey); offline also red.
- New "paused" status (operating_state contains "pause" while not mining):
  its own blue row colour, a blue "Paused" KPI card, and a Kpis.paused count.
- Combined actual/expected columns: Hashrate, Hashboards and TotalChips fold
  their separate Expected* columns into one "actual / expected" cell; the actual
  is drawn on a smooth red->amber->green scale by ratio (100% = green), the
  expected in plain text, the slash black. num_value is carved out so a numeric
  filter never matches a row that only has an expected value.
- Fan column shows every fan's RPM as "rpm/rpm/rpm" (max 3 sig digits, SI-style),
  each fan coloured on its own grey->blue speed scale, slashes black.
- These four columns render via a new wxDataViewCustomRenderer (SegmentRenderer)
  that draws colour runs from a \x1f/\x1e-encoded value; every other column keeps
  the stock renderer and per-row status colour.

Interaction:
- KPI quick-filter: clicking the Hashing / Slow / Not hashing / Paused card
  filters the table to that status (composed with any column filters) and
  highlights the active card; clicking again clears it.
- Removed "Select all" / "Clear selection" from the right-click menu.
- Right-click "Refresh": re-polls the selected miners (asic-rs scan_miner) on a
  background thread and upserts the rows, without a full network scan.
- "Set scan credentials..." button (top-right): stores a username/password
  (~/.config/alkane-toolkit/scan-credentials.txt, 0600) that is fanned out to
  every asic-rs firmware backend via with_firmware_discovery_auth, so scans and
  all right-click actions authenticate. Applied through a new
  credentials::configured_factory() used everywhere MinerFactory::new() was.
- "Flash firmware..." (right-click): asic-rs UpgradeFirmware for the backends
  that support it (stock Antminer + EPIC; every other backend declines and is
  reported as unsupported). File picker (new wxFileDialog binding) + a typed
  "FLASH" confirmation; one miner at a time; cancel only between miners.
- Responsive layout: the KPI and controls rows use wxWrapSizer so they reflow
  when narrow; the min window size drops from 1200x720 to 640x480.

Bridge (wx-rs): SegmentRenderer + dvlc_append_colored_col, wrap_sizer,
bind_click (clickable KPI cards), file_dialog; dropped a vestigial gtk.h include.
Patches 0002/0003 regenerated + round-trip validated.

Portability note: every widget is a stock, natively-backed wxWidgets control
(ports to wxMSW/wxOSX); wxDataViewCtrl is native on Linux/macOS and wx's own
generic (still-correct) drawing on Windows.

Verified: cargo check --release --tests is clean; the release build + tests +
headless self-test run in CI. (Local release link is OOM-blocked on this
desktop; CI is the authoritative build.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 13:09:16 -06:00
noahandClaude Opus 4.8 eb08a9ef97 GUI: per-miner capabilities + live config write path (right-click actions)
Completes the right-click config menu (round-2 item 11): the menu now offers
real actions computed from the intersection of what every selected miner
supports, and applies them to the fleet over the network.

- Capability detection: to_row probes each miner's asic-rs supports_* methods
  (fault light, restart, pause, resume, power limit, tuning) at scan time and
  stores them in MinerRow.caps -- no extra network round-trip.
- Intersection: MinerCaps::intersect_all yields the actions common to the whole
  selection; the context menu offers only those (a mixed mining + idle selection
  shows just fault light + restart; an all-mining selection shows everything).
- Write path: scan::start_config_action runs on a background thread -- it
  re-discovers each selected miner with asic-rs scan_miner(ip), applies the
  setter, and reports per-IP results that drain into the status bar (running
  progress while applying, a pass/fail summary when done). Cancellable, and a
  new action cancels any in-flight one so two never overlap. In fake-scan mode
  it simulates success so the flow is exercisable offline.
- Actions: fault light on/off, pause, resume, restart apply immediately; set
  power limit and set tuning % open a small value-prompt dialog first. Factory
  reset, change password, and firmware upgrade are deliberately not exposed in a
  casual right-click.

Adds the `measurements` dependency (already in the lock, transitive via asic-rs)
for Power::from_watts.

Review fixes (one review pass):
- Restart / pause / resume now require a confirmation dialog (naming the count)
  so a misclick can't stop a producing fleet; fault light stays instant, and
  power/tuning are confirmed by their value entry.
- The action result is held on the status bar for a few ticks so a fleet
  action's outcome (including failures) isn't clobbered by the next timer tick.
- The action loop uses a current-thread tokio runtime (it applies to one miner
  at a time; a worker pool was wasted).
- The value prompt validates before closing: a bad value keeps the dialog and
  the captured selection so it can be corrected.
- The menu's "(N)" counts use the rows-backed selection, matching what is
  actually acted on.

Verified off-screen: capability intersection (mixed vs all-mining selections),
the value-prompt and confirmation nested modals (menu -> dialog) with no crash,
the end-to-end apply flow, 46 unit tests (incl. a caps-intersection test), and
the headless self-test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 11:05:15 -06:00
noahandClaude Opus 4.8 297e21a519 GUI round 3: Excel-style filters, status row colours, icon controls, context menu, live theme
Addresses the round-3 feedback batch:

- Right-click now works: a context menu (open selected in browser, select all,
  clear) pops up from the table. It was never wired before. (The live-config
  intersection over the selection remains a follow-up; no dead menu items.)
- Selection is readable again in both themes: the alt-row/zebra CSS hack (which
  painted row backgrounds over the native highlight, leaving white-on-white) is
  gone; the native selection highlight shows through.
- Row text is coloured by status (green = hashing, amber = slow, grey = not
  hashing), which also separates rows without fragile GTK zebra striping.
- Dark mode: KPI cards and rows follow the system theme (no more white boxes in
  dark mode); a system-colour-changed event repaints them live if the OS toggles
  light/dark while the app is open.
- Play / Pause / Stop are coloured media icons (green triangle / amber bars /
  red square) instead of text buttons.
- Filter panel redesigned Excel-style: a column dropdown at the top selects the
  column; controls adapt to its type. Text columns: a value checklist ("is any
  of") or a predicate (contains / does not contain / begins with / ends with /
  equals). Numeric columns: between / = / != / > / >= / < / <=. Filters AND
  across columns; edits held in a working copy, committed on Apply.
- Auto-rescan label shortened to "Rescan (s):" so the value field has room.

Table: replaced wxDataViewListCtrl with a raw wxDataViewCtrl + a custom
AttrListStore (per-row foreground via GetAttrByRow), which keeps in-table column
drag while enabling status row colours. New wx-rs bridge primitives: wxChoice
dropdown, coloured media buttons (drawn on a transparent bitmap via
wxGraphicsContext), a wxEVT_SYS_COLOUR_CHANGED event, destroy_children, and
call_after (deferred rebuilds). Patches 0002/0003 regenerated + round-trip
validated.

Model: ColFilter { Values, Text{op}, Num{op} } with TextOp/NumOp and
passes_filters -> ColFilter::matches; Column::num_value for numeric filtering.

Review fixes (one review pass):
- Deferred the two rebuilds that destroyed a control from inside its own event
  (filter op-dropdown change; column drag-reorder) via call_after, avoiding a
  use-after-free.
- num_value returns None for a blank-displaying value-type cell (Hashrate,
  Power, ChipTemp, ...), so "ChipTemp <= 50" no longer matches a miner with no
  temperature reading.
- Value checklist maps a checked entry back to its real value by index, so a
  literal "(blank)" value is not confused with an empty cell.

Verified off-screen: 45 unit tests, headless self-test (14 checks), and
interaction screenshots of selection, right-click, the text/numeric filter, the
comparator swap, and dark mode.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 09:19:38 -06:00
12 changed files with 3754 additions and 376 deletions
Generated
+1
View File
@@ -80,6 +80,7 @@ dependencies = [
"alkane-discovery",
"asic-rs",
"futures-util",
"measurements",
"tokio",
"wx-rs",
]
+1
View File
@@ -14,5 +14,6 @@ alkane-discovery = { path = "../alkane-discovery" }
# vendored + patched wx-rs (see vendor/wx-rs/patches/)
wx-rs = { path = "../../thirdparty/wx-rs/wx-rs-0.2.0-patched" }
asic-rs = "0.8.1"
measurements = "0.11"
tokio = { version = "1", features = ["rt"] }
futures-util = "0.3"
+127
View File
@@ -0,0 +1,127 @@
//! Optional saved miner credentials, applied to every asic-rs discovery call.
//!
//! asic-rs has no single global credential field on `MinerFactory`: auth is set
//! per firmware backend via `with_firmware_discovery_auth`. `configured_factory`
//! is the one place that fans a saved username/password out across the whole
//! firmware registry, so `scan`'s callers never have to think about it.
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use asic_rs::MinerFactory;
use asic_rs::core::traits::miner::MinerAuth;
use crate::scan::config_path;
pub const CREDENTIALS_FILE: &str = "scan-credentials.txt";
/// Load the saved miner username/password, if any were saved.
pub fn load_credentials() -> Option<(String, String)> {
let s = std::fs::read_to_string(config_path(CREDENTIALS_FILE)).ok()?;
let mut lines = s.lines();
let user = lines.next()?.to_string();
let pass = lines.next().unwrap_or("").to_string();
Some((user, pass))
}
/// Save the miner username/password, restricting the file to owner
/// read/write (credentials are plaintext on disk, so the mode matters).
pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> {
let p = config_path(CREDENTIALS_FILE);
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
// Open (and create) with mode 0600 up front so a freshly created file is
// never world/group-readable, even for the instant before the write. For a
// pre-existing file the create mode is ignored, so also tighten it to 0600
// while it is still empty (post-truncate, pre-write) -- the plaintext is
// never on disk under a looser mode.
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(format!("{user}\n{pass}\n").as_bytes())?;
Ok(())
}
/// Remove the saved credentials, if any. Not an error if none were saved.
pub fn clear_credentials() -> std::io::Result<()> {
match std::fs::remove_file(config_path(CREDENTIALS_FILE)) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
/// Build a `MinerFactory` with the saved credentials (if any) applied as
/// discovery auth for every firmware backend, so scans, refreshes, config
/// actions, and firmware flashes all authenticate against a non-default
/// login the same way. With no saved credentials this is plain `MinerFactory::new()`
/// and every backend falls back to its own default auth.
pub fn configured_factory() -> MinerFactory {
let mut factory = MinerFactory::new();
if let Some((user, pass)) = load_credentials() {
for fw in asic_rs::factory::default_firmware_registry() {
factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user.clone(), pass.clone()));
}
}
factory
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credentials_round_trip_and_file_perms() {
// config_path() reads $HOME; point it at a private temp dir. HOME is
// process-global, so this stays one test and restores HOME afterward
// (matching the pattern used by scan::tests::auto_secs_round_trip_and_defaults).
let prev = std::env::var_os("HOME");
let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("HOME", &dir);
assert_eq!(load_credentials(), None, "no file -> None");
save_credentials("admin", "hunter2").unwrap();
assert_eq!(load_credentials(), Some(("admin".to_string(), "hunter2".to_string())));
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600");
// configured_factory() must construct in both branches without panicking:
// with saved credentials (fans auth across every firmware backend) ...
let _ = configured_factory();
// A pre-existing, world-readable credentials file must be tightened to
// 0600 by save_credentials (the create-mode is ignored for an existing
// file, so the explicit set_permissions is what protects it).
let path = config_path(CREDENTIALS_FILE);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
save_credentials("admin2", "s3cr3t").unwrap();
let meta = std::fs::metadata(&path).unwrap();
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"save over a pre-existing 0644 file must re-tighten to 0600"
);
assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string())));
clear_credentials().unwrap();
// ... and with no saved credentials (plain MinerFactory::new()).
let _ = configured_factory();
assert_eq!(load_credentials(), None, "cleared -> None");
clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error
match prev {
Some(v) => std::env::set_var("HOME", v),
None => std::env::remove_var("HOME"),
}
let _ = std::fs::remove_dir_all(&dir);
}
}
+73 -19
View File
@@ -1,8 +1,10 @@
//! Bench-fleet fixtures: the expected hardware output of the 9 boards on
//! 10.255.1.0/24 (see ../../../HANDOFF.md section 7 and the parent project's
//! [removed]). These are the reference values the workflow tests compare
//! the application's actual output against, and the rows the offline
//! `ALKANE_FAKE_SCAN` demo mode renders.
//! [removed]), plus one synthetic unreachable IP rendered via
//! `MinerRow::offline()` so the "offline" status/row shape is exercisable
//! offline too (10 rows total). These are the reference values the workflow
//! tests compare the application's actual output against, and the rows the
//! offline `ALKANE_FAKE_SCAN` demo mode renders.
//!
//! Hashrate/power/temp are representative per-model figures (the bench boards
//! are not always energised); the point of the fixtures is a fixed, known input
@@ -24,6 +26,10 @@ struct Board {
fan: f64,
worker: &'static str,
mining: bool,
/// True for the bench board deliberately rebucketed into the "paused"
/// status/KPI bucket (not-mining but operator-paused, distinct from a
/// unit that is simply idle/not-hashing).
paused: bool,
}
impl Board {
@@ -37,6 +43,18 @@ impl Board {
} else {
(None, None, 0.0)
};
let fan_rpms = if self.mining {
vec![self.fan, self.fan * 0.95, self.fan * 1.02]
} else {
vec![]
};
// Firmware-flash capability is modeled on the real Bitmain/Antminer
// upgrade path (S17/S19/S21 family); WhatsMiner boards in this fleet
// don't advertise it, so both true and false show up and the
// firmware menu item is testable.
let firmware_flash = self.model == "Antminer S17"
|| self.model.starts_with("Antminer S19")
|| self.model.starts_with("Antminer S21");
MinerRow {
ip: self.ip.to_string(),
selected: false,
@@ -47,10 +65,12 @@ impl Board {
efficiency,
power_w: self.power,
chip_temp_c: self.temp,
fan_rpm: self.fan,
fan_rpms,
worker: self.worker.to_string(),
is_mining: self.mining,
slow,
paused: self.paused,
// offline defaults to false (online); these bench rows are reachable.
mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)),
hostname: format!("miner-{last_octet}"),
hashboards: boards,
@@ -68,47 +88,81 @@ impl Board {
("stratum+tcp://backup.blueflare:3333".to_string(), format!("{}_bak", self.worker)),
]
},
operating_state: if self.mining { "mining".to_string() } else { "idle".to_string() },
operating_state: if self.paused {
"paused".to_string()
} else if self.mining {
"mining".to_string()
} else {
"idle".to_string()
},
// Synthetic capabilities so the right-click config menu is
// exercisable offline: mining units support everything, idle ones
// only the fault light + restart (to show the capability intersection).
caps: crate::model::MinerCaps {
fault_light: true,
restart: true,
pause: self.mining,
resume: self.mining,
power_limit: self.mining,
tuning: self.mining,
firmware_flash,
},
..Default::default()
}
}
}
/// The 9 bench boards. Two are idle (S17 stock, WardenOS dev), one is slow
/// (S21 Pro aml stock at ~30% of expected); the other six hash normally.
/// The 9 bench boards plus one synthetic offline entry (10 rows total).
/// One is idle/not-hashing (S17 stock, .112); one is paused (WardenOS dev,
/// .115 - deliberately rebucketed from idle so the "paused" status/KPI
/// bucket is exercisable offline); one is slow (S21 Pro aml stock at ~30%
/// of expected); the other six hash normally; the last row is an
/// unreachable IP rendered via `MinerRow::offline()` (blank fields,
/// `offline: true`).
///
/// Derived totals (used by the workflow tests):
/// total = 9, hashing = 6, slow = 1, not hashing = 2,
/// total hashrate = 685.0 TH/s, total power = 21300 W.
/// total = 10, hashing = 6, slow = 1, not hashing = 1, paused = 1, offline = 1,
/// total hashrate = 685.0 TH/s, total power = 21300 W (offline row is all zero).
///
/// Note: `compute_kpis` has no separate "offline" bucket - an offline row is
/// `!is_mining && !paused && !slow`, so it folds into the "not hashing" KPI
/// alongside the idle S17, giving `Kpis.not_hashing == 2`. The per-row
/// `status()` text still distinguishes them ("not hashing" for .112 vs.
/// "offline" for .199).
pub fn bench_fleet() -> Vec<MinerRow> {
let boards = [
Board { ip: "10.255.1.112", model: "Antminer S17", firmware: "Stock",
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
worker: "", mining: false },
worker: "", mining: false, paused: false },
Board { ip: "10.255.1.166", model: "Antminer S19", firmware: "[removed] 1.2",
hashrate: 95.0, expected: 96.0, power: 3250.0, temp: 65.0, fan: 4200.0,
worker: "blueflare.s19", mining: true },
worker: "blueflare.s19", mining: true, paused: false },
Board { ip: "10.255.1.152", model: "Antminer S19j Pro", firmware: "[removed] 1.2",
hashrate: 100.0, expected: 104.0, power: 3100.0, temp: 62.0, fan: 3900.0,
worker: "blueflare.s19jpro", mining: true },
worker: "blueflare.s19jpro", mining: true, paused: false },
Board { ip: "10.255.1.167", model: "Antminer S19k Pro", firmware: "[removed] 1.2",
hashrate: 120.0, expected: 128.0, power: 3300.0, temp: 68.0, fan: 4500.0,
worker: "blueflare.s19kpro", mining: true },
worker: "blueflare.s19kpro", mining: true, paused: false },
Board { ip: "10.255.1.149", model: "Antminer S21 Pro", firmware: "Stock",
hashrate: 60.0, expected: 200.0, power: 1500.0, temp: 55.0, fan: 3000.0,
worker: "blueflare.s21pro", mining: true }, // slow: 60/200 = 30%
worker: "blueflare.s21pro", mining: true, paused: false }, // slow: 60/200 = 30%
Board { ip: "10.255.1.126", model: "WhatsMiner M30S", firmware: "WMOS H3",
hashrate: 92.0, expected: 96.0, power: 3400.0, temp: 70.0, fan: 4800.0,
worker: "blueflare.h3", mining: true },
worker: "blueflare.h3", mining: true, paused: false },
Board { ip: "10.255.1.131", model: "WhatsMiner M30S+", firmware: "WMOS H616",
hashrate: 100.0, expected: 100.0, power: 3450.0, temp: 71.0, fan: 4900.0,
worker: "blueflare.h616", mining: true },
worker: "blueflare.h616", mining: true, paused: false },
Board { ip: "10.255.1.148", model: "WhatsMiner M50", firmware: "WMOS CB4",
hashrate: 118.0, expected: 122.0, power: 3300.0, temp: 66.0, fan: 4600.0,
worker: "blueflare.m50", mining: true },
worker: "blueflare.m50", mining: true, paused: false },
// Rebucketed from idle/not-hashing to paused so the "paused"
// status/KPI bucket is exercisable in the fake-scan/offline demo.
Board { ip: "10.255.1.115", model: "Antminer S19", firmware: "WardenOS dev",
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
worker: "", mining: false },
worker: "", mining: false, paused: true },
];
boards.into_iter().map(Board::into_row).collect()
let mut rows: Vec<MinerRow> = boards.into_iter().map(Board::into_row).collect();
// Synthetic offline board: unreachable IP, blank/zeroed fields, offline: true.
rows.push(MinerRow::offline("10.255.1.199".into()));
rows
}
+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 credentials;
mod fixtures;
mod model;
mod scan;
+641 -89
View File
@@ -14,13 +14,15 @@ pub fn is_slow(is_mining: bool, hashrate_ths: f64, expected_ths: f64) -> bool {
is_mining && expected_ths > 0.0 && hashrate_ths < SLOW_THRESHOLD * expected_ths
}
/// Format a value in its base unit with an SI prefix chosen so the number stays
/// compact: the prefix puts the mantissa in [1, 1000), then it is shown with 1
/// decimal below 100 and no decimal from 100 up (so 21300 W -> "21.3 kW",
/// 685e12 H/s -> "685 TH/s", 6.8e12 -> "6.8 TH/s"). Zero renders as "0 <unit>".
pub fn format_si(value_base: f64, unit: &str) -> String {
/// Choose an SI prefix and a max-3-significant-digit mantissa string for a
/// base value, shared by `format_si` and `format_fan_rpm`: the prefix puts
/// the mantissa in [1, 1000), shown with 1 decimal below 100 and no decimal
/// from 100 up. `None` for a non-finite or non-positive value -- the caller
/// renders its own "absent" form ("0 <unit>" for `format_si`, "-" for
/// `format_fan_rpm`).
fn si_mantissa_and_prefix(value_base: f64) -> Option<(String, &'static str)> {
if !value_base.is_finite() || value_base <= 0.0 {
return format!("0 {unit}");
return None;
}
const PREFIXES: [&str; 8] = ["", "k", "M", "G", "T", "P", "E", "Z"];
let mut v = value_base;
@@ -42,7 +44,90 @@ pub fn format_si(value_base: f64, unit: &str) -> String {
} else if num == "100.0" {
num = "100".to_string();
}
format!("{num} {}{unit}", PREFIXES[i])
Some((num, PREFIXES[i]))
}
/// Format a value in its base unit with an SI prefix chosen so the number stays
/// compact: the prefix puts the mantissa in [1, 1000), then it is shown with 1
/// decimal below 100 and no decimal from 100 up (so 21300 W -> "21.3 kW",
/// 685e12 H/s -> "685 TH/s", 6.8e12 -> "6.8 TH/s"). Zero renders as "0 <unit>".
pub fn format_si(value_base: f64, unit: &str) -> String {
match si_mantissa_and_prefix(value_base) {
Some((num, prefix)) => format!("{num} {prefix}{unit}"),
None => format!("0 {unit}"),
}
}
/// Like `format_si` but for a cooling-fan RPM reading: no unit/space suffix,
/// and "-" (rather than "0") for an absent/non-positive reading, since a fan
/// column packs several of these per cell (see `Column::Cooling`).
pub fn format_fan_rpm(rpm: f64) -> String {
match si_mantissa_and_prefix(rpm) {
Some((num, prefix)) => format!("{num}{prefix}"),
None => "-".to_string(),
}
}
/// The actual/expected ratio, or `None` when the expected value is unknown
/// (<= 0.0) so a ratio-based color/warning never divides by zero or treats an
/// unknown expectation as a 0% shortfall.
pub fn actual_expected_ratio(actual: f64, expected: f64) -> Option<f64> {
if expected > 0.0 { Some(actual / expected) } else { None }
}
/// Render a combined "actual / expected" cell for a value shown against its
/// model-expected counterpart (UI-SPEC combined columns: Hashrate,
/// Hashboards, TotalChips): blank when neither is known, the bare actual
/// when only it is known, "- / <expected>" when only the expected is known,
/// and "<actual> / <expected>" when both are.
fn combined_si(actual_ths: f64, expected_ths: f64) -> String {
let actual = (actual_ths > 0.0).then(|| format_si(actual_ths * 1e12, "H/s"));
let expected = (expected_ths > 0.0).then(|| format_si(expected_ths * 1e12, "H/s"));
match (actual, expected) {
(None, None) => String::new(),
(Some(a), None) => a,
(None, Some(e)) => format!("- / {e}"),
(Some(a), Some(e)) => format!("{a} / {e}"),
}
}
/// Same combined rendering as `combined_si`, for a plain integer count
/// (hashboards, total chips) instead of an SI-formatted rate.
fn combined_count(actual: Option<u32>, expected: Option<u32>) -> String {
match (actual, expected) {
(None, None) => String::new(),
(Some(a), None) => a.to_string(),
(None, Some(e)) => format!("- / {e}"),
(Some(a), Some(e)) => format!("{a} / {e}"),
}
}
/// Encode colored text segments for a custom-rendered cell (see the wx-rs
/// `SegmentRenderer`): segments are joined by U+001F, and within a segment an
/// optional uppercase RRGGBB color is separated from its text by U+001E.
/// `decode_segments_plain` is the inverse for anything that just wants the
/// plain text (filtering, sorting, tests).
pub fn encode_segments(segs: &[(Option<(u8, u8, u8)>, String)]) -> String {
segs.iter()
.map(|(color, text)| {
let hex = color.map(|(r, g, b)| format!("{r:02X}{g:02X}{b:02X}")).unwrap_or_default();
format!("{hex}\u{1e}{text}")
})
.collect::<Vec<_>>()
.join("\u{1f}")
}
/// Strip the encoding `encode_segments` applies, returning just the
/// concatenated text. A plain string with no U+001E in it (i.e. never passed
/// through `encode_segments`) round-trips unchanged, so this is safe to call
/// on any cell value.
pub fn decode_segments_plain(s: &str) -> String {
if !s.contains('\u{1e}') {
return s.to_string();
}
s.split('\u{1f}')
.map(|seg| seg.split_once('\u{1e}').map(|(_, text)| text).unwrap_or(seg))
.collect::<String>()
}
/// Compact human duration (e.g. "3d 4h", "5h 12m", "42m", "18s").
@@ -67,8 +152,9 @@ pub fn format_uptime(secs: u64) -> String {
/// Pack a dotted-quad IPv4 string into a u32 for numeric ordering, so
/// "10.255.1.9" sorts before "10.255.1.10" (a plain string sort gets this
/// wrong). Anything unparseable sorts first (0).
fn ip_to_u32(s: &str) -> u32 {
/// wrong). Anything unparseable sorts first (0). `pub(crate)` so the headless
/// self-test can build the same numeric order it asserts the view against.
pub(crate) fn ip_to_u32(s: &str) -> u32 {
let mut parts = s.split('.');
let mut acc = 0u32;
for _ in 0..4 {
@@ -78,6 +164,52 @@ fn ip_to_u32(s: &str) -> u32 {
acc
}
/// What a miner supports being told to do, probed from asic-rs' `supports_*`
/// capability methods at scan time. The right-click menu offers an action only
/// when every selected miner supports it (the intersection of capabilities).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MinerCaps {
pub fault_light: bool,
pub restart: bool,
pub pause: bool,
pub resume: bool,
pub power_limit: bool,
pub tuning: bool,
/// Whether this miner's asic-rs driver supports `upgrade_firmware`
/// (probed via `supports_upgrade_firmware()` at scan time).
pub firmware_flash: bool,
}
impl MinerCaps {
/// The capabilities common to `self` and `other` (logical AND per action).
pub fn intersect(self, other: MinerCaps) -> MinerCaps {
MinerCaps {
fault_light: self.fault_light && other.fault_light,
restart: self.restart && other.restart,
pause: self.pause && other.pause,
resume: self.resume && other.resume,
power_limit: self.power_limit && other.power_limit,
tuning: self.tuning && other.tuning,
firmware_flash: self.firmware_flash && other.firmware_flash,
}
}
/// The capabilities common to every miner in `caps` (all-true identity when
/// empty is intentionally avoided: an empty selection has no common caps).
pub fn intersect_all(caps: impl IntoIterator<Item = MinerCaps>) -> MinerCaps {
let mut it = caps.into_iter();
match it.next() {
Some(first) => it.fold(first, MinerCaps::intersect),
None => MinerCaps::default(),
}
}
/// True when no action is supported (nothing to offer in the menu).
pub fn is_empty(self) -> bool {
self == MinerCaps::default()
}
}
/// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the
/// scalar fields the table can display. Absent metrics are `None` / empty /
/// 0.0 and render as a blank cell.
@@ -85,6 +217,8 @@ fn ip_to_u32(s: &str) -> u32 {
pub struct MinerRow {
pub ip: String,
pub selected: bool,
/// What this miner supports being told to do (for the right-click menu).
pub caps: MinerCaps,
// identity
pub model: String,
pub mac: String,
@@ -104,7 +238,9 @@ pub struct MinerRow {
pub chip_temp_c: f64,
pub fluid_temp_c: f64,
pub outlet_temp_c: f64,
pub fan_rpm: f64,
/// Individual cooling-fan RPMs (empty if unknown). PSU fan is tracked
/// separately below since it is not part of the cooling-fan set.
pub fan_rpms: Vec<f64>,
pub psu_fan_rpm: f64,
pub fan_count: Option<u32>,
pub expected_fans: Option<u32>,
@@ -127,12 +263,36 @@ pub struct MinerRow {
pub operating_state: String,
pub is_mining: bool,
pub slow: bool,
/// Not-mining because an operator paused it (distinct from simply idle);
/// see `is_paused`.
pub paused: bool,
/// Whether this miner FAILED to respond to the scan. Stored as `offline`
/// (not `online`) so `Default` gives `false` -- i.e. a plain
/// `MinerRow { ..Default::default() }` is a reachable row, and only
/// `MinerRow::offline` deliberately marks a row unreachable. This removes
/// the old footgun where a struct-update literal that forgot `online: true`
/// silently read back as offline.
pub offline: bool,
}
impl MinerRow {
/// A miner that did not respond to this scan attempt: ip only, every
/// other field blank/zero/false, `offline: true` so `status()` reports
/// "offline".
pub fn offline(ip: String) -> MinerRow {
let mut r = MinerRow::default();
r.ip = ip;
r.offline = true;
r
}
pub fn status(&self) -> &'static str {
if self.slow {
if self.offline {
"offline"
} else if self.slow {
"slow"
} else if self.paused {
"paused"
} else if self.is_mining {
"hashing"
} else {
@@ -153,6 +313,22 @@ impl MinerRow {
}
}
/// The single source of truth for the "paused" classification: a miner is
/// counted as operator-paused when it is not currently mining and its raw
/// operating-state string says so (case-insensitively), shared by the live
/// scan (`scan::to_row`) and the fixtures/tests.
pub fn is_paused(operating_state: &str, is_mining: bool) -> bool {
!is_mining && operating_state.to_lowercase().contains("pause")
}
/// The typed-confirmation gate for the irreversible firmware-flash action: the
/// operator must type exactly "FLASH" (surrounding whitespace ignored, but not
/// case-folded and not a prefix). Pure so the guard is unit-testable without a
/// live dialog.
pub fn flash_confirmed(input: &str) -> bool {
input.trim() == "FLASH"
}
/// 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
/// the old checkbox column.
@@ -167,7 +343,6 @@ pub enum Column {
Worker,
Model,
Status,
ExpectedHashrate,
Efficiency,
FluidTemp,
OutletTemp,
@@ -175,9 +350,7 @@ pub enum Column {
FanCount,
ExpectedFans,
TotalChips,
ExpectedChips,
Hashboards,
ExpectedHashboards,
Mac,
Hostname,
Serial,
@@ -200,7 +373,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; 35] = [
Column::Ip,
Column::Hashrate,
Column::Power,
@@ -210,7 +383,6 @@ pub const ALL_COLUMNS: [Column; 38] = [
Column::Worker,
Column::Model,
Column::Status,
Column::ExpectedHashrate,
Column::Efficiency,
Column::FluidTemp,
Column::OutletTemp,
@@ -218,9 +390,7 @@ pub const ALL_COLUMNS: [Column; 38] = [
Column::FanCount,
Column::ExpectedFans,
Column::TotalChips,
Column::ExpectedChips,
Column::Hashboards,
Column::ExpectedHashboards,
Column::Mac,
Column::Hostname,
Column::Serial,
@@ -265,7 +435,6 @@ impl Column {
Column::Worker => "Pool worker",
Column::Model => "Model",
Column::Status => "Status",
Column::ExpectedHashrate => "Expected HR",
Column::Efficiency => "Efficiency (J/TH)",
Column::FluidTemp => "Fluid temp",
Column::OutletTemp => "Outlet temp",
@@ -273,9 +442,7 @@ impl Column {
Column::FanCount => "Fans",
Column::ExpectedFans => "Fans (exp)",
Column::TotalChips => "Chips",
Column::ExpectedChips => "Chips (exp)",
Column::Hashboards => "Boards",
Column::ExpectedHashboards => "Boards (exp)",
Column::Mac => "MAC",
Column::Hostname => "Hostname",
Column::Serial => "Serial",
@@ -300,7 +467,7 @@ impl Column {
pub fn width(self) -> i32 {
match self {
Column::Ip => 130,
Column::Hashrate | Column::ExpectedHashrate => 110,
Column::Hashrate => 110,
Column::Power => 90,
Column::ChipTemp | Column::FluidTemp | Column::OutletTemp => 95,
Column::Cooling | Column::PsuFan => 100,
@@ -310,10 +477,7 @@ impl Column {
Column::Status => 95,
Column::Efficiency => 120,
Column::FanCount | Column::TotalChips | Column::Hashboards => 70,
Column::ExpectedFans
| Column::ExpectedChips
| Column::ExpectedHashboards
| Column::TuningPercent => 90,
Column::ExpectedFans | Column::TuningPercent => 90,
Column::Mac | Column::Hostname | Column::Serial => 150,
Column::ApiVersion | Column::Light => 90,
Column::ControlBoard => 130,
@@ -332,7 +496,6 @@ impl Column {
matches!(
self,
Column::Hashrate
| Column::ExpectedHashrate
| Column::Power
| Column::Efficiency
| Column::ChipTemp
@@ -343,9 +506,7 @@ impl Column {
| Column::FanCount
| Column::ExpectedFans
| Column::TotalChips
| Column::ExpectedChips
| Column::Hashboards
| Column::ExpectedHashboards
| Column::Uptime
| Column::BestShare
| Column::SessionBestShare
@@ -353,6 +514,32 @@ impl Column {
)
}
/// The numeric value used for numeric filtering, or `None` for a text column
/// or a blank/missing cell (so `> 0` never matches an absent metric). A
/// "blank" cell is exactly one the table renders empty -- several value-type
/// columns store an absent reading as 0.0, which `cell()` blanks; mirror that
/// here so a filter like "ChipTemp <= 50" cannot match a miner with no
/// temperature reading.
pub fn num_value(&self, r: &MinerRow) -> Option<f64> {
// The 3 combined (actual/expected) columns must never let a numeric
// filter match a row that only has an expected value: their cell()
// renders "- / <expected>" (non-empty) in that case, so the generic
// blank check below is not enough on its own.
match self {
Column::Hashrate if r.hashrate_ths <= 0.0 => return None,
Column::Hashboards if r.hashboards.is_none() => return None,
Column::TotalChips if r.total_chips.is_none() => return None,
_ => {}
}
if !self.is_numeric() || self.cell(r).is_empty() {
return None;
}
match self.sort_key(r) {
SortKey::Num(v) if v.is_finite() => Some(v),
_ => None,
}
}
/// Sort key. Numeric columns compare by their underlying number (absent =
/// -inf so blanks sort to the bottom of a descending sort); others compare
/// as lowercase strings.
@@ -360,22 +547,21 @@ impl Column {
let none = f64::NEG_INFINITY;
match self {
Column::Hashrate => SortKey::Num(r.hashrate_ths),
Column::ExpectedHashrate => SortKey::Num(r.expected_ths),
Column::Power => SortKey::Num(r.power_w),
Column::Efficiency => SortKey::Num(if r.efficiency > 0.0 { r.efficiency } else { none }),
Column::ChipTemp => SortKey::Num(r.chip_temp_c),
Column::FluidTemp => SortKey::Num(r.fluid_temp_c),
Column::OutletTemp => SortKey::Num(r.outlet_temp_c),
Column::Cooling => SortKey::Num(r.fan_rpm),
Column::Cooling => SortKey::Num(if r.fan_rpms.is_empty() {
none
} else {
r.fan_rpms.iter().cloned().fold(f64::INFINITY, f64::min)
}),
Column::PsuFan => SortKey::Num(r.psu_fan_rpm),
Column::FanCount => SortKey::Num(r.fan_count.map(|v| v as f64).unwrap_or(none)),
Column::ExpectedFans => SortKey::Num(r.expected_fans.map(|v| v as f64).unwrap_or(none)),
Column::TotalChips => SortKey::Num(r.total_chips.map(|v| v as f64).unwrap_or(none)),
Column::ExpectedChips => SortKey::Num(r.expected_chips.map(|v| v as f64).unwrap_or(none)),
Column::Hashboards => SortKey::Num(r.hashboards.map(|v| v as f64).unwrap_or(none)),
Column::ExpectedHashboards => {
SortKey::Num(r.expected_hashboards.map(|v| v as f64).unwrap_or(none))
}
Column::Uptime => SortKey::Num(if r.uptime_secs > 0 { r.uptime_secs as f64 } else { none }),
Column::BestShare => SortKey::Num(r.best_share.unwrap_or(none)),
Column::SessionBestShare => SortKey::Num(r.session_best_share.unwrap_or(none)),
@@ -404,20 +590,7 @@ impl Column {
let pool_worker = |i: usize| r.pools.get(i).map(|(_, w)| w.clone()).unwrap_or_default();
match self {
Column::Ip => r.ip.clone(),
Column::Hashrate => {
if r.hashrate_ths > 0.0 {
format_si(r.hashrate_ths * 1e12, "H/s")
} else {
String::new()
}
}
Column::ExpectedHashrate => {
if r.expected_ths > 0.0 {
format_si(r.expected_ths * 1e12, "H/s")
} else {
String::new()
}
}
Column::Hashrate => combined_si(r.hashrate_ths, r.expected_ths),
Column::Power => {
if r.power_w > 0.0 {
format_si(r.power_w, "W")
@@ -429,14 +602,14 @@ impl Column {
Column::ChipTemp => num(r.chip_temp_c, 1, " C"),
Column::FluidTemp => num(r.fluid_temp_c, 1, " C"),
Column::OutletTemp => num(r.outlet_temp_c, 1, " C"),
Column::Cooling => num(r.fan_rpm, 0, ""),
Column::Cooling => {
r.fan_rpms.iter().map(|&v| format_fan_rpm(v)).collect::<Vec<_>>().join("/")
}
Column::PsuFan => num(r.psu_fan_rpm, 0, ""),
Column::FanCount => count(r.fan_count),
Column::ExpectedFans => count(r.expected_fans),
Column::TotalChips => count(r.total_chips),
Column::ExpectedChips => count(r.expected_chips),
Column::Hashboards => count(r.hashboards),
Column::ExpectedHashboards => count(r.expected_hashboards),
Column::TotalChips => combined_count(r.total_chips, r.expected_chips),
Column::Hashboards => combined_count(r.hashboards, r.expected_hashboards),
Column::Firmware => r.firmware.clone(),
Column::Worker => r.worker.clone(),
Column::PoolUrl => r.pool_url.clone(),
@@ -474,14 +647,78 @@ pub enum SortKey {
Str(String),
}
/// Text-column filter operators (Excel-style text filters).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextOp {
Contains,
NotContains,
BeginsWith,
EndsWith,
Equals,
}
/// Numeric-column filter operators (Excel-style number filters).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumOp {
Between,
Eq,
Ne,
Gt,
Ge,
Lt,
Le,
}
/// 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.
#[derive(Debug, Clone)]
pub enum ColFilter {
Values(HashSet<String>),
Text { op: TextOp, needle: String },
Num { op: NumOp, a: f64, b: f64 },
}
impl ColFilter {
/// Does `r`'s value in `col` satisfy this filter?
pub fn matches(&self, col: Column, r: &MinerRow) -> bool {
match self {
ColFilter::Values(set) => set.contains(&col.cell(r)),
ColFilter::Text { op, needle } => {
let hay = col.cell(r).to_lowercase();
let n = needle.to_lowercase();
match op {
TextOp::Contains => hay.contains(&n),
TextOp::NotContains => !hay.contains(&n),
TextOp::BeginsWith => hay.starts_with(&n),
TextOp::EndsWith => hay.ends_with(&n),
TextOp::Equals => hay == n,
}
}
ColFilter::Num { op, a, b } => {
let Some(v) = col.num_value(r) else { return false };
let (a, b) = (*a, *b);
match op {
NumOp::Between => v >= a.min(b) && v <= a.max(b),
NumOp::Eq => v == a,
NumOp::Ne => v != a,
NumOp::Gt => v > a,
NumOp::Ge => v >= a,
NumOp::Lt => v < a,
NumOp::Le => v <= a,
}
}
}
}
}
/// Display state: order, visibility, sort, filter.
pub struct ViewState {
/// Model column order as displayed (Ip is always the first visible column).
pub order: Vec<Column>,
pub visible: HashSet<Column>,
pub sort: Option<(Column, bool)>, // (column, ascending)
/// Per-column allowed values; None = unfiltered.
pub filters: HashMap<Column, HashSet<String>>,
/// Active per-column filters (AND across columns); empty = unfiltered.
pub filters: HashMap<Column, ColFilter>,
}
impl Default for ViewState {
@@ -532,11 +769,9 @@ impl ViewState {
.collect();
}
/// Rows that pass every active filter (AND across columns, OR within one).
/// Rows that pass every active filter (AND across columns).
pub fn passes_filters(&self, r: &MinerRow) -> bool {
self.filters
.iter()
.all(|(col, allowed)| allowed.contains(&col.cell(r)))
self.filters.iter().all(|(col, f)| f.matches(*col, r))
}
/// Filtered + sorted rows in display order.
@@ -565,26 +800,39 @@ impl ViewState {
}
}
/// The six KPIs (UI-SPEC header), derived from the filtered view.
/// The KPIs (UI-SPEC header), derived from the filtered view. There is no
/// separate "offline" bucket: an offline row is (by construction) neither
/// slow, paused, nor mining, so it folds into `not_hashing`.
pub struct Kpis {
pub total: usize,
pub hashing: usize,
pub slow: usize,
pub not_hashing: usize,
pub paused: usize,
pub total_hashrate_ths: f64,
pub total_power_w: f64,
}
pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
let mut k = Kpis { total: view_idx.len(), hashing: 0, slow: 0, not_hashing: 0, total_hashrate_ths: 0.0, total_power_w: 0.0 };
let mut k = Kpis {
total: view_idx.len(),
hashing: 0,
slow: 0,
not_hashing: 0,
paused: 0,
total_hashrate_ths: 0.0,
total_power_w: 0.0,
};
for &i in view_idx {
let r = &rows[i];
if r.slow {
k.slow += 1;
} else if r.is_mining {
k.hashing += 1;
} else {
k.not_hashing += 1;
// Bucket by the same precedence status() uses, so the KPI header can
// never disagree with a row's own status text. There is no separate
// "offline" KPI, so offline folds into not_hashing (the `_` arm).
match r.status() {
"slow" => k.slow += 1,
"paused" => k.paused += 1,
"hashing" => k.hashing += 1,
_ => k.not_hashing += 1,
}
k.total_hashrate_ths += r.hashrate_ths;
k.total_power_w += r.power_w;
@@ -609,15 +857,39 @@ mod tests {
#[test]
fn kpis_match_expected_hardware_output() {
// Round-6 fixtures are being rebucketed concurrently (an idle board
// moved into "paused", a new offline row added), so this does not
// hardcode fixture counts: it independently recomputes each expected
// KPI bucket and sum straight from the rows (via `status()`, a
// separate code path from `compute_kpis`'s own if/else chain) and
// cross-checks `compute_kpis`'s output against that.
let (rows, _v, idx) = full_view();
let k = compute_kpis(&rows, &idx);
assert_eq!(k.total, 9, "total miners");
assert_eq!(k.hashing, 6, "hashing");
assert_eq!(k.slow, 1, "slow");
assert_eq!(k.not_hashing, 2, "not hashing");
assert!((k.total_hashrate_ths - 685.0).abs() < 1e-9, "hashrate {}", k.total_hashrate_ths);
assert!((k.total_power_w - 21300.0).abs() < 1e-9, "power {}", k.total_power_w);
assert_eq!(k.total, k.hashing + k.slow + k.not_hashing);
let mut exp_hashing = 0usize;
let mut exp_slow = 0usize;
let mut exp_paused = 0usize;
let mut exp_not_hashing = 0usize;
for &i in &idx {
match rows[i].status() {
"slow" => exp_slow += 1,
"paused" => exp_paused += 1,
"hashing" => exp_hashing += 1,
// offline folds into not_hashing for KPIs (no separate bucket).
"not hashing" | "offline" => exp_not_hashing += 1,
other => panic!("unexpected status: {other}"),
}
}
assert_eq!(k.hashing, exp_hashing, "hashing");
assert_eq!(k.slow, exp_slow, "slow");
assert_eq!(k.paused, exp_paused, "paused");
assert_eq!(k.not_hashing, exp_not_hashing, "not hashing");
let exp_hashrate: f64 = idx.iter().map(|&i| rows[i].hashrate_ths).sum();
let exp_power: f64 = idx.iter().map(|&i| rows[i].power_w).sum();
assert!((k.total_hashrate_ths - exp_hashrate).abs() < 1e-9, "hashrate {}", k.total_hashrate_ths);
assert!((k.total_power_w - exp_power).abs() < 1e-9, "power {}", k.total_power_w);
assert_eq!(k.total, k.hashing + k.slow + k.not_hashing + k.paused);
}
#[test]
@@ -649,20 +921,23 @@ mod tests {
assert_eq!(Column::Status.cell(s17), "not hashing");
let s21 = rows.iter().find(|r| r.ip == "10.255.1.149").unwrap();
assert_eq!(Column::Hashrate.cell(s21), "60.0 TH/s");
// Combined actual/expected cell: both known -> "<actual> / <expected>".
assert_eq!(Column::Hashrate.cell(s21), "60.0 TH/s / 200 TH/s");
assert_eq!(Column::Power.cell(s21), "1.5 kW");
assert_eq!(Column::Status.cell(s21), "slow");
}
#[test]
fn default_view_sorts_by_ip_ascending() {
// Fixture count/IPs are not hardcoded here (round-6 fixtures are being
// extended concurrently): recompute the expected numeric-IP order
// straight from the rows instead.
let (rows, _v, idx) = full_view();
let ips: Vec<String> = idx.iter().map(|&i| rows[i].ip.clone()).collect();
assert_eq!(ips.len(), 9);
let mut sorted = ips.clone();
sorted.sort();
assert_eq!(ips, sorted, "default view should be IP-ascending");
assert_eq!(ips[0], "10.255.1.112");
assert_eq!(ips.len(), rows.len(), "the default view has no filters");
let mut expected: Vec<String> = rows.iter().map(|r| r.ip.clone()).collect();
expected.sort_by_key(|ip| ip_to_u32(ip));
assert_eq!(ips, expected, "default view should be IP-ascending (numeric)");
}
#[test]
@@ -684,7 +959,7 @@ mod tests {
let mut view = ViewState::default();
let mut allowed = HashSet::new();
allowed.insert("slow".to_string());
view.filters.insert(Column::Status, allowed);
view.filters.insert(Column::Status, ColFilter::Values(allowed));
let idx = view.view(&rows);
assert_eq!(idx.len(), 1);
assert_eq!(rows[idx[0]].ip, "10.255.1.149");
@@ -764,7 +1039,7 @@ mod tests {
expected_ths: 200.0,
power_w: 3000.0 + (i % 500) as f64,
chip_temp_c: 55.0 + (i % 25) as f64,
fan_rpm: 4000.0 + (i % 900) as f64,
fan_rpms: vec![4000.0 + (i % 900) as f64],
is_mining: i % 7 != 0,
model: format!("Model-{}", i % 12),
firmware: format!("fw-{}", i % 6),
@@ -938,8 +1213,8 @@ mod tests {
MinerRow { ip: "10.0.0.3".into(), is_mining: false, model: "A".into(), ..Default::default() },
];
let mut view = ViewState::default();
view.filters.insert(Column::Status, HashSet::from(["hashing".to_string()]));
view.filters.insert(Column::Model, HashSet::from(["A".to_string()]));
view.filters.insert(Column::Status, ColFilter::Values(HashSet::from(["hashing".to_string()])));
view.filters.insert(Column::Model, ColFilter::Values(HashSet::from(["A".to_string()])));
let idx = view.view(&rows);
assert_eq!(idx.len(), 1, "only the hashing AND model-A row passes");
assert_eq!(rows[idx[0]].ip, "10.0.0.1");
@@ -948,14 +1223,16 @@ mod tests {
#[test]
fn passes_filters_ors_within_one_column() {
let rows = bench_fleet();
// Not hardcoded (fixture composition is changing concurrently):
// recompute the expected count straight from the rows' own status().
let expected = rows.iter().filter(|r| matches!(r.status(), "slow" | "not hashing")).count();
let mut view = ViewState::default();
view.filters.insert(
Column::Status,
HashSet::from(["slow".to_string(), "not hashing".to_string()]),
ColFilter::Values(HashSet::from(["slow".to_string(), "not hashing".to_string()])),
);
let idx = view.view(&rows);
// fixtures: 1 slow + 2 not-hashing.
assert_eq!(idx.len(), 3);
assert_eq!(idx.len(), expected);
}
#[test]
@@ -1027,7 +1304,7 @@ mod tests {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let mut view = ViewState::default();
view.filters.insert(Column::Model, HashSet::from(["Model-3".to_string()]));
view.filters.insert(Column::Model, ColFilter::Values(HashSet::from(["Model-3".to_string()])));
view.sort = Some((Column::Hashrate, false));
let iters = 200u32;
let t = Instant::now();
@@ -1057,4 +1334,279 @@ mod tests {
println!("bench_upsert_cold_start_population: {n} rows cold-start = {:?}", elapsed);
assert!(elapsed.as_millis() < 2000, "cold-start upsert regressed: {elapsed:?} for {n} rows");
}
// ---- Excel-style column filters (round 3) ----
#[test]
fn text_filter_operators_are_case_insensitive() {
let r = MinerRow { firmware: "WMOS H616".into(), ..Default::default() };
let c = Column::Firmware;
let t = |op, needle: &str| ColFilter::Text { op, needle: needle.into() }.matches(c, &r);
assert!(t(TextOp::Contains, "wmos"));
assert!(!t(TextOp::Contains, "vnish"));
assert!(!t(TextOp::NotContains, "wmos"));
assert!(t(TextOp::NotContains, "vnish"));
assert!(t(TextOp::BeginsWith, "WMOS"));
assert!(!t(TextOp::BeginsWith, "616"));
assert!(t(TextOp::EndsWith, "h616"));
assert!(t(TextOp::Equals, "wmos h616"));
assert!(!t(TextOp::Equals, "wmos"));
}
#[test]
fn numeric_filter_operators() {
let r = MinerRow { hashrate_ths: 100.0, is_mining: true, ..Default::default() };
let c = Column::Hashrate;
let n = |op, a: f64, b: f64| ColFilter::Num { op, a, b }.matches(c, &r);
assert!(n(NumOp::Gt, 50.0, 0.0));
assert!(!n(NumOp::Gt, 150.0, 0.0));
assert!(n(NumOp::Ge, 100.0, 0.0));
assert!(n(NumOp::Lt, 150.0, 0.0));
assert!(n(NumOp::Le, 100.0, 0.0));
assert!(n(NumOp::Eq, 100.0, 0.0));
assert!(n(NumOp::Ne, 99.0, 0.0));
assert!(n(NumOp::Between, 90.0, 110.0));
assert!(n(NumOp::Between, 110.0, 90.0), "bounds are order-agnostic");
assert!(!n(NumOp::Between, 0.0, 50.0));
}
#[test]
fn num_value_none_for_text_and_blank() {
let r = MinerRow { firmware: "x".into(), efficiency: 0.0, ..Default::default() };
assert_eq!(Column::Firmware.num_value(&r), None, "text column");
assert_eq!(Column::Ip.num_value(&r), None, "IP is text, not numeric");
assert_eq!(Column::Efficiency.num_value(&r), None, "blank numeric -> None");
let r2 = MinerRow { hashrate_ths: 42.0, ..Default::default() };
assert_eq!(Column::Hashrate.num_value(&r2), Some(42.0));
}
#[test]
fn caps_intersection_is_the_common_actions() {
let full = MinerCaps {
fault_light: true,
restart: true,
pause: true,
resume: true,
power_limit: true,
tuning: true,
firmware_flash: true,
};
let idle = MinerCaps { fault_light: true, restart: true, ..Default::default() };
// Two full miners keep every action.
assert_eq!(MinerCaps::intersect_all([full, full]), full);
// A full + idle mix keeps only what both support.
assert_eq!(MinerCaps::intersect_all([full, idle]), idle);
// A single miner's caps are its own.
assert_eq!(MinerCaps::intersect_all([full]), full);
// Empty selection -> nothing common.
assert_eq!(MinerCaps::intersect_all([]), MinerCaps::default());
assert!(MinerCaps::default().is_empty());
assert!(!full.is_empty());
}
#[test]
fn numeric_filter_excludes_blank_cells() {
// A blank-displaying value-type cell (absent reading stored as 0.0) must
// not match a numeric predicate -- it has no value to compare.
let blank = MinerRow { hashrate_ths: 0.0, chip_temp_c: 0.0, power_w: 0.0, is_mining: false, ..Default::default() };
assert_eq!(Column::Hashrate.num_value(&blank), None);
assert_eq!(Column::ChipTemp.num_value(&blank), None);
assert_eq!(Column::Power.num_value(&blank), None);
// "<= 50" and "<= 1000" must NOT match a miner with no temp / power.
assert!(!ColFilter::Num { op: NumOp::Le, a: 50.0, b: 0.0 }.matches(Column::ChipTemp, &blank));
assert!(!ColFilter::Num { op: NumOp::Lt, a: 1000.0, b: 0.0 }.matches(Column::Power, &blank));
// A real reading still matches.
let live = MinerRow { chip_temp_c: 45.0, is_mining: true, ..Default::default() };
assert!(ColFilter::Num { op: NumOp::Le, a: 50.0, b: 0.0 }.matches(Column::ChipTemp, &live));
}
// ---- round 6: offline/paused rows, combined columns, fan RPMs, segments ----
#[test]
fn format_fan_rpm_boundaries() {
assert_eq!(format_fan_rpm(0.0), "-");
assert_eq!(format_fan_rpm(-100.0), "-");
assert_eq!(format_fan_rpm(f64::NAN), "-");
assert_eq!(format_fan_rpm(f64::INFINITY), "-");
assert_eq!(format_fan_rpm(950.0), "950");
assert_eq!(format_fan_rpm(4200.0), "4.2k");
// Shares format_si's rounding-rollover and >=100 rules.
assert_eq!(format_fan_rpm(99.95), "100");
assert_eq!(format_fan_rpm(999.9), "1.0k");
}
#[test]
fn combined_cell_all_four_cases() {
let neither = MinerRow::default();
assert_eq!(Column::Hashrate.cell(&neither), "", "both unknown -> blank");
assert_eq!(Column::Hashboards.cell(&neither), "");
assert_eq!(Column::TotalChips.cell(&neither), "");
let actual_only = MinerRow {
hashrate_ths: 60.0,
hashboards: Some(3),
total_chips: Some(210),
..Default::default()
};
assert_eq!(Column::Hashrate.cell(&actual_only), "60.0 TH/s", "only actual -> bare actual");
assert_eq!(Column::Hashboards.cell(&actual_only), "3");
assert_eq!(Column::TotalChips.cell(&actual_only), "210");
let expected_only = MinerRow {
expected_ths: 200.0,
expected_hashboards: Some(3),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.cell(&expected_only), "- / 200 TH/s", "only expected -> '- / <expected>'");
assert_eq!(Column::Hashboards.cell(&expected_only), "- / 3");
assert_eq!(Column::TotalChips.cell(&expected_only), "- / 228");
let both = MinerRow {
hashrate_ths: 60.0,
expected_ths: 200.0,
hashboards: Some(3),
expected_hashboards: Some(3),
total_chips: Some(190),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.cell(&both), "60.0 TH/s / 200 TH/s", "both known -> '<actual> / <expected>'");
assert_eq!(Column::Hashboards.cell(&both), "3 / 3");
assert_eq!(Column::TotalChips.cell(&both), "190 / 228");
}
#[test]
fn num_value_none_when_only_expected_known() {
// A numeric filter must never match a row that only has an expected
// value -- there is no actual reading to compare.
let expected_only = MinerRow {
expected_ths: 200.0,
expected_hashboards: Some(3),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.num_value(&expected_only), None);
assert_eq!(Column::Hashboards.num_value(&expected_only), None);
assert_eq!(Column::TotalChips.num_value(&expected_only), None);
let both = MinerRow {
hashrate_ths: 60.0,
expected_ths: 200.0,
hashboards: Some(3),
expected_hashboards: Some(3),
total_chips: Some(190),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.num_value(&both), Some(60.0));
assert_eq!(Column::Hashboards.num_value(&both), Some(3.0));
assert_eq!(Column::TotalChips.num_value(&both), Some(190.0));
}
#[test]
fn cooling_column_joins_fan_rpms_and_sorts_by_min() {
let r = MinerRow { fan_rpms: vec![4200.0, 3990.0, 4500.0], ..Default::default() };
assert_eq!(Column::Cooling.cell(&r), "4.2k/4.0k/4.5k");
assert_eq!(Column::Cooling.num_value(&r), Some(3990.0));
let none = MinerRow::default();
assert_eq!(Column::Cooling.cell(&none), "");
assert_eq!(Column::Cooling.num_value(&none), None);
}
#[test]
fn segments_round_trip_and_plain_passthrough() {
let segs = vec![(Some((255u8, 0u8, 0u8)), "Err".to_string()), (None, ": offline".to_string())];
let encoded = encode_segments(&segs);
assert_eq!(encoded, "FF0000\u{1e}Err\u{1f}\u{1e}: offline");
assert_eq!(decode_segments_plain(&encoded), "Err: offline");
// A plain string with no segment markers round-trips unchanged.
assert_eq!(decode_segments_plain("10.255.1.9"), "10.255.1.9");
assert_eq!(decode_segments_plain(""), "");
}
#[test]
fn actual_expected_ratio_handles_unknown_expected() {
// 50/200 = 0.25 is exactly representable, so this is a safe exact
// comparison (unlike e.g. 60/200, whose nearest-double result is not
// guaranteed to bit-match a decimal literal).
assert_eq!(actual_expected_ratio(50.0, 200.0), Some(0.25));
assert_eq!(actual_expected_ratio(60.0, 0.0), None);
assert_eq!(actual_expected_ratio(0.0, 0.0), None);
}
#[test]
fn status_offline_and_paused() {
let offline = MinerRow::offline("10.1.2.3".into());
assert_eq!(offline.status(), "offline");
assert!(offline.offline);
assert_eq!(offline.ip, "10.1.2.3");
assert_eq!(offline.hashrate_ths, 0.0, "offline row is otherwise blank");
// A plain default row is online (offline: false), so a struct-update
// literal that forgets to say so is reachable, not silently offline.
let default_is_online = MinerRow { ..Default::default() };
assert!(!default_is_online.offline, "Default row must be online");
assert_eq!(default_is_online.status(), "not hashing");
let paused = MinerRow { paused: true, ..Default::default() };
assert_eq!(paused.status(), "paused");
let hashing = MinerRow { is_mining: true, ..Default::default() };
assert_eq!(hashing.status(), "hashing");
let not_hashing = MinerRow { ..Default::default() };
assert_eq!(not_hashing.status(), "not hashing");
// offline outranks slow/paused/hashing in the precedence order.
let offline_but_flagged =
MinerRow { offline: true, slow: true, paused: true, is_mining: true, ..Default::default() };
assert_eq!(offline_but_flagged.status(), "offline");
// slow outranks paused (and hashing).
let slow_and_paused = MinerRow { slow: true, paused: true, ..Default::default() };
assert_eq!(slow_and_paused.status(), "slow");
}
#[test]
fn is_paused_detection() {
assert!(is_paused("Paused", false));
assert!(is_paused("PAUSED (manual)", false));
assert!(!is_paused("Paused", true), "mining overrides an even stale 'paused' state string");
assert!(!is_paused("Mining", false));
assert!(!is_paused("", false));
}
#[test]
fn kpis_bucket_by_status_not_raw_flags() {
// An offline row that also carries stale slow/paused/mining flags must
// count as not_hashing (matching status() == "offline"), never as slow
// or paused -- i.e. compute_kpis and status() can't diverge.
let rows = vec![
MinerRow { offline: true, slow: true, paused: true, is_mining: true, ..Default::default() },
MinerRow { slow: true, ..Default::default() },
MinerRow { paused: true, ..Default::default() },
MinerRow { is_mining: true, ..Default::default() },
];
let idx: Vec<usize> = (0..rows.len()).collect();
let k = compute_kpis(&rows, &idx);
assert_eq!(k.slow, 1, "only the genuinely-slow row");
assert_eq!(k.paused, 1, "only the genuinely-paused row");
assert_eq!(k.hashing, 1);
assert_eq!(k.not_hashing, 1, "the offline-but-flagged row folds here, not into slow");
assert_eq!(k.total, 4);
}
#[test]
fn flash_confirmed_requires_exact_word() {
assert!(flash_confirmed("FLASH"));
assert!(flash_confirmed(" FLASH "), "surrounding whitespace is trimmed");
assert!(!flash_confirmed("flash"), "case-sensitive");
assert!(!flash_confirmed("Flash"));
assert!(!flash_confirmed("FLASHING"), "not a prefix match");
assert!(!flash_confirmed("FLASH NOW"));
assert!(!flash_confirmed(""));
}
}
+509 -15
View File
@@ -1,10 +1,11 @@
//! Scan engine: drives vendored asic-rs over the configured subnets and
//! streams MinerRow snapshots to the UI thread via a std channel.
use crate::model::MinerRow;
use asic_rs::MinerFactory;
use crate::model::{MinerCaps, MinerRow};
use asic_rs::core::data::firmware::FirmwareImage;
use asic_rs::core::traits::miner::Miner;
use futures_util::StreamExt;
use measurements::Power;
use std::collections::HashSet;
use std::net::Ipv4Addr;
use std::path::PathBuf;
@@ -257,8 +258,13 @@ pub fn start_scan(lines: Vec<String>) -> ScanHandle {
let err_tx = tx.clone();
let res = std::thread::Builder::new().name("fake-scan".into()).spawn(move || {
let rows = crate::fixtures::bench_fleet();
let targets: HashSet<String> = rows.iter().map(|r| r.ip.clone()).collect();
let total = rows.len();
// A synthetic unreachable host, so the offline-recognition path
// (a probed address with no miner behind it) is exercised even
// when running fully offline against fixtures.
let offline_ip = "10.255.1.254".to_string();
let mut targets: HashSet<String> = rows.iter().map(|r| r.ip.clone()).collect();
targets.insert(offline_ip.clone());
let total = rows.len() + 1;
let _ = tx.send(ScanMsg::Started { total, targets });
for (i, row) in rows.into_iter().enumerate() {
if thread_cancel.load(Ordering::Relaxed) {
@@ -269,6 +275,13 @@ pub fn start_scan(lines: Vec<String>) -> ScanHandle {
}
let _ = tx.send(ScanMsg::Progress { done: i + 1, total, ip: String::new() });
}
if thread_cancel.load(Ordering::Relaxed) {
return;
}
if tx.send(ScanMsg::Row(MinerRow::offline(offline_ip))).is_err() {
return;
}
let _ = tx.send(ScanMsg::Progress { done: total, total, ip: String::new() });
let _ = tx.send(ScanMsg::Done("fixtures".into()));
});
if let Err(e) = res {
@@ -305,7 +318,7 @@ pub fn start_scan(lines: Vec<String>) -> ScanHandle {
}
};
rt.block_on(async move {
let mut factory = MinerFactory::new();
let mut factory = crate::credentials::configured_factory();
for (ip, prefix) in &cidrs {
factory = match factory.with_subnet(&format!("{ip}/{prefix}")) {
Ok(f) => f,
@@ -325,11 +338,15 @@ pub fn start_scan(lines: Vec<String>) -> ScanHandle {
return; // Stop / re-scan requested
}
done += 1;
if let Some(miner) = miner {
let row = to_row(&*miner).await;
if tx.send(ScanMsg::Row(row)).is_err() {
return; // UI gone
}
// Always report a row, even for an address that answered no
// miner protocol: `MinerRow::offline` keeps it visible (and
// distinct from a row the scan simply never reached).
let row = match miner {
Some(m) => to_row(&*m).await,
None => MinerRow::offline(ip.to_string()),
};
if tx.send(ScanMsg::Row(row)).is_err() {
return; // UI gone
}
if done % step == 0 || done == total {
let _ = tx.send(ScanMsg::Progress { done, total, ip: ip.to_string() });
@@ -362,11 +379,11 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.as_ref()
.map(|t| t.as_celsius())
.unwrap_or(0.0);
let fan_rpm = data
let fan_rpms: Vec<f64> = data
.fans
.iter()
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
.fold(0.0f64, f64::max);
.map(|f| f.rpm.as_ref().map(|r| r.as_rpm()).unwrap_or(0.0))
.collect();
let worker = data
.pools
.iter()
@@ -419,9 +436,24 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.fold(0.0f64, f64::max);
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();
let paused = crate::model::is_paused(&operating_state, is_mining);
// Probe what this miner supports being told to do (sync, no extra I/O).
let caps = MinerCaps {
fault_light: miner.supports_set_fault_light(),
restart: miner.supports_restart(),
pause: miner.supports_pause(),
resume: miner.supports_resume(),
power_limit: miner.supports_set_power_limit(),
tuning: miner.supports_set_tuning_percent(),
firmware_flash: miner.supports_upgrade_firmware(),
};
MinerRow {
ip: data.ip.to_string(),
selected: false,
// A miner that responded to the scan is reachable.
offline: false,
caps,
model,
mac: data.mac.map(|m| m.to_string()).unwrap_or_default(),
hostname: data.hostname.clone().unwrap_or_default(),
@@ -437,7 +469,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
chip_temp_c,
fluid_temp_c,
outlet_temp_c,
fan_rpm,
fan_rpms,
psu_fan_rpm,
fan_count: (!data.fans.is_empty()).then_some(data.fans.len() as u32),
expected_fans: data.expected_fans.map(|v| v as u32),
@@ -452,13 +484,352 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
session_best_share: data.session_best_share,
uptime_secs: data.uptime.map(|d| d.as_secs()).unwrap_or(0),
light_flashing: data.light_flashing,
operating_state: data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default(),
operating_state,
is_mining,
slow,
paused,
}
}
/// A one-shot configuration action applied to a set of miners from the
/// right-click menu.
#[derive(Debug, Clone)]
pub enum ConfigAction {
FaultLight(bool),
Restart,
Pause,
Resume,
PowerLimit(f64), // watts
TuningPercent(u8),
}
impl ConfigAction {
/// Short label for status text and summaries.
pub fn label(&self) -> String {
match self {
ConfigAction::FaultLight(true) => "fault light on".into(),
ConfigAction::FaultLight(false) => "fault light off".into(),
ConfigAction::Restart => "restart".into(),
ConfigAction::Pause => "pause".into(),
ConfigAction::Resume => "resume".into(),
ConfigAction::PowerLimit(w) => format!("power limit {w:.0} W"),
ConfigAction::TuningPercent(p) => format!("tuning {p}%"),
}
}
}
/// Progress/results from a running config action.
pub enum ActionMsg {
Started { total: usize },
Result { ip: String, ok: bool, detail: String },
Done { ok: usize, total: usize },
}
/// A running config action; `stop` cancels the remaining miners.
pub struct ActionHandle {
pub rx: Receiver<ActionMsg>,
cancel: Arc<AtomicBool>,
}
impl ActionHandle {
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result<bool, String> {
let result = match action {
ConfigAction::FaultLight(on) => miner.set_fault_light(*on).await,
ConfigAction::Restart => miner.restart().await,
ConfigAction::Pause => miner.pause(None).await,
ConfigAction::Resume => miner.resume(None).await,
ConfigAction::PowerLimit(w) => miner.set_power_limit(Power::from_watts(*w)).await,
ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await,
};
result.map_err(|e| e.to_string())
}
/// Apply `action` to each miner in `ips` on a background thread: re-discover the
/// miner (asic-rs `scan_miner`), run the setter, and report per-IP results. In
/// fake-scan mode it reports simulated successes so the flow works offline.
pub fn start_config_action(ips: Vec<String>, action: ConfigAction) -> ActionHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let total = ips.len();
let _ = tx.send(ActionMsg::Started { total });
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-action".into()).spawn(move || {
let mut ok = 0usize;
for ip in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() });
ok += 1;
}
let _ = tx.send(ActionMsg::Done { ok, total });
});
if res.is_err() {
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
}
return ActionHandle { rx, cancel };
}
let thread_cancel = cancel.clone();
let err_tx = tx.clone();
let res = std::thread::Builder::new().name("config-action".into()).spawn(move || {
// A single-threaded runtime: the loop applies to one miner at a time, so
// a worker-per-CPU pool would be wasted.
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
Ok(rt) => rt,
Err(_) => {
let _ = tx.send(ActionMsg::Done { ok: 0, total });
return;
}
};
rt.block_on(async move {
let factory = crate::credentials::configured_factory();
let mut ok = 0usize;
for ip_s in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let (success, detail) = match ip_s.parse::<std::net::IpAddr>() {
Err(_) => (false, "bad IP".to_string()),
Ok(ip) => match factory.scan_miner(ip).await {
Ok(Some(miner)) => match apply_action(&*miner, &action).await {
Ok(true) => (true, "ok".to_string()),
Ok(false) => (false, "refused".to_string()),
Err(e) => (false, format!("{e}")),
},
Ok(None) => (false, "no miner at IP".to_string()),
Err(e) => (false, format!("{e}")),
},
};
if success {
ok += 1;
}
if tx.send(ActionMsg::Result { ip: ip_s, ok: success, detail }).is_err() {
return; // UI gone
}
}
let _ = tx.send(ActionMsg::Done { ok, total });
});
});
if res.is_err() {
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
}
ActionHandle { rx, cancel }
}
/// Progress/results from a background refresh of a specific, already-known
/// set of miners (re-poll on a timer or after a right-click "Refresh" action,
/// as opposed to `start_scan`'s full subnet sweep).
pub enum RefreshMsg {
Started { total: usize },
/// A miner's telemetry was re-read successfully.
Row(MinerRow),
/// A miner could not be reached or re-identified.
Failed { ip: String, detail: String },
Done { ok: usize, total: usize },
}
/// A running refresh; `stop` cancels the remaining miners.
pub struct RefreshHandle {
pub rx: Receiver<RefreshMsg>,
cancel: Arc<AtomicBool>,
}
impl RefreshHandle {
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
/// Re-poll a specific list of already-known miner IPs on a background thread:
/// re-discover each one (asic-rs `scan_miner`) and report its fresh row. In
/// fake-scan mode it reports the matching bench-fleet fixture row per IP.
pub fn start_refresh(ips: Vec<String>) -> RefreshHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let total = ips.len();
let _ = tx.send(RefreshMsg::Started { total });
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-refresh".into()).spawn(move || {
let fleet = crate::fixtures::bench_fleet();
let mut ok = 0usize;
for ip in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
match fleet.iter().find(|r| r.ip == ip) {
Some(row) => {
if tx.send(RefreshMsg::Row(row.clone())).is_err() {
return; // UI gone
}
ok += 1;
}
None => {
if tx.send(RefreshMsg::Failed { ip, detail: "offline".into() }).is_err() {
return;
}
}
}
}
let _ = tx.send(RefreshMsg::Done { ok, total });
});
if res.is_err() {
let _ = err_tx.send(RefreshMsg::Done { ok: 0, total });
}
return RefreshHandle { rx, cancel };
}
let thread_cancel = cancel.clone();
let err_tx = tx.clone();
let res = std::thread::Builder::new().name("miner-refresh".into()).spawn(move || {
// A single-threaded runtime: the loop applies to one miner at a time, so
// a worker-per-CPU pool would be wasted.
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
Ok(rt) => rt,
Err(_) => {
let _ = tx.send(RefreshMsg::Done { ok: 0, total });
return;
}
};
rt.block_on(async move {
let factory = crate::credentials::configured_factory();
let mut ok = 0usize;
for ip_s in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let msg = match ip_s.parse::<std::net::IpAddr>() {
Err(_) => RefreshMsg::Failed { ip: ip_s, detail: "bad IP".to_string() },
Ok(ip) => match factory.scan_miner(ip).await {
Ok(Some(miner)) => {
ok += 1;
RefreshMsg::Row(to_row(&*miner).await)
}
Ok(None) => RefreshMsg::Failed { ip: ip_s, detail: "offline".to_string() },
Err(e) => RefreshMsg::Failed { ip: ip_s, detail: format!("{e}") },
},
};
if tx.send(msg).is_err() {
return; // UI gone
}
}
let _ = tx.send(RefreshMsg::Done { ok, total });
});
});
if res.is_err() {
let _ = err_tx.send(RefreshMsg::Done { ok: 0, total });
}
RefreshHandle { rx, cancel }
}
/// Prepare (if the backend supports it) then upload a firmware image to one
/// miner. Never interrupted once started: `start_firmware_flash_action` only
/// checks its cancel flag between miners, not while this is running.
async fn flash_one(miner: &dyn Miner, image: &FirmwareImage) -> Result<bool, String> {
let image = if miner.supports_prepare_firmware() {
miner.prepare_firmware(image.clone()).await.map_err(|e| e.to_string())?
} else {
image.clone()
};
miner.upgrade_firmware(image).await.map_err(|e| e.to_string())
}
/// Flash `image` to each miner in `ips` on a background thread: re-discover the
/// miner (asic-rs `scan_miner`), then prepare (if supported) and upload the
/// firmware, reporting per-IP results. Backends that don't implement firmware
/// upgrade report "unsupported" rather than attempting anything. The cancel
/// flag is only checked between miners: a flash in progress always runs to
/// completion instead of being interrupted mid-upload. In fake-scan mode it
/// reports simulated successes so the flow works offline.
pub fn start_firmware_flash_action(ips: Vec<String>, image: FirmwareImage) -> ActionHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let total = ips.len();
let _ = tx.send(ActionMsg::Started { total });
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-firmware-flash".into()).spawn(move || {
let mut ok = 0usize;
for ip in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() });
ok += 1;
}
let _ = tx.send(ActionMsg::Done { ok, total });
});
if res.is_err() {
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
}
return ActionHandle { rx, cancel };
}
let thread_cancel = cancel.clone();
let err_tx = tx.clone();
let res = std::thread::Builder::new().name("firmware-flash".into()).spawn(move || {
// A single-threaded runtime: flashes run one miner at a time by
// design (see the cancel-between-miners note above).
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
Ok(rt) => rt,
Err(_) => {
let _ = tx.send(ActionMsg::Done { ok: 0, total });
return;
}
};
rt.block_on(async move {
let factory = crate::credentials::configured_factory();
let mut ok = 0usize;
for ip_s in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let (success, detail) = match ip_s.parse::<std::net::IpAddr>() {
Err(_) => (false, "bad IP".to_string()),
Ok(ip) => match factory.scan_miner(ip).await {
Ok(Some(miner)) => {
if !miner.supports_upgrade_firmware() {
(false, "unsupported".to_string())
} else {
match flash_one(&*miner, &image).await {
Ok(true) => (true, "ok".to_string()),
Ok(false) => (false, "refused".to_string()),
Err(e) => (false, format!("{e}")),
}
}
}
Ok(None) => (false, "no miner at IP".to_string()),
Err(e) => (false, format!("{e}")),
},
};
if success {
ok += 1;
}
if tx.send(ActionMsg::Result { ip: ip_s, ok: success, detail }).is_err() {
return; // UI gone
}
}
let _ = tx.send(ActionMsg::Done { ok, total });
});
});
if res.is_err() {
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
}
ActionHandle { rx, cancel }
}
#[cfg(test)]
mod tests {
@@ -694,4 +1065,127 @@ mod tests {
println!("bench_targets_to_cidrs_large_range: {} addrs -> {sink} cidrs, {:?}/op", ips.len(), per);
assert!(per.as_millis() < 200, "targets_to_cidrs regressed: {per:?}/op");
}
/// Exercise the round-6 background actions through their fake-scan branch:
/// offline-row emission (start_scan), per-IP refresh (start_refresh),
/// firmware flash (start_firmware_flash_action), and that a cancelled run
/// still terminates. ALKANE_FAKE_SCAN is process-global, but no other test
/// calls these functions, so setting it here only affects this one
/// (sequential) test; all fake-mode assertions live in a single #[test] so
/// they never race each other over the env var.
#[test]
fn fake_mode_background_actions() {
use std::sync::mpsc::RecvTimeoutError;
use std::time::Duration;
let deadline = Duration::from_secs(5);
std::env::set_var(FAKE_SCAN_ENV, "1");
// start_scan: every probed IP produces a Row, including a synthetic
// unreachable host that must come back as an offline row.
{
let h = start_scan(vec!["10.255.1.0/30".into()]);
let mut rows = Vec::new();
let mut total = 0usize;
loop {
match h.rx.recv_timeout(deadline) {
Ok(ScanMsg::Started { total: t, .. }) => total = t,
Ok(ScanMsg::Row(r)) => rows.push(r),
Ok(ScanMsg::Done(_)) => break,
Ok(_) => {}
Err(RecvTimeoutError::Timeout) => panic!("fake start_scan hung"),
Err(RecvTimeoutError::Disconnected) => break,
}
}
assert_eq!(rows.len(), total, "one Row per probed target, incl. the offline host");
let offline = rows
.iter()
.find(|r| r.ip == "10.255.1.254")
.expect("synthetic offline row must be emitted");
assert!(offline.offline);
assert_eq!(offline.status(), "offline");
}
// start_refresh: a known fixture IP re-reads as a Row, an unknown IP is
// reported Failed{offline}, and the run ends with Done{ok:1,total:2}.
{
let known = "10.255.1.112".to_string(); // an S17 in bench_fleet
let unknown = "10.0.0.250".to_string();
let h = start_refresh(vec![known.clone(), unknown.clone()]);
let (mut rows, mut failed, mut done) = (0usize, 0usize, None);
loop {
match h.rx.recv_timeout(deadline) {
Ok(RefreshMsg::Started { .. }) => {}
Ok(RefreshMsg::Row(r)) => {
assert_eq!(r.ip, known);
rows += 1;
}
Ok(RefreshMsg::Failed { ip, detail }) => {
assert_eq!(ip, unknown);
assert_eq!(detail, "offline");
failed += 1;
}
Ok(RefreshMsg::Done { ok, total }) => {
done = Some((ok, total));
break;
}
Err(RecvTimeoutError::Timeout) => panic!("fake start_refresh hung"),
Err(RecvTimeoutError::Disconnected) => break,
}
}
assert_eq!(rows, 1);
assert_eq!(failed, 1);
assert_eq!(done, Some((1, 2)));
}
// start_firmware_flash_action: fake mode reports one simulated success
// per IP and a matching Done summary.
{
let image = FirmwareImage::new("fw.bin".to_string(), vec![0u8; 8]);
let h = start_firmware_flash_action(
vec!["10.255.1.166".into(), "10.255.1.149".into()],
image,
);
let (mut results, mut done) = (0usize, None);
loop {
match h.rx.recv_timeout(deadline) {
Ok(ActionMsg::Started { .. }) => {}
Ok(ActionMsg::Result { ok, detail, .. }) => {
assert!(ok);
assert_eq!(detail, "simulated");
results += 1;
}
Ok(ActionMsg::Done { ok, total }) => {
done = Some((ok, total));
break;
}
Err(RecvTimeoutError::Timeout) => panic!("fake flash hung"),
Err(RecvTimeoutError::Disconnected) => break,
}
}
assert_eq!(results, 2);
assert_eq!(done, Some((2, 2)));
}
// Cancellation contract: stopping a run still delivers a terminal Done
// rather than hanging (the fake branches now honour the cancel flag).
{
let big: Vec<String> = (0..200).map(|i| format!("10.9.0.{}", i % 256)).collect();
let h = start_refresh(big);
h.stop();
let mut saw_done = false;
loop {
match h.rx.recv_timeout(deadline) {
Ok(RefreshMsg::Done { .. }) => {
saw_done = true;
break;
}
Ok(_) => {}
Err(_) => break,
}
}
assert!(saw_done, "a cancelled fake refresh must still emit Done, not hang");
}
std::env::remove_var(FAKE_SCAN_ENV);
}
}
+1429 -123
View File
File diff suppressed because it is too large Load Diff
+128 -1
View File
@@ -10,7 +10,7 @@
+pub use widgets::*;
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -0,0 +1,561 @@
@@ -0,0 +1,688 @@
+// 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).
@@ -28,6 +28,7 @@
+ pub fn wxbr_main_frame() -> *mut c_void;
+ pub fn wxbr_panel(parent: *mut c_void) -> *mut c_void;
+ pub fn wxbr_box_sizer(vertical: c_int) -> *mut c_void;
+ pub fn wxbr_wrap_sizer(vertical: c_int) -> *mut c_void;
+ pub fn wxbr_sizer_add(sizer: *mut c_void, win: *mut c_void, proportion: c_int, flags: c_int, border: c_int);
+ pub fn wxbr_sizer_add_sizer(sizer: *mut c_void, subsizer: *mut c_void, proportion: c_int, flags: c_int, border: c_int);
+ pub fn wxbr_sizer_add_spacer(sizer: *mut c_void, px: c_int);
@@ -43,6 +44,7 @@
+ pub fn wxbr_set_bold(win: *mut c_void);
+ pub fn wxbr_set_font_size(win: *mut c_void, pts: c_int);
+ pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
+ pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
+ pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
+ pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
@@ -59,8 +61,10 @@
+ pub fn wxbr_dialog(parent: *mut c_void, title: *const c_char) -> *mut c_void;
+ pub fn wxbr_dialog_show_modal(win: *mut c_void) -> c_int;
+ pub fn wxbr_dialog_close(win: *mut c_void, code: c_int);
+ pub fn wxbr_file_dialog(parent: *mut c_void, title: *const c_char, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_dvlc(parent: *mut c_void) -> *mut c_void;
+ pub fn wxbr_dvlc_append_text_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int);
+ pub fn wxbr_dvlc_append_colored_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int) -> *mut c_void;
+ pub fn wxbr_dvlc_append_toggle_col(win: *mut c_void, width: c_int);
+ pub fn wxbr_dvlc_append_row(win: *mut c_void, nvals: c_int, vals: *const *const c_char);
+ pub fn wxbr_dvlc_delete_row(win: *mut c_void, row: usize);
@@ -77,6 +81,7 @@
+ pub fn wxbr_dvlc_get_selections(win: *mut c_void, buf: *mut c_int, cap: c_int) -> c_int;
+ pub fn wxbr_dvlc_select_rows(win: *mut c_void, rows: *const c_int, n: c_int);
+ pub fn wxbr_dvlc_set_alt_row_color(win: *mut c_void, r: c_int, g: c_int, b: c_int);
+ pub fn wxbr_dvlc_set_row_color(win: *mut c_void, row: usize, r: c_int, g: c_int, b: c_int);
+ pub fn wxbr_apply_zebra_css(r: c_int, g: c_int, b: c_int);
+ pub fn wxbr_rearrange_list(parent: *mut c_void, n: c_int, order: *const c_int, items: *const *const c_char) -> *mut c_void;
+ pub fn wxbr_rearrange_get_order(win: *mut c_void, buf: *mut c_int, cap: c_int) -> c_int;
@@ -96,7 +101,16 @@
+ pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
+ pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
+ pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
+ pub fn wxbr_choice(parent: *mut c_void, id: c_int) -> *mut c_void;
+ pub fn wxbr_choice_append(win: *mut c_void, label: *const c_char);
+ pub fn wxbr_choice_clear(win: *mut c_void);
+ pub fn wxbr_choice_get_selection(win: *mut c_void) -> c_int;
+ pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
+ pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
+ pub fn wxbr_bind_sys_colour(win: *mut c_void);
+ 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);
+ }
+}
+
@@ -129,6 +143,9 @@
+ DvlcSelectionChanged,
+ DvlcContextMenu,
+ MenuItem,
+ ChoiceChanged,
+ SysColour,
+ Deferred,
+}
+
+impl WxEventKind {
@@ -144,6 +161,9 @@
+ 9 => WxEventKind::DvlcSelectionChanged,
+ 10 => WxEventKind::DvlcContextMenu,
+ 11 => WxEventKind::MenuItem,
+ 12 => WxEventKind::ChoiceChanged,
+ 13 => WxEventKind::SysColour,
+ 14 => WxEventKind::Deferred,
+ _ => return None,
+ })
+ }
@@ -154,6 +174,13 @@
+ unsafe { notsafe::wxbr_apply_zebra_css(r as c_int, g as c_int, b as c_int) }
+}
+
+/// Schedule a deferred action: a `Deferred` event carrying `id` is delivered
+/// from the event loop after the current event finishes. Use this to rebuild or
+/// destroy a control from outside its own event handler.
+pub fn call_after(id: i32) {
+ unsafe { notsafe::wxbr_call_after(id 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();
@@ -229,6 +256,14 @@
+ Widget(unsafe { notsafe::wxbr_box_sizer(vertical as c_int) })
+ }
+
+ /// A box sizer that wraps overflowing items onto additional lines instead
+ /// of shrinking them. wxWrapSizer is a wxBoxSizer subclass, so the result
+ /// accepts the same add/add_sizer/add_spacer/add_stretch/set_sizer_on
+ /// calls as `box_sizer`'s.
+ pub fn wrap_sizer(vertical: bool) -> Widget {
+ Widget(unsafe { notsafe::wxbr_wrap_sizer(vertical as c_int) })
+ }
+
+ pub fn add(&self, win: Widget, proportion: i32, flags: i32, border: i32) {
+ unsafe { notsafe::wxbr_sizer_add(self.0, win.0, proportion, flags, border) }
+ }
@@ -305,6 +340,15 @@
+ Widget(unsafe { notsafe::wxbr_button(parent.0, c.as_ptr(), id) })
+ }
+
+ /// Make this window clickable: a left mouse down on it emits the same
+ /// `ButtonClicked` event a real button would, carrying `id`. Bind each
+ /// child that should also count as part of the click target (e.g. the
+ /// static text labels on a KPI card), since a child window swallows its
+ /// own mouse events rather than letting them propagate to the parent.
+ pub fn bind_click(&self, id: i32) {
+ unsafe { notsafe::wxbr_bind_click(self.0, id) }
+ }
+
+ pub fn text_ctrl(parent: Widget, multiline: bool) -> Widget {
+ Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
+ }
@@ -384,6 +428,21 @@
+ unsafe { notsafe::wxbr_dialog_close(self.0, code) }
+ }
+
+ /// Show a native "open file, must exist" dialog. Returns the chosen path,
+ /// or `None` if the dialog was cancelled.
+ pub fn file_dialog(parent: Widget, title: &str) -> Option<String> {
+ let c = CString::new(title).unwrap_or_default();
+ let mut buf = vec![0i8; 4096];
+ let n = unsafe {
+ notsafe::wxbr_file_dialog(parent.0, c.as_ptr(), buf.as_mut_ptr(), buf.len() as c_int)
+ };
+ if n <= 0 {
+ return None;
+ }
+ let bytes: Vec<u8> = buf[..(n - 1) as usize].iter().map(|&b| b as u8).collect();
+ Some(String::from_utf8_lossy(&bytes).into_owned())
+ }
+
+ // ---- data view list ctrl ----
+
+ pub fn dvlc(parent: Widget) -> Widget {
@@ -395,6 +454,14 @@
+ unsafe { notsafe::wxbr_dvlc_append_text_col(self.0, c.as_ptr(), width, reorderable as c_int) }
+ }
+
+ /// Like `dvlc_append_text_col`, but the column renders cell values through
+ /// the SegmentRenderer, so a value built with `model::encode_segments` is
+ /// drawn as coloured text runs (a plain string still renders normally).
+ pub fn dvlc_append_colored_col(&self, title: &str, width: i32, reorderable: bool) {
+ let c = CString::new(title).unwrap_or_default();
+ unsafe { notsafe::wxbr_dvlc_append_colored_col(self.0, c.as_ptr(), width, reorderable as c_int) };
+ }
+
+ pub fn dvlc_append_toggle_col(&self, width: i32) {
+ unsafe { notsafe::wxbr_dvlc_append_toggle_col(self.0, width) }
+ }
@@ -472,6 +539,15 @@
+ unsafe { notsafe::wxbr_dvlc_set_alt_row_color(self.0, r as c_int, g as c_int, b as c_int) }
+ }
+
+ /// Set a row's text colour (e.g. by miner status). Pass `None` to clear it.
+ pub fn dvlc_set_row_color(&self, row: usize, color: Option<(u8, u8, u8)>) {
+ let (r, g, b) = match color {
+ Some((r, g, b)) => (r as c_int, g as c_int, b as c_int),
+ None => (-1, -1, -1),
+ };
+ unsafe { notsafe::wxbr_dvlc_set_row_color(self.0, row, r, g, b) }
+ }
+
+ // ---- rearrangeable check-list ----
+
+ /// Create a rearrangeable checklist. `order` uses wx encoding: a value `v`
@@ -566,9 +642,60 @@
+ unsafe { notsafe::wxbr_set_fg(self.0, r as c_int, g as c_int, b as c_int) }
+ }
+
+ // ---- choice (dropdown) ----
+
+ /// Create a dropdown; selection changes emit `ChoiceChanged` with this id.
+ pub fn choice(parent: Widget, id: i32) -> Widget {
+ Widget(unsafe { notsafe::wxbr_choice(parent.0, id) })
+ }
+
+ pub fn choice_append(&self, label: &str) {
+ let c = CString::new(label).unwrap_or_default();
+ unsafe { notsafe::wxbr_choice_append(self.0, c.as_ptr()) }
+ }
+
+ pub fn choice_clear(&self) {
+ unsafe { notsafe::wxbr_choice_clear(self.0) }
+ }
+
+ pub fn choice_get_selection(&self) -> i32 {
+ unsafe { notsafe::wxbr_choice_get_selection(self.0) }
+ }
+
+ pub fn choice_set_selection(&self, i: i32) {
+ unsafe { notsafe::wxbr_choice_set_selection(self.0, i) }
+ }
+
+ // ---- media (icon) button ----
+
+ /// A coloured icon button: `kind` 0=play, 1=pause, 2=stop. Clicks emit
+ /// `ButtonClicked` with `id`, like a normal button.
+ pub fn media_button(parent: Widget, id: i32, kind: i32, color: (u8, u8, u8)) -> Widget {
+ Widget(unsafe {
+ notsafe::wxbr_media_button(
+ parent.0,
+ id,
+ kind,
+ color.0 as c_int,
+ color.1 as c_int,
+ color.2 as c_int,
+ )
+ })
+ }
+
+ /// Listen for OS light/dark theme changes on this window (emits `SysColour`).
+ pub fn bind_sys_colour(&self) {
+ unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
+ }
+
+ /// Deferred destruction (safe from event handlers); used to rebuild
+ /// the table when its column set changes.
+ pub fn destroy(&self) {
+ unsafe { notsafe::wxbr_destroy(self.0) }
+ }
+
+ /// Destroy this window's children (to rebuild dynamic panel contents).
+ pub fn destroy_children(&self) {
+ unsafe { notsafe::wxbr_destroy_children(self.0) }
+ }
+}
+359 -65
View File
@@ -1,6 +1,6 @@
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -0,0 +1,598 @@
@@ -0,0 +1,892 @@
+// 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).
@@ -23,10 +23,18 @@
+#include <wx/app.h>
+#include <wx/rearrangectrl.h>
+#include <wx/menu.h>
+#ifdef __WXGTK__
+#include <gtk/gtk.h>
+#endif
+#include <wx/choice.h>
+#include <wx/bmpbuttn.h>
+#include <wx/bitmap.h>
+#include <wx/image.h>
+#include <wx/dcmemory.h>
+#include <wx/dcgraph.h>
+#include <wx/graphics.h>
+#include <wx/wrapsizer.h>
+#include <wx/filedlg.h>
+#include <cstring>
+#include <cstdio>
+#include <vector>
+
+typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
+static WxWidgetEventFn g_widget_event = nullptr;
@@ -43,6 +51,123 @@
+ WxEV_DVLC_SELECTION_CHANGED = 9,
+ WxEV_DVLC_CONTEXT_MENU = 10,
+ WxEV_MENU_ITEM = 11,
+ WxEV_CHOICE_CHANGED = 12,
+ WxEV_SYS_COLOUR = 13,
+ WxEV_DEFERRED = 14,
+};
+
+// A list store that carries an optional per-row foreground colour, surfaced to
+// the native control via GetAttrByRow. This is how the miner table paints each
+// row's text by status and separates rows on GTK (where SetAlternateRowColour
+// and :nth-child CSS are unreliable and fight the selection highlight).
+class AttrListStore : public wxDataViewListStore {
+ public:
+ std::vector<wxColour> row_fg;
+ bool GetAttrByRow(unsigned int row, unsigned int col,
+ wxDataViewItemAttr& attr) const override {
+ (void)col;
+ if (row < row_fg.size() && row_fg[row].IsOk()) {
+ attr.SetColour(row_fg[row]);
+ return true;
+ }
+ return false;
+ }
+};
+
+// A wxDataViewCustomRenderer that draws a cell value made of coloured text
+// runs. The encoding matches alkane_gui::model::encode_segments: segments are
+// joined by U+001F (ASCII unit separator); each segment is an optional
+// 6-hex-digit RRGGBB colour followed by U+001E (ASCII record separator) and
+// then its plain text. A value containing no U+001E at all -- e.g. any
+// ordinary string -- is drawn as a single run in the default text colour, so
+// this renderer is safe to use in place of a plain text column.
+namespace {
+
+struct ColorSegment {
+ bool has_colour = false;
+ wxColour colour;
+ wxString text;
+};
+
+std::vector<ColorSegment> ParseColorSegments(const wxString& value) {
+ std::vector<ColorSegment> segs;
+ if (value.Find(wxUniChar(0x1e)) == wxNOT_FOUND) {
+ ColorSegment s;
+ s.text = value;
+ segs.push_back(s);
+ return segs;
+ }
+ wxString rest = value;
+ for (;;) {
+ int sep = rest.Find(wxUniChar(0x1f));
+ wxString piece = (sep == wxNOT_FOUND) ? rest : rest.Left(sep);
+ ColorSegment s;
+ int csep = piece.Find(wxUniChar(0x1e));
+ if (csep == wxNOT_FOUND) {
+ s.text = piece;
+ } else {
+ wxString hex = piece.Left(csep);
+ s.text = piece.Mid(csep + 1);
+ unsigned long v;
+ if (hex.length() == 6 && hex.ToULong(&v, 16)) {
+ s.colour = wxColour((unsigned char)((v >> 16) & 0xff),
+ (unsigned char)((v >> 8) & 0xff),
+ (unsigned char)(v & 0xff));
+ s.has_colour = true;
+ }
+ }
+ segs.push_back(s);
+ if (sep == wxNOT_FOUND) break;
+ rest = rest.Mid(sep + 1);
+ }
+ return segs;
+}
+
+} // namespace
+
+class SegmentRenderer : public wxDataViewCustomRenderer {
+ public:
+ SegmentRenderer()
+ : wxDataViewCustomRenderer(wxASCII_STR("string"), wxDATAVIEW_CELL_INERT) {}
+
+ bool SetValue(const wxVariant& value) override {
+ m_value = value.GetString();
+ return true;
+ }
+
+ bool GetValue(wxVariant& value) const override {
+ value = m_value;
+ return true;
+ }
+
+ bool Render(wxRect cell, wxDC* dc, int state) override {
+ bool selected = (state & wxDATAVIEW_CELL_SELECTED) != 0;
+ wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
+ wxColour plain = GetAttr().HasColour()
+ ? GetAttr().GetColour()
+ : wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
+ wxCoord x = cell.x;
+ for (const ColorSegment& seg : ParseColorSegments(m_value)) {
+ if (seg.text.IsEmpty()) continue;
+ dc->SetTextForeground(selected ? highlight : (seg.has_colour ? seg.colour : plain));
+ wxSize extent = dc->GetTextExtent(seg.text);
+ wxCoord y = cell.y + (cell.height - extent.GetHeight()) / 2;
+ dc->DrawText(seg.text, x, y);
+ x += extent.GetWidth();
+ }
+ return true;
+ }
+
+ wxSize GetSize() const override {
+ wxString plain;
+ for (const ColorSegment& seg : ParseColorSegments(m_value)) plain += seg.text;
+ wxSize sz = GetTextExtent(plain);
+ if (sz.GetWidth() < 1) sz.SetWidth(1);
+ return sz;
+ }
+
+ private:
+ wxString m_value;
+};
+
+extern "C" {
@@ -61,6 +186,14 @@
+ return (void*)new wxBoxSizer(vertical ? wxVERTICAL : wxHORIZONTAL);
+}
+
+// A box sizer that wraps its items onto additional lines instead of shrinking
+// them when the available space runs out. wxWrapSizer is a wxBoxSizer
+// subclass, so it accepts the same add/add_sizer/add_spacer/add_stretch and
+// set_sizer_on calls as wxbr_box_sizer's result.
+void* wxbr_wrap_sizer(int vertical) {
+ return (void*)new wxWrapSizer(vertical ? wxVERTICAL : wxHORIZONTAL);
+}
+
+// flag bits (must match Rust sizer_flags):
+// 1 = EXPAND, 2 = ALIGN_CENTRE_VERTICAL, 4 = wxALL, 8 = wxTOP,
+// 16 = wxBOTTOM, 32 = wxLEFT, 64 = wxRIGHT
@@ -169,6 +302,17 @@
+ return (void*)b;
+}
+
+// Make an arbitrary window (e.g. a KPI card panel) clickable: a left mouse
+// down on it emits the same WxEV_BUTTON_CLICKED event a real button would,
+// carrying `id`. Bind this on the panel itself; a child wxStaticText label
+// swallows its own mouse events, so the caller binds each child that should
+// also act as part of the click target rather than relying on propagation.
+void wxbr_bind_click(void* win, int id) {
+ ((wxWindow*)win)->Bind(wxEVT_LEFT_DOWN, [id](wxMouseEvent&) {
+ if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
+ });
+}
+
+// ---- text ctrl ------------------------------------------------------------
+
+void* wxbr_text_ctrl(void* parent, int multiline) {
@@ -267,65 +411,111 @@
+ ((wxDialog*)win)->EndModal(code);
+}
+
+// ---- file dialog -------------------------------------------------------------
+
+// Show a native "open file, must exist" dialog. On OK, copies the chosen
+// path (UTF-8) into buf (capped at cap) and returns its length + 1, like the
+// other buffer-filling bridge functions; on Cancel returns 0 and leaves buf
+// untouched.
+int wxbr_file_dialog(void* parent, const char* title, char* buf, int cap) {
+ wxFileDialog dlg((wxWindow*)parent, wxString::FromUTF8(title), wxEmptyString,
+ wxEmptyString, wxFileSelectorDefaultWildcardStr,
+ wxFD_OPEN | wxFD_FILE_MUST_EXIST);
+ if (dlg.ShowModal() != wxID_OK) return 0;
+ wxCharBuffer b = dlg.GetPath().ToUTF8();
+ int n = (int)strlen(b.data());
+ if (n >= cap) n = cap - 1;
+ memcpy(buf, b.data(), n);
+ buf[n] = 0;
+ return n + 1;
+}
+
+// ---- data view list ctrl ------------------------------------------------------
+
+static AttrListStore* dvlc_store(void* win) {
+ return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
+}
+
+void* wxbr_dvlc(void* parent) {
+ // Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
+ // checkbox column.
+ wxDataViewListCtrl* lc =
+ new wxDataViewListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
+ wxSize(-1, -1), wxDV_ROW_LINES | wxDV_MULTIPLE);
+ lc->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
+ // checkbox column. A custom AttrListStore backs it so rows can be coloured by
+ // status while the native selection highlight still shows through.
+ wxDataViewCtrl* dv =
+ new wxDataViewCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
+ wxSize(-1, -1), wxDV_ROW_LINES | wxDV_MULTIPLE);
+ AttrListStore* store = new AttrListStore();
+ dv->AssociateModel(store);
+ store->DecRef(); // the control owns a reference now
+ dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
+ if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
+ });
+ lc->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [](wxDataViewEvent&) {
+ dv->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [](wxDataViewEvent&) {
+ if (g_widget_event) g_widget_event(WxEV_DVLC_CONTEXT_MENU, 0, 0);
+ });
+ lc->Bind(wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [](wxDataViewEvent& e) {
+ dv->Bind(wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [](wxDataViewEvent& e) {
+ if (g_widget_event) {
+ wxDataViewListCtrl* lc =
+ dynamic_cast<wxDataViewListCtrl*>((wxWindow*)e.GetEventObject());
+ if (!lc) return;
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
+ if (!dv) return;
+ wxDataViewItem item = e.GetItem();
+ if (!item.IsOk()) return;
+ int row = lc->GetStore()->GetRow(item);
+ int row = ((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
+ g_widget_event(WxEV_DVLC_VALUE_CHANGED, row, (long)e.GetColumn());
+ }
+ });
+ lc->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, [](wxDataViewEvent& e) {
+ dv->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, [](wxDataViewEvent& e) {
+ if (g_widget_event) g_widget_event(WxEV_DVLC_HEADER_CLICK, (long)e.GetColumn(), 0);
+ });
+ lc->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);
+ });
+ // Row activation (double-click / Enter): report the row + column so the app
+ // can, e.g., open the miner's IP in a browser.
+ lc->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
+ dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
+ if (g_widget_event) {
+ wxDataViewListCtrl* lc =
+ dynamic_cast<wxDataViewListCtrl*>((wxWindow*)e.GetEventObject());
+ if (!lc) return;
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
+ if (!dv) return;
+ wxDataViewItem item = e.GetItem();
+ if (!item.IsOk()) return;
+ int row = lc->GetStore()->GetRow(item);
+ int row = ((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
+ g_widget_event(WxEV_DVLC_ACTIVATED, row, (long)e.GetColumn());
+ }
+ });
+ return (void*)lc;
+ return (void*)dv;
+}
+
+void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ int flags = wxDATAVIEW_COL_RESIZABLE;
+ if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
+ ((wxDataViewListCtrl*)win)
+ ->AppendTextColumn(wxString::FromUTF8(title), wxDATAVIEW_CELL_INERT,
+ width, wxALIGN_NOT, flags);
+ unsigned col = dv->GetColumnCount(); // next model column index
+ dvlc_store(win)->AppendColumn("string");
+ dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
+ width, wxALIGN_NOT, flags);
+}
+
+// Same bookkeeping as wxbr_dvlc_append_text_col, but the column is drawn by a
+// SegmentRenderer so its cell values can carry the '\x1f'/'\x1e' colour-run
+// encoding produced by alkane_gui::model::encode_segments. An ordinary string
+// with no encoding in it still renders fine (single default-coloured run).
+void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ int flags = wxDATAVIEW_COL_RESIZABLE;
+ if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
+ unsigned col = dv->GetColumnCount(); // next model column index
+ dvlc_store(win)->AppendColumn("string");
+ SegmentRenderer* renderer = new SegmentRenderer();
+ wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
+ width, wxALIGN_NOT, flags);
+ dv->AppendColumn(c);
+ return (void*)c;
+}
+
+void wxbr_dvlc_append_toggle_col(void* win, int width) {
+ ((wxDataViewListCtrl*)win)
+ ->AppendToggleColumn(wxT(""), wxDATAVIEW_CELL_ACTIVATABLE, width,
+ wxALIGN_CENTRE, 0);
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ unsigned col = dv->GetColumnCount();
+ dvlc_store(win)->AppendColumn("bool");
+ dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
+ wxALIGN_CENTRE, 0);
+}
+
+void wxbr_dvlc_append_row(void* win, int nvals, const char** vals) {
@@ -334,28 +524,45 @@
+ for (int i = 0; i < nvals; i++) {
+ values.push_back(wxVariant(vals[i] ? wxString::FromUTF8(vals[i]) : wxString()));
+ }
+ ((wxDataViewListCtrl*)win)->AppendItem(values);
+ AttrListStore* store = dvlc_store(win);
+ store->AppendItem(values);
+ store->row_fg.push_back(wxColour()); // no per-row colour until set
+}
+
+void wxbr_dvlc_delete_row(void* win, unsigned row) {
+ ((wxDataViewListCtrl*)win)->DeleteItem(row);
+ AttrListStore* store = dvlc_store(win);
+ store->DeleteItem(row);
+ if (row < store->row_fg.size()) store->row_fg.erase(store->row_fg.begin() + row);
+}
+
+void wxbr_dvlc_clear(void* win) { ((wxDataViewListCtrl*)win)->DeleteAllItems(); }
+void wxbr_dvlc_clear(void* win) {
+ AttrListStore* store = dvlc_store(win);
+ store->DeleteAllItems();
+ store->row_fg.clear();
+}
+
+// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
+void wxbr_dvlc_set_row_color(void* win, unsigned row, int r, int g, int b) {
+ AttrListStore* store = dvlc_store(win);
+ if (row >= store->row_fg.size()) return;
+ store->row_fg[row] = (r < 0) ? wxColour() : wxColour(r, g, b);
+ store->RowChanged(row);
+}
+
+int wxbr_dvlc_row_count(void* win) {
+ return (int)((wxDataViewListCtrl*)win)->GetStore()->GetItemCount();
+ return (int)dvlc_store(win)->GetItemCount();
+}
+
+void wxbr_dvlc_set_cell(void* win, unsigned row, unsigned col, const char* value) {
+ ((wxDataViewListCtrl*)win)
+ ->SetValue(wxVariant(wxString::FromUTF8(value)), row, col);
+ AttrListStore* store = dvlc_store(win);
+ store->SetValueByRow(wxVariant(wxString::FromUTF8(value)), row, col);
+ store->RowValueChanged(row, col);
+}
+
+int wxbr_dvlc_get_cell(void* win, unsigned row, unsigned col, char* buf, int cap) {
+ wxDataViewListCtrl* lc = (wxDataViewListCtrl*)win;
+ wxDataViewListStore* store = lc->GetStore();
+ if (row >= store->GetItemCount() || col >= lc->GetColumnCount())
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ AttrListStore* store = dvlc_store(win);
+ if (row >= store->GetItemCount() || (int)col >= (int)dv->GetColumnCount())
+ return 0;
+ wxVariant v;
+ store->GetValueByRow(v, row, col);
@@ -369,7 +576,7 @@
+}
+
+int wxbr_dvlc_col_count(void* win) {
+ return (int)((wxDataViewListCtrl*)win)->GetColumnCount();
+ return (int)((wxDataViewCtrl*)win)->GetColumnCount();
+}
+
+// Update a column's header text in place (creation index) without recreating
@@ -409,58 +616,51 @@
+}
+
+long wxbr_dvlc_selected_row(void* win) {
+ return (long)((wxDataViewListCtrl*)win)->GetSelectedRow();
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewItem it = dv->GetSelection();
+ if (!it.IsOk()) return -1;
+ return (long)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(it);
+}
+
+// Fill `buf` with the selected row indices (multi-select); returns the count.
+int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
+ wxDataViewListCtrl* lc = (wxDataViewListCtrl*)win;
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ wxDataViewItemArray items;
+ int n = (int)lc->GetSelections(items);
+ int n = (int)dv->GetSelections(items);
+ int out = 0;
+ for (int i = 0; i < n && out < cap; i++) {
+ int row = lc->GetStore()->GetRow(items[i]);
+ int row = m->GetRow(items[i]);
+ if (row >= 0) buf[out++] = row;
+ }
+ return out;
+}
+
+void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
+ wxDataViewListCtrl* lc = (wxDataViewListCtrl*)win;
+ lc->UnselectAll();
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ dv->UnselectAll();
+ for (int i = 0; i < n; i++) {
+ if (rows[i] >= 0) lc->SelectRow((unsigned)rows[i]);
+ if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
+ }
+}
+
+// Retained for ABI; per-row colour is handled by the store (GetAttrByRow) and
+// the native selection highlight, so these row-background hacks are no-ops now
+// (they fought the selection highlight on GTK 3.3).
+void wxbr_dvlc_set_alt_row_color(void* win, int r, int g, int b) {
+ // No-op on GTK (native dataview lacks it); see wxbr_apply_zebra_css.
+ ((wxDataViewListCtrl*)win)->SetAlternateRowColour(wxColour(r, g, b));
+ (void)win; (void)r; (void)g; (void)b;
+}
+
+// GTK's native dataview does not implement SetAlternateRowColour, so apply
+// zebra striping app-wide via a CSS provider (GTK 3.20+ supports :nth-child on
+// treeview rows). No-op off GTK.
+void wxbr_apply_zebra_css(int r, int g, int b) {
+#ifdef __WXGTK__
+ GtkCssProvider* p = gtk_css_provider_new();
+ char css[192];
+ std::snprintf(css, sizeof(css),
+ "treeview.view:nth-child(even){background-color:rgb(%d,%d,%d);}",
+ r, g, b);
+ gtk_css_provider_load_from_data(p, css, -1, NULL);
+ gtk_style_context_add_provider_for_screen(
+ gdk_screen_get_default(), GTK_STYLE_PROVIDER(p),
+ GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
+ g_object_unref(p);
+#else
+ (void)r; (void)g; (void)b;
+#endif
+}
+
+void wxbr_dvlc_select_row(void* win, long row) {
+ if (row < 0) return;
+ ((wxDataViewListCtrl*)win)->SelectRow((unsigned)row);
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ dv->Select(m->GetItem((unsigned)row));
+}
+
+// ---- timer -----------------------------------------------------------------
@@ -594,8 +794,102 @@
+ delete m;
+}
+
+// ---- choice (dropdown) ------------------------------------------------------
+
+void* wxbr_choice(void* parent, int id) {
+ wxChoice* c = new wxChoice((wxWindow*)parent, id);
+ c->Bind(wxEVT_CHOICE, [id](wxCommandEvent& e) {
+ if (g_widget_event)
+ g_widget_event(WxEV_CHOICE_CHANGED, id, (long)e.GetSelection());
+ });
+ return (void*)c;
+}
+
+void wxbr_choice_append(void* win, const char* label) {
+ ((wxChoice*)win)->Append(wxString::FromUTF8(label));
+}
+
+void wxbr_choice_clear(void* win) { ((wxChoice*)win)->Clear(); }
+
+int wxbr_choice_get_selection(void* win) {
+ return ((wxChoice*)win)->GetSelection();
+}
+
+void wxbr_choice_set_selection(void* win, int i) {
+ ((wxChoice*)win)->SetSelection(i);
+}
+
+// ---- media (icon) button: play / pause / stop -------------------------------
+
+// kind: 0=play (triangle), 1=pause (two bars), 2=stop (square). Drawn in the
+// given colour on a transparent bitmap so it reads as a coloured glyph on the
+// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
+void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
+ const int sz = 20;
+ wxImage img(sz, sz);
+ img.InitAlpha();
+ unsigned char* a = img.GetAlpha();
+ if (a) memset(a, 0, (size_t)sz * sz); // fully transparent
+ wxBitmap bmp(img);
+ {
+ wxMemoryDC mdc(bmp);
+ wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
+ if (gc) {
+ gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
+ wxColour col(r, g, b);
+ gc->SetBrush(wxBrush(col));
+ gc->SetPen(wxPen(col, 1.0));
+ if (kind == 0) {
+ wxGraphicsPath p = gc->CreatePath();
+ p.MoveToPoint(5, 4);
+ p.AddLineToPoint(16, 10);
+ p.AddLineToPoint(5, 16);
+ p.CloseSubpath();
+ gc->FillPath(p);
+ } else if (kind == 1) {
+ gc->DrawRectangle(5, 4, 3.5, 12);
+ gc->DrawRectangle(11.5, 4, 3.5, 12);
+ } else {
+ gc->DrawRectangle(5, 5, 10, 10);
+ }
+ delete gc;
+ }
+ }
+ wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bmp);
+ btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
+ if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
+ });
+ return (void*)btn;
+}
+
+// ---- live theme changes -----------------------------------------------------
+
+// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
+// repaint custom-coloured widgets (KPI cards, table rows).
+void wxbr_bind_sys_colour(void* win) {
+ ((wxWindow*)win)->Bind(wxEVT_SYS_COLOUR_CHANGED, [](wxSysColourChangedEvent& e) {
+ e.Skip();
+ if (g_widget_event) g_widget_event(WxEV_SYS_COLOUR, 0, 0);
+ });
+}
+
+// Run a deferred action after the current event finishes unwinding: emits
+// WxEV_DEFERRED with `id` from the main event loop. Used to rebuild a control
+// from outside its own event handler (destroying a widget mid-event is unsafe).
+void wxbr_call_after(int id) {
+ if (wxTheApp) {
+ wxTheApp->CallAfter([id]() {
+ if (g_widget_event) g_widget_event(WxEV_DEFERRED, id, 0);
+ });
+ }
+}
+
+// ---- deferred destroy (safe from event handlers) ----------------------------
+
+void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
+
+// Destroy a window's children immediately (used to rebuild a panel's dynamic
+// contents in place, e.g. the filter dialog's per-column controls).
+void wxbr_destroy_children(void* win) { ((wxWindow*)win)->DestroyChildren(); }
+
+} // extern "C"
@@ -20,10 +20,18 @@
#include <wx/app.h>
#include <wx/rearrangectrl.h>
#include <wx/menu.h>
#ifdef __WXGTK__
#include <gtk/gtk.h>
#endif
#include <wx/choice.h>
#include <wx/bmpbuttn.h>
#include <wx/bitmap.h>
#include <wx/image.h>
#include <wx/dcmemory.h>
#include <wx/dcgraph.h>
#include <wx/graphics.h>
#include <wx/wrapsizer.h>
#include <wx/filedlg.h>
#include <cstring>
#include <cstdio>
#include <vector>
typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
static WxWidgetEventFn g_widget_event = nullptr;
@@ -40,6 +48,123 @@ enum WxWidgetEventKind {
WxEV_DVLC_SELECTION_CHANGED = 9,
WxEV_DVLC_CONTEXT_MENU = 10,
WxEV_MENU_ITEM = 11,
WxEV_CHOICE_CHANGED = 12,
WxEV_SYS_COLOUR = 13,
WxEV_DEFERRED = 14,
};
// A list store that carries an optional per-row foreground colour, surfaced to
// the native control via GetAttrByRow. This is how the miner table paints each
// row's text by status and separates rows on GTK (where SetAlternateRowColour
// and :nth-child CSS are unreliable and fight the selection highlight).
class AttrListStore : public wxDataViewListStore {
public:
std::vector<wxColour> row_fg;
bool GetAttrByRow(unsigned int row, unsigned int col,
wxDataViewItemAttr& attr) const override {
(void)col;
if (row < row_fg.size() && row_fg[row].IsOk()) {
attr.SetColour(row_fg[row]);
return true;
}
return false;
}
};
// A wxDataViewCustomRenderer that draws a cell value made of coloured text
// runs. The encoding matches alkane_gui::model::encode_segments: segments are
// joined by U+001F (ASCII unit separator); each segment is an optional
// 6-hex-digit RRGGBB colour followed by U+001E (ASCII record separator) and
// then its plain text. A value containing no U+001E at all -- e.g. any
// ordinary string -- is drawn as a single run in the default text colour, so
// this renderer is safe to use in place of a plain text column.
namespace {
struct ColorSegment {
bool has_colour = false;
wxColour colour;
wxString text;
};
std::vector<ColorSegment> ParseColorSegments(const wxString& value) {
std::vector<ColorSegment> segs;
if (value.Find(wxUniChar(0x1e)) == wxNOT_FOUND) {
ColorSegment s;
s.text = value;
segs.push_back(s);
return segs;
}
wxString rest = value;
for (;;) {
int sep = rest.Find(wxUniChar(0x1f));
wxString piece = (sep == wxNOT_FOUND) ? rest : rest.Left(sep);
ColorSegment s;
int csep = piece.Find(wxUniChar(0x1e));
if (csep == wxNOT_FOUND) {
s.text = piece;
} else {
wxString hex = piece.Left(csep);
s.text = piece.Mid(csep + 1);
unsigned long v;
if (hex.length() == 6 && hex.ToULong(&v, 16)) {
s.colour = wxColour((unsigned char)((v >> 16) & 0xff),
(unsigned char)((v >> 8) & 0xff),
(unsigned char)(v & 0xff));
s.has_colour = true;
}
}
segs.push_back(s);
if (sep == wxNOT_FOUND) break;
rest = rest.Mid(sep + 1);
}
return segs;
}
} // namespace
class SegmentRenderer : public wxDataViewCustomRenderer {
public:
SegmentRenderer()
: wxDataViewCustomRenderer(wxASCII_STR("string"), wxDATAVIEW_CELL_INERT) {}
bool SetValue(const wxVariant& value) override {
m_value = value.GetString();
return true;
}
bool GetValue(wxVariant& value) const override {
value = m_value;
return true;
}
bool Render(wxRect cell, wxDC* dc, int state) override {
bool selected = (state & wxDATAVIEW_CELL_SELECTED) != 0;
wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
wxColour plain = GetAttr().HasColour()
? GetAttr().GetColour()
: wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
wxCoord x = cell.x;
for (const ColorSegment& seg : ParseColorSegments(m_value)) {
if (seg.text.IsEmpty()) continue;
dc->SetTextForeground(selected ? highlight : (seg.has_colour ? seg.colour : plain));
wxSize extent = dc->GetTextExtent(seg.text);
wxCoord y = cell.y + (cell.height - extent.GetHeight()) / 2;
dc->DrawText(seg.text, x, y);
x += extent.GetWidth();
}
return true;
}
wxSize GetSize() const override {
wxString plain;
for (const ColorSegment& seg : ParseColorSegments(m_value)) plain += seg.text;
wxSize sz = GetTextExtent(plain);
if (sz.GetWidth() < 1) sz.SetWidth(1);
return sz;
}
private:
wxString m_value;
};
extern "C" {
@@ -58,6 +183,14 @@ void* wxbr_box_sizer(int vertical) {
return (void*)new wxBoxSizer(vertical ? wxVERTICAL : wxHORIZONTAL);
}
// A box sizer that wraps its items onto additional lines instead of shrinking
// them when the available space runs out. wxWrapSizer is a wxBoxSizer
// subclass, so it accepts the same add/add_sizer/add_spacer/add_stretch and
// set_sizer_on calls as wxbr_box_sizer's result.
void* wxbr_wrap_sizer(int vertical) {
return (void*)new wxWrapSizer(vertical ? wxVERTICAL : wxHORIZONTAL);
}
// flag bits (must match Rust sizer_flags):
// 1 = EXPAND, 2 = ALIGN_CENTRE_VERTICAL, 4 = wxALL, 8 = wxTOP,
// 16 = wxBOTTOM, 32 = wxLEFT, 64 = wxRIGHT
@@ -166,6 +299,17 @@ void* wxbr_button(void* parent, const char* label, int id) {
return (void*)b;
}
// Make an arbitrary window (e.g. a KPI card panel) clickable: a left mouse
// down on it emits the same WxEV_BUTTON_CLICKED event a real button would,
// carrying `id`. Bind this on the panel itself; a child wxStaticText label
// swallows its own mouse events, so the caller binds each child that should
// also act as part of the click target rather than relying on propagation.
void wxbr_bind_click(void* win, int id) {
((wxWindow*)win)->Bind(wxEVT_LEFT_DOWN, [id](wxMouseEvent&) {
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
});
}
// ---- text ctrl ------------------------------------------------------------
void* wxbr_text_ctrl(void* parent, int multiline) {
@@ -264,65 +408,111 @@ void wxbr_dialog_close(void* win, int code) {
((wxDialog*)win)->EndModal(code);
}
// ---- file dialog -------------------------------------------------------------
// Show a native "open file, must exist" dialog. On OK, copies the chosen
// path (UTF-8) into buf (capped at cap) and returns its length + 1, like the
// other buffer-filling bridge functions; on Cancel returns 0 and leaves buf
// untouched.
int wxbr_file_dialog(void* parent, const char* title, char* buf, int cap) {
wxFileDialog dlg((wxWindow*)parent, wxString::FromUTF8(title), wxEmptyString,
wxEmptyString, wxFileSelectorDefaultWildcardStr,
wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (dlg.ShowModal() != wxID_OK) return 0;
wxCharBuffer b = dlg.GetPath().ToUTF8();
int n = (int)strlen(b.data());
if (n >= cap) n = cap - 1;
memcpy(buf, b.data(), n);
buf[n] = 0;
return n + 1;
}
// ---- data view list ctrl ------------------------------------------------------
static AttrListStore* dvlc_store(void* win) {
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
}
void* wxbr_dvlc(void* parent) {
// Multi-select (ctrl/shift-click) + row lines. Selection replaces the old
// checkbox column.
wxDataViewListCtrl* lc =
new wxDataViewListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, -1), wxDV_ROW_LINES | wxDV_MULTIPLE);
lc->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
// checkbox column. A custom AttrListStore backs it so rows can be coloured by
// status while the native selection highlight still shows through.
wxDataViewCtrl* dv =
new wxDataViewCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, -1), wxDV_ROW_LINES | wxDV_MULTIPLE);
AttrListStore* store = new AttrListStore();
dv->AssociateModel(store);
store->DecRef(); // the control owns a reference now
dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
});
lc->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [](wxDataViewEvent&) {
dv->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [](wxDataViewEvent&) {
if (g_widget_event) g_widget_event(WxEV_DVLC_CONTEXT_MENU, 0, 0);
});
lc->Bind(wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [](wxDataViewEvent& e) {
dv->Bind(wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [](wxDataViewEvent& e) {
if (g_widget_event) {
wxDataViewListCtrl* lc =
dynamic_cast<wxDataViewListCtrl*>((wxWindow*)e.GetEventObject());
if (!lc) return;
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv) return;
wxDataViewItem item = e.GetItem();
if (!item.IsOk()) return;
int row = lc->GetStore()->GetRow(item);
int row = ((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
g_widget_event(WxEV_DVLC_VALUE_CHANGED, row, (long)e.GetColumn());
}
});
lc->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, [](wxDataViewEvent& e) {
dv->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, [](wxDataViewEvent& e) {
if (g_widget_event) g_widget_event(WxEV_DVLC_HEADER_CLICK, (long)e.GetColumn(), 0);
});
lc->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);
});
// Row activation (double-click / Enter): report the row + column so the app
// can, e.g., open the miner's IP in a browser.
lc->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
dv->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [](wxDataViewEvent& e) {
if (g_widget_event) {
wxDataViewListCtrl* lc =
dynamic_cast<wxDataViewListCtrl*>((wxWindow*)e.GetEventObject());
if (!lc) return;
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv) return;
wxDataViewItem item = e.GetItem();
if (!item.IsOk()) return;
int row = lc->GetStore()->GetRow(item);
int row = ((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
g_widget_event(WxEV_DVLC_ACTIVATED, row, (long)e.GetColumn());
}
});
return (void*)lc;
return (void*)dv;
}
void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
int flags = wxDATAVIEW_COL_RESIZABLE;
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
((wxDataViewListCtrl*)win)
->AppendTextColumn(wxString::FromUTF8(title), wxDATAVIEW_CELL_INERT,
width, wxALIGN_NOT, flags);
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
width, wxALIGN_NOT, flags);
}
// Same bookkeeping as wxbr_dvlc_append_text_col, but the column is drawn by a
// SegmentRenderer so its cell values can carry the '\x1f'/'\x1e' colour-run
// encoding produced by alkane_gui::model::encode_segments. An ordinary string
// with no encoding in it still renders fine (single default-coloured run).
void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
int flags = wxDATAVIEW_COL_RESIZABLE;
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
SegmentRenderer* renderer = new SegmentRenderer();
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
width, wxALIGN_NOT, flags);
dv->AppendColumn(c);
return (void*)c;
}
void wxbr_dvlc_append_toggle_col(void* win, int width) {
((wxDataViewListCtrl*)win)
->AppendToggleColumn(wxT(""), wxDATAVIEW_CELL_ACTIVATABLE, width,
wxALIGN_CENTRE, 0);
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned col = dv->GetColumnCount();
dvlc_store(win)->AppendColumn("bool");
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
wxALIGN_CENTRE, 0);
}
void wxbr_dvlc_append_row(void* win, int nvals, const char** vals) {
@@ -331,28 +521,45 @@ void wxbr_dvlc_append_row(void* win, int nvals, const char** vals) {
for (int i = 0; i < nvals; i++) {
values.push_back(wxVariant(vals[i] ? wxString::FromUTF8(vals[i]) : wxString()));
}
((wxDataViewListCtrl*)win)->AppendItem(values);
AttrListStore* store = dvlc_store(win);
store->AppendItem(values);
store->row_fg.push_back(wxColour()); // no per-row colour until set
}
void wxbr_dvlc_delete_row(void* win, unsigned row) {
((wxDataViewListCtrl*)win)->DeleteItem(row);
AttrListStore* store = dvlc_store(win);
store->DeleteItem(row);
if (row < store->row_fg.size()) store->row_fg.erase(store->row_fg.begin() + row);
}
void wxbr_dvlc_clear(void* win) { ((wxDataViewListCtrl*)win)->DeleteAllItems(); }
void wxbr_dvlc_clear(void* win) {
AttrListStore* store = dvlc_store(win);
store->DeleteAllItems();
store->row_fg.clear();
}
// Set (or clear, when r<0) a row's text colour; used to paint rows by status.
void wxbr_dvlc_set_row_color(void* win, unsigned row, int r, int g, int b) {
AttrListStore* store = dvlc_store(win);
if (row >= store->row_fg.size()) return;
store->row_fg[row] = (r < 0) ? wxColour() : wxColour(r, g, b);
store->RowChanged(row);
}
int wxbr_dvlc_row_count(void* win) {
return (int)((wxDataViewListCtrl*)win)->GetStore()->GetItemCount();
return (int)dvlc_store(win)->GetItemCount();
}
void wxbr_dvlc_set_cell(void* win, unsigned row, unsigned col, const char* value) {
((wxDataViewListCtrl*)win)
->SetValue(wxVariant(wxString::FromUTF8(value)), row, col);
AttrListStore* store = dvlc_store(win);
store->SetValueByRow(wxVariant(wxString::FromUTF8(value)), row, col);
store->RowValueChanged(row, col);
}
int wxbr_dvlc_get_cell(void* win, unsigned row, unsigned col, char* buf, int cap) {
wxDataViewListCtrl* lc = (wxDataViewListCtrl*)win;
wxDataViewListStore* store = lc->GetStore();
if (row >= store->GetItemCount() || col >= lc->GetColumnCount())
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
AttrListStore* store = dvlc_store(win);
if (row >= store->GetItemCount() || (int)col >= (int)dv->GetColumnCount())
return 0;
wxVariant v;
store->GetValueByRow(v, row, col);
@@ -366,7 +573,7 @@ int wxbr_dvlc_get_cell(void* win, unsigned row, unsigned col, char* buf, int cap
}
int wxbr_dvlc_col_count(void* win) {
return (int)((wxDataViewListCtrl*)win)->GetColumnCount();
return (int)((wxDataViewCtrl*)win)->GetColumnCount();
}
// Update a column's header text in place (creation index) without recreating
@@ -406,58 +613,51 @@ int wxbr_dvlc_col_at_pos(void* win, int pos) {
}
long wxbr_dvlc_selected_row(void* win) {
return (long)((wxDataViewListCtrl*)win)->GetSelectedRow();
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewItem it = dv->GetSelection();
if (!it.IsOk()) return -1;
return (long)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(it);
}
// Fill `buf` with the selected row indices (multi-select); returns the count.
int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
wxDataViewListCtrl* lc = (wxDataViewListCtrl*)win;
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
wxDataViewItemArray items;
int n = (int)lc->GetSelections(items);
int n = (int)dv->GetSelections(items);
int out = 0;
for (int i = 0; i < n && out < cap; i++) {
int row = lc->GetStore()->GetRow(items[i]);
int row = m->GetRow(items[i]);
if (row >= 0) buf[out++] = row;
}
return out;
}
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
wxDataViewListCtrl* lc = (wxDataViewListCtrl*)win;
lc->UnselectAll();
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
dv->UnselectAll();
for (int i = 0; i < n; i++) {
if (rows[i] >= 0) lc->SelectRow((unsigned)rows[i]);
if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
}
}
// Retained for ABI; per-row colour is handled by the store (GetAttrByRow) and
// the native selection highlight, so these row-background hacks are no-ops now
// (they fought the selection highlight on GTK 3.3).
void wxbr_dvlc_set_alt_row_color(void* win, int r, int g, int b) {
// No-op on GTK (native dataview lacks it); see wxbr_apply_zebra_css.
((wxDataViewListCtrl*)win)->SetAlternateRowColour(wxColour(r, g, b));
(void)win; (void)r; (void)g; (void)b;
}
// GTK's native dataview does not implement SetAlternateRowColour, so apply
// zebra striping app-wide via a CSS provider (GTK 3.20+ supports :nth-child on
// treeview rows). No-op off GTK.
void wxbr_apply_zebra_css(int r, int g, int b) {
#ifdef __WXGTK__
GtkCssProvider* p = gtk_css_provider_new();
char css[192];
std::snprintf(css, sizeof(css),
"treeview.view:nth-child(even){background-color:rgb(%d,%d,%d);}",
r, g, b);
gtk_css_provider_load_from_data(p, css, -1, NULL);
gtk_style_context_add_provider_for_screen(
gdk_screen_get_default(), GTK_STYLE_PROVIDER(p),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
g_object_unref(p);
#else
(void)r; (void)g; (void)b;
#endif
}
void wxbr_dvlc_select_row(void* win, long row) {
if (row < 0) return;
((wxDataViewListCtrl*)win)->SelectRow((unsigned)row);
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
dv->Select(m->GetItem((unsigned)row));
}
// ---- timer -----------------------------------------------------------------
@@ -591,8 +791,102 @@ void wxbr_popup_menu(void* win, void* menu) {
delete m;
}
// ---- choice (dropdown) ------------------------------------------------------
void* wxbr_choice(void* parent, int id) {
wxChoice* c = new wxChoice((wxWindow*)parent, id);
c->Bind(wxEVT_CHOICE, [id](wxCommandEvent& e) {
if (g_widget_event)
g_widget_event(WxEV_CHOICE_CHANGED, id, (long)e.GetSelection());
});
return (void*)c;
}
void wxbr_choice_append(void* win, const char* label) {
((wxChoice*)win)->Append(wxString::FromUTF8(label));
}
void wxbr_choice_clear(void* win) { ((wxChoice*)win)->Clear(); }
int wxbr_choice_get_selection(void* win) {
return ((wxChoice*)win)->GetSelection();
}
void wxbr_choice_set_selection(void* win, int i) {
((wxChoice*)win)->SetSelection(i);
}
// ---- media (icon) button: play / pause / stop -------------------------------
// kind: 0=play (triangle), 1=pause (two bars), 2=stop (square). Drawn in the
// given colour on a transparent bitmap so it reads as a coloured glyph on the
// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
const int sz = 20;
wxImage img(sz, sz);
img.InitAlpha();
unsigned char* a = img.GetAlpha();
if (a) memset(a, 0, (size_t)sz * sz); // fully transparent
wxBitmap bmp(img);
{
wxMemoryDC mdc(bmp);
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
if (gc) {
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
wxColour col(r, g, b);
gc->SetBrush(wxBrush(col));
gc->SetPen(wxPen(col, 1.0));
if (kind == 0) {
wxGraphicsPath p = gc->CreatePath();
p.MoveToPoint(5, 4);
p.AddLineToPoint(16, 10);
p.AddLineToPoint(5, 16);
p.CloseSubpath();
gc->FillPath(p);
} else if (kind == 1) {
gc->DrawRectangle(5, 4, 3.5, 12);
gc->DrawRectangle(11.5, 4, 3.5, 12);
} else {
gc->DrawRectangle(5, 5, 10, 10);
}
delete gc;
}
}
wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bmp);
btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
});
return (void*)btn;
}
// ---- live theme changes -----------------------------------------------------
// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
// repaint custom-coloured widgets (KPI cards, table rows).
void wxbr_bind_sys_colour(void* win) {
((wxWindow*)win)->Bind(wxEVT_SYS_COLOUR_CHANGED, [](wxSysColourChangedEvent& e) {
e.Skip();
if (g_widget_event) g_widget_event(WxEV_SYS_COLOUR, 0, 0);
});
}
// Run a deferred action after the current event finishes unwinding: emits
// WxEV_DEFERRED with `id` from the main event loop. Used to rebuild a control
// from outside its own event handler (destroying a widget mid-event is unsafe).
void wxbr_call_after(int id) {
if (wxTheApp) {
wxTheApp->CallAfter([id]() {
if (g_widget_event) g_widget_event(WxEV_DEFERRED, id, 0);
});
}
}
// ---- deferred destroy (safe from event handlers) ----------------------------
void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
// Destroy a window's children immediately (used to rebuild a panel's dynamic
// contents in place, e.g. the filter dialog's per-column controls).
void wxbr_destroy_children(void* win) { ((wxWindow*)win)->DestroyChildren(); }
} // extern "C"
+127
View File
@@ -15,6 +15,7 @@ mod notsafe {
pub fn wxbr_main_frame() -> *mut c_void;
pub fn wxbr_panel(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_box_sizer(vertical: c_int) -> *mut c_void;
pub fn wxbr_wrap_sizer(vertical: c_int) -> *mut c_void;
pub fn wxbr_sizer_add(sizer: *mut c_void, win: *mut c_void, proportion: c_int, flags: c_int, border: c_int);
pub fn wxbr_sizer_add_sizer(sizer: *mut c_void, subsizer: *mut c_void, proportion: c_int, flags: c_int, border: c_int);
pub fn wxbr_sizer_add_spacer(sizer: *mut c_void, px: c_int);
@@ -30,6 +31,7 @@ mod notsafe {
pub fn wxbr_set_bold(win: *mut c_void);
pub fn wxbr_set_font_size(win: *mut c_void, pts: c_int);
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
@@ -46,8 +48,10 @@ mod notsafe {
pub fn wxbr_dialog(parent: *mut c_void, title: *const c_char) -> *mut c_void;
pub fn wxbr_dialog_show_modal(win: *mut c_void) -> c_int;
pub fn wxbr_dialog_close(win: *mut c_void, code: c_int);
pub fn wxbr_file_dialog(parent: *mut c_void, title: *const c_char, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_dvlc(parent: *mut c_void) -> *mut c_void;
pub fn wxbr_dvlc_append_text_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int);
pub fn wxbr_dvlc_append_colored_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int) -> *mut c_void;
pub fn wxbr_dvlc_append_toggle_col(win: *mut c_void, width: c_int);
pub fn wxbr_dvlc_append_row(win: *mut c_void, nvals: c_int, vals: *const *const c_char);
pub fn wxbr_dvlc_delete_row(win: *mut c_void, row: usize);
@@ -64,6 +68,7 @@ mod notsafe {
pub fn wxbr_dvlc_get_selections(win: *mut c_void, buf: *mut c_int, cap: c_int) -> c_int;
pub fn wxbr_dvlc_select_rows(win: *mut c_void, rows: *const c_int, n: c_int);
pub fn wxbr_dvlc_set_alt_row_color(win: *mut c_void, r: c_int, g: c_int, b: c_int);
pub fn wxbr_dvlc_set_row_color(win: *mut c_void, row: usize, r: c_int, g: c_int, b: c_int);
pub fn wxbr_apply_zebra_css(r: c_int, g: c_int, b: c_int);
pub fn wxbr_rearrange_list(parent: *mut c_void, n: c_int, order: *const c_int, items: *const *const c_char) -> *mut c_void;
pub fn wxbr_rearrange_get_order(win: *mut c_void, buf: *mut c_int, cap: c_int) -> c_int;
@@ -83,7 +88,16 @@ mod notsafe {
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
pub fn wxbr_choice(parent: *mut c_void, id: c_int) -> *mut c_void;
pub fn wxbr_choice_append(win: *mut c_void, label: *const c_char);
pub fn wxbr_choice_clear(win: *mut c_void);
pub fn wxbr_choice_get_selection(win: *mut c_void) -> c_int;
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
pub fn wxbr_bind_sys_colour(win: *mut c_void);
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);
}
}
@@ -116,6 +130,9 @@ pub enum WxEventKind {
DvlcSelectionChanged,
DvlcContextMenu,
MenuItem,
ChoiceChanged,
SysColour,
Deferred,
}
impl WxEventKind {
@@ -131,6 +148,9 @@ impl WxEventKind {
9 => WxEventKind::DvlcSelectionChanged,
10 => WxEventKind::DvlcContextMenu,
11 => WxEventKind::MenuItem,
12 => WxEventKind::ChoiceChanged,
13 => WxEventKind::SysColour,
14 => WxEventKind::Deferred,
_ => return None,
})
}
@@ -141,6 +161,13 @@ pub fn apply_zebra_css(r: u8, g: u8, b: u8) {
unsafe { notsafe::wxbr_apply_zebra_css(r as c_int, g as c_int, b as c_int) }
}
/// Schedule a deferred action: a `Deferred` event carrying `id` is delivered
/// from the event loop after the current event finishes. Use this to rebuild or
/// destroy a control from outside its own event handler.
pub fn call_after(id: i32) {
unsafe { notsafe::wxbr_call_after(id 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();
@@ -216,6 +243,14 @@ impl Widget {
Widget(unsafe { notsafe::wxbr_box_sizer(vertical as c_int) })
}
/// A box sizer that wraps overflowing items onto additional lines instead
/// of shrinking them. wxWrapSizer is a wxBoxSizer subclass, so the result
/// accepts the same add/add_sizer/add_spacer/add_stretch/set_sizer_on
/// calls as `box_sizer`'s.
pub fn wrap_sizer(vertical: bool) -> Widget {
Widget(unsafe { notsafe::wxbr_wrap_sizer(vertical as c_int) })
}
pub fn add(&self, win: Widget, proportion: i32, flags: i32, border: i32) {
unsafe { notsafe::wxbr_sizer_add(self.0, win.0, proportion, flags, border) }
}
@@ -292,6 +327,15 @@ impl Widget {
Widget(unsafe { notsafe::wxbr_button(parent.0, c.as_ptr(), id) })
}
/// Make this window clickable: a left mouse down on it emits the same
/// `ButtonClicked` event a real button would, carrying `id`. Bind each
/// child that should also count as part of the click target (e.g. the
/// static text labels on a KPI card), since a child window swallows its
/// own mouse events rather than letting them propagate to the parent.
pub fn bind_click(&self, id: i32) {
unsafe { notsafe::wxbr_bind_click(self.0, id) }
}
pub fn text_ctrl(parent: Widget, multiline: bool) -> Widget {
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
}
@@ -371,6 +415,21 @@ impl Widget {
unsafe { notsafe::wxbr_dialog_close(self.0, code) }
}
/// Show a native "open file, must exist" dialog. Returns the chosen path,
/// or `None` if the dialog was cancelled.
pub fn file_dialog(parent: Widget, title: &str) -> Option<String> {
let c = CString::new(title).unwrap_or_default();
let mut buf = vec![0i8; 4096];
let n = unsafe {
notsafe::wxbr_file_dialog(parent.0, c.as_ptr(), buf.as_mut_ptr(), buf.len() as c_int)
};
if n <= 0 {
return None;
}
let bytes: Vec<u8> = buf[..(n - 1) as usize].iter().map(|&b| b as u8).collect();
Some(String::from_utf8_lossy(&bytes).into_owned())
}
// ---- data view list ctrl ----
pub fn dvlc(parent: Widget) -> Widget {
@@ -382,6 +441,14 @@ impl Widget {
unsafe { notsafe::wxbr_dvlc_append_text_col(self.0, c.as_ptr(), width, reorderable as c_int) }
}
/// Like `dvlc_append_text_col`, but the column renders cell values through
/// the SegmentRenderer, so a value built with `model::encode_segments` is
/// drawn as coloured text runs (a plain string still renders normally).
pub fn dvlc_append_colored_col(&self, title: &str, width: i32, reorderable: bool) {
let c = CString::new(title).unwrap_or_default();
unsafe { notsafe::wxbr_dvlc_append_colored_col(self.0, c.as_ptr(), width, reorderable as c_int) };
}
pub fn dvlc_append_toggle_col(&self, width: i32) {
unsafe { notsafe::wxbr_dvlc_append_toggle_col(self.0, width) }
}
@@ -459,6 +526,15 @@ impl Widget {
unsafe { notsafe::wxbr_dvlc_set_alt_row_color(self.0, r as c_int, g as c_int, b as c_int) }
}
/// Set a row's text colour (e.g. by miner status). Pass `None` to clear it.
pub fn dvlc_set_row_color(&self, row: usize, color: Option<(u8, u8, u8)>) {
let (r, g, b) = match color {
Some((r, g, b)) => (r as c_int, g as c_int, b as c_int),
None => (-1, -1, -1),
};
unsafe { notsafe::wxbr_dvlc_set_row_color(self.0, row, r, g, b) }
}
// ---- rearrangeable check-list ----
/// Create a rearrangeable checklist. `order` uses wx encoding: a value `v`
@@ -553,9 +629,60 @@ impl Widget {
unsafe { notsafe::wxbr_set_fg(self.0, r as c_int, g as c_int, b as c_int) }
}
// ---- choice (dropdown) ----
/// Create a dropdown; selection changes emit `ChoiceChanged` with this id.
pub fn choice(parent: Widget, id: i32) -> Widget {
Widget(unsafe { notsafe::wxbr_choice(parent.0, id) })
}
pub fn choice_append(&self, label: &str) {
let c = CString::new(label).unwrap_or_default();
unsafe { notsafe::wxbr_choice_append(self.0, c.as_ptr()) }
}
pub fn choice_clear(&self) {
unsafe { notsafe::wxbr_choice_clear(self.0) }
}
pub fn choice_get_selection(&self) -> i32 {
unsafe { notsafe::wxbr_choice_get_selection(self.0) }
}
pub fn choice_set_selection(&self, i: i32) {
unsafe { notsafe::wxbr_choice_set_selection(self.0, i) }
}
// ---- media (icon) button ----
/// A coloured icon button: `kind` 0=play, 1=pause, 2=stop. Clicks emit
/// `ButtonClicked` with `id`, like a normal button.
pub fn media_button(parent: Widget, id: i32, kind: i32, color: (u8, u8, u8)) -> Widget {
Widget(unsafe {
notsafe::wxbr_media_button(
parent.0,
id,
kind,
color.0 as c_int,
color.1 as c_int,
color.2 as c_int,
)
})
}
/// Listen for OS light/dark theme changes on this window (emits `SysColour`).
pub fn bind_sys_colour(&self) {
unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
}
/// Deferred destruction (safe from event handlers); used to rebuild
/// the table when its column set changes.
pub fn destroy(&self) {
unsafe { notsafe::wxbr_destroy(self.0) }
}
/// Destroy this window's children (to rebuild dynamic panel contents).
pub fn destroy_children(&self) {
unsafe { notsafe::wxbr_destroy_children(self.0) }
}
}