Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
297e21a519 | ||
|
|
7fac0ce726 | ||
|
|
8e9c5e7105 |
@@ -21,6 +21,10 @@ jobs:
|
||||
id: ver
|
||||
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Test version logic
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
run: bash ci/test-compute-version.sh
|
||||
|
||||
- name: Install build dependencies
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
run: |
|
||||
@@ -71,9 +75,9 @@ jobs:
|
||||
|
||||
- name: Headless UI self-test
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
apt-get update -qq && apt-get install -y -qq --no-install-recommends xvfb dbus-x11 fonts-dejavu-core >/dev/null
|
||||
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
|
||||
xvfb xauth dbus-x11 fonts-dejavu-core >/dev/null
|
||||
BIN=target/release/alkane-toolkit
|
||||
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
|
||||
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
/target
|
||||
|
||||
|
||||
**/target
|
||||
.claude/
|
||||
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for ci/compute-version.sh (the X.Y.Z versioning logic). Each case builds
|
||||
# a throwaway git repo in a scratch tmp dir (never inside this repo / the Ultron
|
||||
# mount), lays out a scenario, runs compute-version.sh inside it, and asserts the
|
||||
# emitted KEY=VALUE lines. Run: bash ci/test-compute-version.sh
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT="$(cd "$(dirname "$0")" && pwd)/compute-version.sh"
|
||||
[ -f "$SCRIPT" ] || { echo "cannot find compute-version.sh at $SCRIPT"; exit 2; }
|
||||
|
||||
pass=0
|
||||
fail=0
|
||||
|
||||
# new_repo: fresh git repo in a scratch dir, echoes its path.
|
||||
new_repo() {
|
||||
local r
|
||||
r="$(mktemp -d "${TMPDIR:-/tmp}/alkane-cv-XXXXXX")"
|
||||
git -C "$r" init -q
|
||||
git -C "$r" config user.email t@t
|
||||
git -C "$r" config user.name t
|
||||
echo "$r"
|
||||
}
|
||||
|
||||
commit() { # commit <repo> <msg>
|
||||
git -C "$1" add -A
|
||||
git -C "$1" commit -q -m "$2"
|
||||
}
|
||||
|
||||
# run_case: <name> <repo> then key=value expectations as remaining args.
|
||||
run_case() {
|
||||
local name="$1" repo="$2"; shift 2
|
||||
local out get k v ok=1
|
||||
out="$(cd "$repo" && bash "$SCRIPT")"
|
||||
get() { echo "$out" | grep "^$1=" | cut -d= -f2-; }
|
||||
for kv in "$@"; do
|
||||
k="${kv%%=*}"; v="${kv#*=}"
|
||||
if [ "$(get "$k")" != "$v" ]; then
|
||||
echo "FAIL [$name]: expected $k=$v, got $k=$(get "$k")"
|
||||
ok=0
|
||||
fi
|
||||
done
|
||||
if [ "$ok" = 1 ]; then echo "PASS [$name]"; pass=$((pass + 1)); else fail=$((fail + 1)); fi
|
||||
rm -rf "$repo"
|
||||
}
|
||||
|
||||
# 1. First release, no tag, X=0 -> 0.1.0
|
||||
R="$(new_repo)"; mkdir -p "$R/ci"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init
|
||||
run_case first_release "$R" version=0.1.0 tag=v0.1.0 bump=initial release=true last_tag=none
|
||||
|
||||
# 2. First release with a pre-bumped major (X=2, no tag) -> 2.0.0
|
||||
R="$(new_repo)"; mkdir -p "$R/ci"; printf '2' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init
|
||||
run_case first_release_prebumped_x "$R" version=2.0.0 bump=initial release=true
|
||||
|
||||
# 3. Backend path change bumps Y
|
||||
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf 'fn x(){}' > "$R/crates/alkane-gui/src/scan.rs"; commit "$R" backend
|
||||
run_case backend_bump "$R" version=1.3.0 tag=v1.3.0 bump=backend release=true last_tag=v1.2.3
|
||||
|
||||
# 4. UI path change bumps Z
|
||||
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf 'fn x(){}' > "$R/crates/alkane-gui/src/fixtures.rs"; commit "$R" ui
|
||||
run_case ui_bump "$R" version=1.2.4 bump=ui release=true
|
||||
|
||||
# 5. Docs-only change -> no release
|
||||
R="$(new_repo)"; mkdir -p "$R/ci"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf 'more docs' > "$R/README.md"; commit "$R" docs
|
||||
run_case no_release_docs_only "$R" version=1.2.3 bump=none release=false
|
||||
|
||||
# 6. Manual major bump wins over a simultaneous UI change
|
||||
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf '2' > "$R/ci/version-x.txt"; printf 'fn x(){}' > "$R/crates/alkane-gui/src/fixtures.rs"; commit "$R" bumpx
|
||||
run_case manual_major_wins_over_ui "$R" version=2.0.0 bump=major release=true
|
||||
|
||||
# 7. Backend wins over UI when both change in the same diff
|
||||
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf 'a' > "$R/crates/alkane-gui/src/scan.rs"
|
||||
printf 'b' > "$R/crates/alkane-gui/src/fixtures.rs"; commit "$R" both
|
||||
run_case backend_wins_over_ui "$R" version=1.3.0 bump=backend release=true
|
||||
|
||||
# 8. Nested ci/ path classified as backend (also covers editing compute-version.sh)
|
||||
R="$(new_repo)"; mkdir -p "$R/ci"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf '# tweak' >> "$R/ci/compute-version.sh"; commit "$R" ci
|
||||
run_case ci_nested_is_backend "$R" version=1.3.0 bump=backend release=true
|
||||
|
||||
# 9. Nested thirdparty/wx-rs path classified as UI
|
||||
R="$(new_repo)"; mkdir -p "$R/ci" "$R/thirdparty/wx-rs/src/deep"; printf '0' > "$R/ci/version-x.txt"
|
||||
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
|
||||
printf 'x' > "$R/thirdparty/wx-rs/src/deep/nested.rs"; commit "$R" wx
|
||||
run_case wx_rs_nested_is_ui "$R" version=1.2.4 bump=ui release=true
|
||||
|
||||
echo "----"
|
||||
echo "compute-version tests: $pass passed, $fail failed"
|
||||
[ "$fail" -eq 0 ]
|
||||
+401
-17
@@ -29,11 +29,19 @@ pub fn format_si(value_base: f64, unit: &str) -> String {
|
||||
v /= 1000.0;
|
||||
i += 1;
|
||||
}
|
||||
let num = if v >= 100.0 {
|
||||
format!("{v:.0}")
|
||||
} else {
|
||||
format!("{v:.1}")
|
||||
};
|
||||
// Round first, then re-check the prefix. A mantissa that rounds up to 1000
|
||||
// (e.g. 999.9 -> "1000") must roll over to the next prefix so the number
|
||||
// never shows more than three integer digits; and a mantissa in [99.95,100)
|
||||
// rounds to "100.0" and should drop its decimal (the >=100 branch's rule).
|
||||
let render = |v: f64| if v >= 100.0 { format!("{v:.0}") } else { format!("{v:.1}") };
|
||||
let mut num = render(v);
|
||||
if (num == "1000" || num == "1000.0") && i < PREFIXES.len() - 1 {
|
||||
v /= 1000.0;
|
||||
i += 1;
|
||||
num = render(v);
|
||||
} else if num == "100.0" {
|
||||
num = "100".to_string();
|
||||
}
|
||||
format!("{num} {}{unit}", PREFIXES[i])
|
||||
}
|
||||
|
||||
@@ -57,6 +65,19 @@ 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 {
|
||||
let mut parts = s.split('.');
|
||||
let mut acc = 0u32;
|
||||
for _ in 0..4 {
|
||||
let octet: u32 = parts.next().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
|
||||
acc = (acc << 8) | (octet & 0xff);
|
||||
}
|
||||
acc
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -332,6 +353,22 @@ 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> {
|
||||
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.
|
||||
@@ -361,6 +398,8 @@ impl Column {
|
||||
Column::TuningPercent => {
|
||||
SortKey::Num(r.tuning_percent.map(|v| v as f64).unwrap_or(none))
|
||||
}
|
||||
// IP sorts numerically (u32 fits exactly in f64), not lexically.
|
||||
Column::Ip => SortKey::Num(ip_to_u32(&r.ip) as f64),
|
||||
_ => SortKey::Str(self.cell(r).to_lowercase()),
|
||||
}
|
||||
}
|
||||
@@ -451,14 +490,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 {
|
||||
@@ -509,11 +612,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.
|
||||
@@ -522,16 +623,21 @@ impl ViewState {
|
||||
.filter(|&i| self.passes_filters(&rows[i]))
|
||||
.collect();
|
||||
if let Some((col, asc)) = self.sort {
|
||||
idx.sort_by(|&a, &b| {
|
||||
let ka = col.sort_key(&rows[a]);
|
||||
let kb = col.sort_key(&rows[b]);
|
||||
// Decorate-sort-undecorate: compute each row's sort key exactly once
|
||||
// (a string key allocates), not twice per comparison.
|
||||
let mut keyed: Vec<(SortKey, usize)> =
|
||||
idx.iter().map(|&i| (col.sort_key(&rows[i]), i)).collect();
|
||||
keyed.sort_by(|(ka, _), (kb, _)| {
|
||||
let ord = match (ka, kb) {
|
||||
(SortKey::Num(x), SortKey::Num(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
|
||||
(SortKey::Str(x), SortKey::Str(y)) => x.cmp(&y),
|
||||
(SortKey::Num(x), SortKey::Num(y)) => {
|
||||
x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
(SortKey::Str(x), SortKey::Str(y)) => x.cmp(y),
|
||||
_ => std::cmp::Ordering::Equal,
|
||||
};
|
||||
if asc { ord } else { ord.reverse() }
|
||||
});
|
||||
idx = keyed.into_iter().map(|(_, i)| i).collect();
|
||||
}
|
||||
idx
|
||||
}
|
||||
@@ -656,7 +762,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");
|
||||
@@ -812,4 +918,282 @@ mod tests {
|
||||
assert!(r.selected, "selection preserved across upsert");
|
||||
assert_eq!(r.hashrate_ths, 12.3, "data updated");
|
||||
}
|
||||
|
||||
// ---- harness-driven additions (correctness + coverage) ----
|
||||
|
||||
#[test]
|
||||
fn format_si_handles_zero_negative_and_nonfinite() {
|
||||
assert_eq!(format_si(0.0, "W"), "0 W");
|
||||
assert_eq!(format_si(-5.0, "W"), "0 W");
|
||||
assert_eq!(format_si(f64::NAN, "W"), "0 W");
|
||||
assert_eq!(format_si(f64::INFINITY, "H/s"), "0 H/s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_si_rolls_over_at_rounding_boundary() {
|
||||
// A mantissa that rounds up to 1000 must advance the prefix, never print
|
||||
// a 4-digit number (spec: at most 2 digits + 1 decimal after the prefix).
|
||||
assert_eq!(format_si(999.9, "W"), "1.0 kW");
|
||||
assert_eq!(format_si(999_990.0, "W"), "1.0 MW");
|
||||
assert_eq!(format_si(1000.0, "W"), "1.0 kW");
|
||||
// [99.95, 100) rounds to 100 and drops the decimal (>=100 rule).
|
||||
assert_eq!(format_si(99.95, "W"), "100 W");
|
||||
assert_eq!(format_si(45.6, "W"), "45.6 W");
|
||||
assert_eq!(format_si(250.0, "W"), "250 W");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_uptime_boundaries() {
|
||||
assert_eq!(format_uptime(0), "");
|
||||
assert_eq!(format_uptime(59), "59s");
|
||||
assert_eq!(format_uptime(60), "1m");
|
||||
assert_eq!(format_uptime(3599), "59m");
|
||||
assert_eq!(format_uptime(3600), "1h 0m");
|
||||
assert_eq!(format_uptime(86_399), "23h 59m");
|
||||
assert_eq!(format_uptime(86_400), "1d 0h");
|
||||
assert_eq!(format_uptime(90_061), "1d 1h");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ip_column_sorts_numerically() {
|
||||
// A plain string sort puts "10.255.1.10" before "10.255.1.2"; the IP
|
||||
// column must order by numeric value instead.
|
||||
let rows = vec![
|
||||
MinerRow { ip: "10.255.1.10".into(), ..Default::default() },
|
||||
MinerRow { ip: "10.255.1.2".into(), ..Default::default() },
|
||||
MinerRow { ip: "10.255.1.112".into(), ..Default::default() },
|
||||
MinerRow { ip: "10.255.1.9".into(), ..Default::default() },
|
||||
];
|
||||
let idx = ViewState::default().view(&rows); // default = Ip ascending
|
||||
let order: Vec<&str> = idx.iter().map(|&i| rows[i].ip.as_str()).collect();
|
||||
assert_eq!(order, ["10.255.1.2", "10.255.1.9", "10.255.1.10", "10.255.1.112"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_into_new_ip_inserts_and_returns_true() {
|
||||
let mut rows = bench_fleet();
|
||||
let n0 = rows.len();
|
||||
let fresh = MinerRow { ip: "10.9.9.9".into(), ..Default::default() };
|
||||
let is_new = fresh.upsert_into(&mut rows);
|
||||
assert!(is_new, "a never-seen IP is an insert");
|
||||
assert_eq!(rows.len(), n0 + 1);
|
||||
assert!(rows.iter().any(|r| r.ip == "10.9.9.9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_light_three_states() {
|
||||
let on = MinerRow { light_flashing: Some(true), ..Default::default() };
|
||||
let off = MinerRow { light_flashing: Some(false), ..Default::default() };
|
||||
let unknown = MinerRow { light_flashing: None, ..Default::default() };
|
||||
assert_eq!(Column::Light.cell(&on), "on");
|
||||
assert_eq!(Column::Light.cell(&off), "off");
|
||||
assert_eq!(Column::Light.cell(&unknown), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_pool_slots_including_out_of_range() {
|
||||
let r = MinerRow {
|
||||
pools: vec![
|
||||
("stratum+tcp://a:1".into(), "wA".into()),
|
||||
("stratum+tcp://b:2".into(), "wB".into()),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(Column::Pool1Url.cell(&r), "stratum+tcp://a:1");
|
||||
assert_eq!(Column::Pool1Worker.cell(&r), "wA");
|
||||
assert_eq!(Column::Pool2Url.cell(&r), "stratum+tcp://b:2");
|
||||
assert_eq!(Column::Pool2Worker.cell(&r), "wB");
|
||||
// Third pool is unconfigured -> blank, not a panic.
|
||||
assert_eq!(Column::Pool3Url.cell(&r), "");
|
||||
assert_eq!(Column::Pool3Worker.cell(&r), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_filters_ands_across_columns() {
|
||||
let rows = vec![
|
||||
MinerRow { ip: "10.0.0.1".into(), is_mining: true, model: "A".into(), ..Default::default() },
|
||||
MinerRow { ip: "10.0.0.2".into(), is_mining: true, model: "B".into(), ..Default::default() },
|
||||
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, 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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_filters_ors_within_one_column() {
|
||||
let rows = bench_fleet();
|
||||
let mut view = ViewState::default();
|
||||
view.filters.insert(
|
||||
Column::Status,
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_visible_reorder_rejects_non_permutation_same_length() {
|
||||
let mut view = ViewState::default();
|
||||
let before = view.order.clone();
|
||||
let hidden = *view
|
||||
.order
|
||||
.iter()
|
||||
.find(|c| **c != Column::Ip && !view.visible.contains(c))
|
||||
.expect("a hidden column exists by default");
|
||||
let mut disp = view.display_columns(); // Ip first, correct length
|
||||
disp[1] = hidden; // same length + Ip first, but no longer a permutation
|
||||
view.apply_visible_reorder(&disp);
|
||||
assert_eq!(view.order, before, "a same-length non-permutation must be ignored");
|
||||
}
|
||||
|
||||
/// Microbenchmark: the DEFAULT view (Ip ascending) at 5000 rows. The existing
|
||||
/// bench_view_pipeline overrides sort to Hashrate, so it never exercised the
|
||||
/// default path (previously a lexical string sort).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_view_pipeline_default_sort() {
|
||||
use std::time::Instant;
|
||||
let rows = synthetic_fleet(5000);
|
||||
let view = ViewState::default();
|
||||
let iters = 200u32;
|
||||
let t = Instant::now();
|
||||
let mut sink = 0usize;
|
||||
for _ in 0..iters {
|
||||
sink += view.view(&rows).len();
|
||||
}
|
||||
let per = t.elapsed() / iters;
|
||||
println!("bench_view_pipeline_default_sort: {:?}/op (sink={sink})", per);
|
||||
assert!(per.as_millis() < 60, "default (Ip) sort regressed: {per:?}/op");
|
||||
}
|
||||
|
||||
/// Microbenchmark: sort by every column once, at 5000 rows. Guards the
|
||||
/// decorate-sort-undecorate path (string columns must not re-allocate keys
|
||||
/// per comparison).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_sort_by_each_column() {
|
||||
use std::time::Instant;
|
||||
let rows = synthetic_fleet(5000);
|
||||
let iters = 10u32;
|
||||
let mut worst = std::time::Duration::ZERO;
|
||||
for &col in ALL_COLUMNS.iter() {
|
||||
let mut view = ViewState::default();
|
||||
view.sort = Some((col, false));
|
||||
let t = Instant::now();
|
||||
let mut sink = 0usize;
|
||||
for _ in 0..iters {
|
||||
sink += view.view(&rows).len();
|
||||
}
|
||||
let per = t.elapsed() / iters;
|
||||
if per > worst {
|
||||
worst = per;
|
||||
}
|
||||
assert!(per.as_millis() < 120, "{col:?} sort regressed: {per:?}/op (sink={sink})");
|
||||
}
|
||||
println!("bench_sort_by_each_column: worst column = {:?}/op", worst);
|
||||
}
|
||||
|
||||
/// Microbenchmark: filtered view (one selective predicate) at 5000 rows.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_view_pipeline_with_filter() {
|
||||
use std::time::Instant;
|
||||
let rows = synthetic_fleet(5000);
|
||||
let mut view = ViewState::default();
|
||||
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();
|
||||
let mut sink = 0usize;
|
||||
for _ in 0..iters {
|
||||
sink += view.view(&rows).len();
|
||||
}
|
||||
let per = t.elapsed() / iters;
|
||||
println!("bench_view_pipeline_with_filter: {sink} avg matches, {:?}/op", per);
|
||||
assert!(per.as_millis() < 60, "filtered view() regressed: {per:?}/op");
|
||||
}
|
||||
|
||||
/// Microbenchmark: cold-start fleet population via upsert_into (the O(n) scan
|
||||
/// per insert; documents the quadratic worst case).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_upsert_cold_start_population() {
|
||||
use std::time::Instant;
|
||||
let n = 3000u32;
|
||||
let fresh = synthetic_fleet(n);
|
||||
let t = Instant::now();
|
||||
let mut rows: Vec<MinerRow> = Vec::new();
|
||||
for r in fresh {
|
||||
r.upsert_into(&mut rows);
|
||||
}
|
||||
let elapsed = t.elapsed();
|
||||
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 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));
|
||||
}
|
||||
}
|
||||
|
||||
+235
-59
@@ -8,7 +8,9 @@ use futures_util::StreamExt;
|
||||
use std::collections::HashSet;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{channel, Receiver};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub enum ScanMsg {
|
||||
/// A new scan started: `total` addresses to probe, and the exact set of
|
||||
@@ -228,27 +230,51 @@ pub fn fake_scan_enabled() -> bool {
|
||||
/// tells the UI which addresses are in range (so out-of-range miners can be
|
||||
/// dropped), then streams identified miners plus progress updates. In fake-scan
|
||||
/// mode it streams the bench-fleet fixtures instead, needing no network.
|
||||
pub fn start_scan(lines: Vec<String>) -> Receiver<ScanMsg> {
|
||||
///
|
||||
/// The returned [`ScanHandle`] carries the message stream plus a cancel flag the
|
||||
/// background thread checks each iteration, so Stop / re-scan can end a scan
|
||||
/// promptly instead of leaving a thread probing dead hosts (each probe waits out
|
||||
/// an asic-rs per-host timeout).
|
||||
pub struct ScanHandle {
|
||||
pub rx: Receiver<ScanMsg>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl ScanHandle {
|
||||
/// Signal the scan thread to stop at its next loop iteration. Idempotent;
|
||||
/// dropping the handle's `rx` alone does NOT stop the thread.
|
||||
pub fn stop(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_scan(lines: Vec<String>) -> ScanHandle {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
|
||||
if fake_scan_enabled() {
|
||||
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();
|
||||
let _ = tx.send(ScanMsg::Started { total, targets });
|
||||
for (i, row) in rows.into_iter().enumerate() {
|
||||
if tx.send(ScanMsg::Row(row)).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(ScanMsg::Progress { done: i + 1, total, ip: String::new() });
|
||||
let thread_cancel = cancel.clone();
|
||||
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();
|
||||
let _ = tx.send(ScanMsg::Started { total, targets });
|
||||
for (i, row) in rows.into_iter().enumerate() {
|
||||
if thread_cancel.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(ScanMsg::Done("fixtures".into()));
|
||||
})
|
||||
.expect("spawn fake-scan thread");
|
||||
return rx;
|
||||
if tx.send(ScanMsg::Row(row)).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(ScanMsg::Progress { done: i + 1, total, ip: String::new() });
|
||||
}
|
||||
let _ = tx.send(ScanMsg::Done("fixtures".into()));
|
||||
});
|
||||
if let Err(e) = res {
|
||||
let _ = err_tx.send(ScanMsg::Failed(format!("spawn fake-scan thread: {e}")));
|
||||
}
|
||||
return ScanHandle { rx, cancel };
|
||||
}
|
||||
|
||||
// Resolve the target addresses up front so we can report total + membership.
|
||||
@@ -256,11 +282,11 @@ pub fn start_scan(lines: Vec<String>) -> Receiver<ScanMsg> {
|
||||
Ok(t) if !t.is_empty() => t,
|
||||
Ok(_) => {
|
||||
let _ = tx.send(ScanMsg::Failed("no addresses in the given ranges".into()));
|
||||
return rx;
|
||||
return ScanHandle { rx, cancel };
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = tx.send(ScanMsg::Failed(e));
|
||||
return rx;
|
||||
return ScanHandle { rx, cancel };
|
||||
}
|
||||
};
|
||||
let total = targets.len();
|
||||
@@ -268,49 +294,54 @@ pub fn start_scan(lines: Vec<String>) -> Receiver<ScanMsg> {
|
||||
let _ = tx.send(ScanMsg::Started { total, targets: target_set });
|
||||
let cidrs = targets_to_cidrs(&targets);
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("asic-rs-scan".into())
|
||||
.spawn(move || {
|
||||
let rt = match tokio::runtime::Runtime::new() {
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
let _ = tx.send(ScanMsg::Failed(format!("tokio runtime: {e}")));
|
||||
return;
|
||||
}
|
||||
};
|
||||
rt.block_on(async move {
|
||||
let mut factory = MinerFactory::new();
|
||||
for (ip, prefix) in &cidrs {
|
||||
factory = match factory.with_subnet(&format!("{ip}/{prefix}")) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let _ = tx.send(ScanMsg::Failed(format!("{ip}/{prefix}: {e}")));
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
// scan_stream_with_ip yields one item per probed address, so we
|
||||
// get accurate progress plus the responders.
|
||||
let mut stream = factory.scan_stream_with_ip();
|
||||
let mut done = 0usize;
|
||||
let step = (total / 100).max(1); // throttle progress messages
|
||||
while let Some((ip, miner)) = stream.next().await {
|
||||
done += 1;
|
||||
if let Some(miner) = miner {
|
||||
let row = to_row(&*miner).await;
|
||||
if tx.send(ScanMsg::Row(row)).is_err() {
|
||||
return; // UI gone
|
||||
}
|
||||
let thread_cancel = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let res = std::thread::Builder::new().name("asic-rs-scan".into()).spawn(move || {
|
||||
let rt = match tokio::runtime::Runtime::new() {
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
let _ = tx.send(ScanMsg::Failed(format!("tokio runtime: {e}")));
|
||||
return;
|
||||
}
|
||||
};
|
||||
rt.block_on(async move {
|
||||
let mut factory = MinerFactory::new();
|
||||
for (ip, prefix) in &cidrs {
|
||||
factory = match factory.with_subnet(&format!("{ip}/{prefix}")) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let _ = tx.send(ScanMsg::Failed(format!("{ip}/{prefix}: {e}")));
|
||||
return;
|
||||
}
|
||||
if done % step == 0 || done == total {
|
||||
let _ = tx.send(ScanMsg::Progress { done, total, ip: ip.to_string() });
|
||||
};
|
||||
}
|
||||
// scan_stream_with_ip yields one item per probed address, so we
|
||||
// get accurate progress plus the responders.
|
||||
let mut stream = factory.scan_stream_with_ip();
|
||||
let mut done = 0usize;
|
||||
let step = (total / 100).max(1); // throttle progress messages
|
||||
while let Some((ip, miner)) = stream.next().await {
|
||||
if thread_cancel.load(Ordering::Relaxed) {
|
||||
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
|
||||
}
|
||||
}
|
||||
let _ = tx.send(ScanMsg::Done(format!("{total} addresses")));
|
||||
});
|
||||
})
|
||||
.expect("spawn scan thread");
|
||||
rx
|
||||
if done % step == 0 || done == total {
|
||||
let _ = tx.send(ScanMsg::Progress { done, total, ip: ip.to_string() });
|
||||
}
|
||||
}
|
||||
let _ = tx.send(ScanMsg::Done(format!("{total} addresses")));
|
||||
});
|
||||
});
|
||||
if let Err(e) = res {
|
||||
let _ = err_tx.send(ScanMsg::Failed(format!("spawn scan thread: {e}")));
|
||||
}
|
||||
ScanHandle { rx, cancel }
|
||||
}
|
||||
|
||||
async fn to_row(miner: &dyn Miner) -> MinerRow {
|
||||
@@ -518,4 +549,149 @@ mod tests {
|
||||
covered.sort();
|
||||
assert_eq!(covered, ips);
|
||||
}
|
||||
|
||||
// ---- harness-driven additions (coverage) ----
|
||||
|
||||
#[test]
|
||||
fn parse_cidr_bare_and_rejections() {
|
||||
assert_eq!(parse_cidr("10.1.2.3"), Some((Ipv4Addr::new(10, 1, 2, 3), 32)));
|
||||
assert_eq!(parse_cidr("10.0.0.1/24"), Some((Ipv4Addr::new(10, 0, 0, 1), 24)));
|
||||
assert_eq!(parse_cidr("10.0.0.1/33"), None);
|
||||
assert_eq!(parse_cidr("10.0.0.1/abc"), None);
|
||||
assert_eq!(parse_cidr("bad/24"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefix_mask_boundaries() {
|
||||
assert_eq!(prefix_mask(0), 0);
|
||||
assert_eq!(prefix_mask(24), 0xFFFF_FF00);
|
||||
assert_eq!(prefix_mask(32), u32::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_line_single_host_cidr_slash_32() {
|
||||
assert_eq!(parse_line("10.1.2.3/32").unwrap(), vec![Ipv4Addr::new(10, 1, 2, 3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_line_empty_and_whitespace() {
|
||||
assert_eq!(parse_line("").unwrap(), Vec::<Ipv4Addr>::new());
|
||||
assert_eq!(parse_line(" ").unwrap(), Vec::<Ipv4Addr>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_line_short_range_single_address_and_reversed() {
|
||||
assert_eq!(parse_line("10.253.1.5-5").unwrap(), vec![Ipv4Addr::new(10, 253, 1, 5)]);
|
||||
// short form whose end octet precedes the start is an inverted range.
|
||||
assert!(parse_line("10.253.1.200-50").is_err());
|
||||
assert!(parse_line("10.253.1.3-300").is_err()); // 300 is not a u8
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_targets_aggregate_cap_and_errors() {
|
||||
// Each /13 (524288) is under the cap; together they exceed 1,000,000.
|
||||
let over = parse_targets(&["10.0.0.0/13".into(), "11.0.0.0/13".into()]);
|
||||
assert!(over.is_err(), "aggregate over MAX_ADDRS must be rejected");
|
||||
// One bad line among good ones propagates.
|
||||
assert!(parse_targets(&["10.0.0.1".into(), "not-an-ip".into()]).is_err());
|
||||
// Empty input is an empty (Ok) set.
|
||||
assert!(parse_targets(&[]).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_ranges_empty_ok_and_bad() {
|
||||
assert!(validate_ranges(&[]).is_err()); // no addresses
|
||||
assert!(validate_ranges(&["10.0.0.0/30".into()]).is_ok());
|
||||
assert!(validate_ranges(&["garbage".into()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_to_cidrs_splits_noncontiguous_runs() {
|
||||
let cidrs = targets_to_cidrs(&[Ipv4Addr::new(10, 0, 0, 5), Ipv4Addr::new(10, 0, 0, 10)]);
|
||||
assert_eq!(cidrs, vec![(Ipv4Addr::new(10, 0, 0, 5), 32), (Ipv4Addr::new(10, 0, 0, 10), 32)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_secs_round_trip_and_defaults() {
|
||||
// config_path() reads $HOME; point it at a private temp dir. HOME is
|
||||
// process-global, so this stays one test and restores HOME afterward.
|
||||
let prev = std::env::var_os("HOME");
|
||||
let dir = std::env::temp_dir().join(format!("alkane-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_auto_secs(), DEFAULT_AUTO_SECS, "missing file -> default");
|
||||
save_auto_secs(150).unwrap();
|
||||
assert_eq!(load_auto_secs(), 150, "round-trip");
|
||||
std::fs::write(config_path(AUTO_FILE), "not-a-number").unwrap();
|
||||
assert_eq!(load_auto_secs(), DEFAULT_AUTO_SECS, "malformed -> default");
|
||||
std::fs::write(config_path(AUTO_FILE), " 42 \n").unwrap();
|
||||
assert_eq!(load_auto_secs(), 42, "whitespace tolerated");
|
||||
|
||||
match prev {
|
||||
Some(v) => std::env::set_var("HOME", v),
|
||||
None => std::env::remove_var("HOME"),
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ---- microbenchmarks (perf-regression gates; run with --ignored) ----
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_parse_line_near_max_addrs() {
|
||||
use std::time::Instant;
|
||||
let start = Ipv4Addr::new(10, 0, 0, 0);
|
||||
let end = Ipv4Addr::from(u32::from(start) + (MAX_ADDRS as u32 - 2));
|
||||
let line = format!("{start}-{end}");
|
||||
let iters = 5u32;
|
||||
let t = Instant::now();
|
||||
let mut sink = 0usize;
|
||||
for _ in 0..iters {
|
||||
sink += parse_line(&line).unwrap().len();
|
||||
}
|
||||
let per = t.elapsed() / iters;
|
||||
println!("bench_parse_line_near_max_addrs: {sink} addrs, {:?}/op", per);
|
||||
assert!(per.as_millis() < 400, "parse_line near MAX_ADDRS regressed: {per:?}/op");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_parse_targets_many_ranges_near_cap() {
|
||||
use std::time::Instant;
|
||||
let mut lines = Vec::new();
|
||||
let mut total = 0u64;
|
||||
let mut b = 0u32;
|
||||
while total + 65536 < MAX_ADDRS && b < 200 {
|
||||
lines.push(format!("10.{b}.0.0/16"));
|
||||
total += 65536;
|
||||
b += 1;
|
||||
}
|
||||
let iters = 5u32;
|
||||
let t = Instant::now();
|
||||
let mut sink = 0usize;
|
||||
for _ in 0..iters {
|
||||
sink += parse_targets(&lines).unwrap().len();
|
||||
}
|
||||
let per = t.elapsed() / iters;
|
||||
println!("bench_parse_targets_many_ranges_near_cap: {} lines, {sink} addrs, {:?}/op", lines.len(), per);
|
||||
assert!(per.as_millis() < 800, "parse_targets regressed: {per:?}/op");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_targets_to_cidrs_large_range() {
|
||||
use std::time::Instant;
|
||||
let ips = parse_line("10.0.0.1-10.7.255.254").unwrap(); // ~524k addrs, odd start
|
||||
let iters = 20u32;
|
||||
let t = Instant::now();
|
||||
let mut sink = 0usize;
|
||||
for _ in 0..iters {
|
||||
sink += targets_to_cidrs(&ips).len();
|
||||
}
|
||||
let per = t.elapsed() / iters;
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
+505
-118
@@ -4,8 +4,7 @@
|
||||
use crate::model::*;
|
||||
use crate::scan::{self, ScanMsg};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use wx_rs::{Widget, WxEvent, WxEventKind, sizer_flags as sf};
|
||||
|
||||
pub const ID_RANGES: i32 = 101;
|
||||
@@ -25,7 +24,18 @@ const ID_FILTER_RESET: i32 = 210;
|
||||
// column index (and the None equivalent). 100 columns of headroom each.
|
||||
const ID_FILTER_ALL_BASE: i32 = 300;
|
||||
const ID_FILTER_NONE_BASE: i32 = 500;
|
||||
// Right-click context-menu item ids.
|
||||
const ID_CTX_OPEN: i32 = 720;
|
||||
const ID_CTX_SELALL: i32 = 721;
|
||||
const ID_CTX_CLEAR: i32 = 722;
|
||||
// Filter dialog: the column-selector dropdown + the comparator dropdown.
|
||||
const ID_FILTER_COL: i32 = 730;
|
||||
const ID_FILTER_OP: i32 = 731;
|
||||
const TIMER_SCAN: i32 = 1;
|
||||
// Deferred-rebuild ids: run a rebuild from outside the triggering widget's own
|
||||
// event (destroying a control mid-event is unsafe). See `wx_rs::call_after`.
|
||||
const DEFER_TABLE: i32 = 1;
|
||||
const DEFER_FILTER: i32 = 2;
|
||||
|
||||
/// Theme-aware palette for the KPI cards. Health is encoded in colour so a red
|
||||
/// "Not hashing" or amber "Slow" draws the eye immediately. Colours derive from
|
||||
@@ -50,6 +60,15 @@ fn nudge(c: (u8, u8, u8), d: i32) -> (u8, u8, u8) {
|
||||
(f(c.0), f(c.1), f(c.2))
|
||||
}
|
||||
|
||||
/// Format a filter's numeric bound without a trailing ".0" for whole numbers.
|
||||
fn fmt_num(v: f64) -> String {
|
||||
if v.is_finite() && v == v.trunc() && v.abs() < 1e15 {
|
||||
format!("{}", v as i64)
|
||||
} else {
|
||||
format!("{v}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Short mm:ss-ish duration for the rescan countdown ("4m 12s", "45s").
|
||||
fn fmt_secs(s: u64) -> String {
|
||||
if s >= 60 {
|
||||
@@ -59,6 +78,40 @@ fn fmt_secs(s: u64) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which palette colour a KPI card's value uses, so the card can be re-themed
|
||||
/// when the system switches light/dark while the app is open.
|
||||
#[derive(Clone, Copy)]
|
||||
enum ColorKind {
|
||||
Neutral,
|
||||
Green,
|
||||
Amber,
|
||||
Red,
|
||||
Accent,
|
||||
}
|
||||
|
||||
fn kind_color(pal: &Palette, k: ColorKind) -> (u8, u8, u8) {
|
||||
match k {
|
||||
ColorKind::Neutral => pal.neutral,
|
||||
ColorKind::Green => pal.green,
|
||||
ColorKind::Amber => pal.amber,
|
||||
ColorKind::Red => pal.red,
|
||||
ColorKind::Accent => pal.accent,
|
||||
}
|
||||
}
|
||||
|
||||
/// A miner row's text colour, by status: green = hashing, amber = slow, muted
|
||||
/// grey = not hashing. This both conveys status and separates rows visually
|
||||
/// (GTK's native zebra/alt-row support is unreliable and fights selection).
|
||||
fn status_color(pal: &Palette, r: &MinerRow) -> (u8, u8, u8) {
|
||||
if r.slow {
|
||||
pal.amber
|
||||
} else if r.is_mining {
|
||||
pal.green
|
||||
} else {
|
||||
pal.label
|
||||
}
|
||||
}
|
||||
|
||||
fn palette() -> Palette {
|
||||
let win = wx_rs::system_color(0); // window background
|
||||
let text = wx_rs::system_color(1); // window text
|
||||
@@ -90,7 +143,7 @@ pub struct App {
|
||||
pub table: Option<Widget>,
|
||||
table_parent: Widget,
|
||||
root_sizer: Widget,
|
||||
pub scan_rx: Option<Receiver<ScanMsg>>,
|
||||
pub scan: Option<scan::ScanHandle>,
|
||||
pub scanning: bool,
|
||||
scan_total: usize,
|
||||
target_ips: HashSet<String>,
|
||||
@@ -101,23 +154,36 @@ pub struct App {
|
||||
// selection (replaces the old checkbox column), tracked by IP so it
|
||||
// survives table refreshes during a scan.
|
||||
selected_ips: HashSet<String>,
|
||||
alt_row: (u8, u8, u8),
|
||||
// current theme palette + the KPI cards (panel, value, caption, colour role)
|
||||
// so both can be repainted when the system light/dark theme changes.
|
||||
pal: Palette,
|
||||
kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)>,
|
||||
// A context menu built on right-click, popped up outside the App borrow.
|
||||
pending_popup: Option<(Widget, Widget)>,
|
||||
ranges_dialog: Widget,
|
||||
ranges_edit: Widget,
|
||||
ranges_auto: Widget,
|
||||
columns_dialog: Widget,
|
||||
columns_list: Widget,
|
||||
// Filter dialog (Excel-style, one column at a time via a dropdown).
|
||||
filter_dialog: Widget,
|
||||
filter_lists: Vec<(Column, Widget)>,
|
||||
filter_col_choice: Widget, // which column to filter
|
||||
filter_controls: Widget, // panel rebuilt per column with its criterion controls
|
||||
filter_op: Widget, // comparator dropdown
|
||||
filter_values: Widget, // value checklist (text "is any of")
|
||||
filter_values_data: Vec<String>, // the checklist's real values, by index
|
||||
filter_text: Widget, // text input (text predicates)
|
||||
filter_num_a: Widget, // numeric input a
|
||||
filter_num_b: Widget, // numeric input b (Between)
|
||||
filter_cols: Vec<Column>, // columns offered in the dropdown, in order
|
||||
filter_cur: usize, // index into filter_cols currently edited
|
||||
filter_active_op: i32, // the op index the visible controls were built for
|
||||
filter_pending_op: Option<i32>, // op to rebuild for, deferred off the choice event
|
||||
filter_working: HashMap<Column, ColFilter>, // edits, committed on Apply
|
||||
}
|
||||
|
||||
pub fn build(frame: Widget) -> App {
|
||||
let pal = palette();
|
||||
// Subtle alternating-row tint derived from the theme. GTK's native dataview
|
||||
// ignores SetAlternateRowColour, so also install an app-wide zebra CSS.
|
||||
let win = wx_rs::system_color(0);
|
||||
let alt_row = if luminance(win) < 128.0 { nudge(win, 12) } else { nudge(win, -12) };
|
||||
wx_rs::apply_zebra_css(alt_row.0, alt_row.1, alt_row.2);
|
||||
let panel = Widget::panel(frame);
|
||||
let root = Widget::box_sizer(true);
|
||||
|
||||
@@ -125,14 +191,16 @@ pub fn build(frame: Widget) -> App {
|
||||
// label. Health KPIs are colour-coded (green/amber/red); hashrate uses the
|
||||
// accent colour so totals stand apart from counts.
|
||||
let kpi_row = Widget::box_sizer(false);
|
||||
let mk_card = |label: &str, value_color: (u8, u8, u8)| -> Widget {
|
||||
let mut kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)> = Vec::new();
|
||||
let mut mk_card = |label: &str, kind: ColorKind| -> Widget {
|
||||
let vc = kind_color(&pal, kind);
|
||||
let card = Widget::panel(panel);
|
||||
card.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
|
||||
let cs = Widget::box_sizer(true);
|
||||
let value = Widget::static_text(card, "0");
|
||||
value.set_font_size(19);
|
||||
value.set_bold();
|
||||
value.set_fg(value_color.0, value_color.1, value_color.2);
|
||||
value.set_fg(vc.0, vc.1, vc.2);
|
||||
value.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
|
||||
let lbl = Widget::static_text(card, label);
|
||||
lbl.set_font_size(9);
|
||||
@@ -142,14 +210,16 @@ pub fn build(frame: Widget) -> App {
|
||||
cs.add(lbl, 0, sf::BORDER_LEFT | sf::BORDER_BOTTOM | sf::BORDER_RIGHT, 12);
|
||||
cs.set_sizer_on(card);
|
||||
kpi_row.add(card, 1, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
kpi_cards.push((card, value, lbl, kind));
|
||||
value
|
||||
};
|
||||
let kpi_total = mk_card("Total", pal.neutral);
|
||||
let kpi_hashing = mk_card("Hashing", pal.green);
|
||||
let kpi_slow = mk_card("Slow", pal.amber);
|
||||
let kpi_not = mk_card("Not hashing", pal.red);
|
||||
let kpi_hashrate = mk_card("Hashrate", pal.accent);
|
||||
let kpi_power = mk_card("Est. power", pal.neutral);
|
||||
let kpi_total = mk_card("Total", ColorKind::Neutral);
|
||||
let kpi_hashing = mk_card("Hashing", ColorKind::Green);
|
||||
let kpi_slow = mk_card("Slow", ColorKind::Amber);
|
||||
let kpi_not = mk_card("Not hashing", ColorKind::Red);
|
||||
let kpi_hashrate = mk_card("Hashrate", ColorKind::Accent);
|
||||
let kpi_power = mk_card("Est. power", ColorKind::Neutral);
|
||||
drop(mk_card);
|
||||
root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
|
||||
// Controls row: scan-ranges + play/pause/stop on the left; Filter / Columns
|
||||
@@ -158,12 +228,14 @@ pub fn build(frame: Widget) -> App {
|
||||
let ranges_btn = Widget::button(panel, "Scan ranges", ID_RANGES);
|
||||
ctl.add(ranges_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
ctl.add_spacer(8);
|
||||
let play_btn = Widget::button(panel, "Play", ID_PLAY);
|
||||
ctl.add(play_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
let pause_btn = Widget::button(panel, "Pause", ID_PAUSE);
|
||||
ctl.add(pause_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
let stop_btn = Widget::button(panel, "Stop", ID_STOP);
|
||||
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
// Play / pause / stop as coloured media icons (green / amber / red). Vivid
|
||||
// fixed colours read well on both light and dark themes.
|
||||
let play_btn = Widget::media_button(panel, ID_PLAY, 0, (56, 190, 108));
|
||||
ctl.add(play_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
let pause_btn = Widget::media_button(panel, ID_PAUSE, 1, (240, 172, 40));
|
||||
ctl.add(pause_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
let stop_btn = Widget::media_button(panel, ID_STOP, 2, (226, 72, 60));
|
||||
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
ctl.add_stretch(1);
|
||||
let filter_btn = Widget::button(panel, "Filter", ID_FILTER);
|
||||
ctl.add(filter_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
@@ -189,6 +261,9 @@ pub fn build(frame: Widget) -> App {
|
||||
wx_rs::create_status_bar();
|
||||
wx_rs::set_status_text("starting scan...");
|
||||
|
||||
// Repaint custom-coloured widgets when the OS switches light/dark.
|
||||
frame.bind_sys_colour();
|
||||
|
||||
let ranges = scan::load_ranges();
|
||||
let mut app = App {
|
||||
rows: Vec::new(),
|
||||
@@ -204,7 +279,7 @@ pub fn build(frame: Widget) -> App {
|
||||
table: None,
|
||||
table_parent,
|
||||
root_sizer: root,
|
||||
scan_rx: Some(scan::start_scan(ranges.clone())),
|
||||
scan: Some(scan::start_scan(ranges.clone())),
|
||||
scanning: true,
|
||||
scan_total: 0,
|
||||
target_ips: HashSet::new(),
|
||||
@@ -212,14 +287,28 @@ pub fn build(frame: Widget) -> App {
|
||||
auto_secs: scan::load_auto_secs(),
|
||||
countdown: 0,
|
||||
selected_ips: HashSet::new(),
|
||||
alt_row,
|
||||
pal,
|
||||
kpi_cards,
|
||||
pending_popup: None,
|
||||
ranges_dialog: frame,
|
||||
ranges_edit: frame,
|
||||
ranges_auto: frame,
|
||||
columns_dialog: frame,
|
||||
columns_list: frame,
|
||||
filter_dialog: frame,
|
||||
filter_lists: Vec::new(),
|
||||
filter_col_choice: frame,
|
||||
filter_controls: frame,
|
||||
filter_op: frame,
|
||||
filter_values: frame,
|
||||
filter_values_data: Vec::new(),
|
||||
filter_text: frame,
|
||||
filter_num_a: frame,
|
||||
filter_num_b: frame,
|
||||
filter_cols: Vec::new(),
|
||||
filter_cur: 0,
|
||||
filter_active_op: 0,
|
||||
filter_pending_op: None,
|
||||
filter_working: HashMap::new(),
|
||||
};
|
||||
app.rebuild_table();
|
||||
Widget::timer(TIMER_SCAN, 1000);
|
||||
@@ -250,7 +339,6 @@ impl App {
|
||||
}
|
||||
t.dvlc_append_text_col(&title, c.width(), !fixed);
|
||||
}
|
||||
t.dvlc_set_alt_row_color(self.alt_row.0, self.alt_row.1, self.alt_row.2);
|
||||
// Add the table to the root sizer (proportion 1 => fills the area under
|
||||
// the KPI + controls rows) and re-run the panel's layout so it is
|
||||
// positioned, not left floating at (0,0).
|
||||
@@ -271,6 +359,10 @@ impl App {
|
||||
let refs: Vec<&str> = cells.iter().map(|s| s.as_str()).collect();
|
||||
t.dvlc_append_row(&refs);
|
||||
}
|
||||
// Colour each row's text by status (also separates rows visually).
|
||||
for (disp, &ri) in self.view_idx.iter().enumerate() {
|
||||
t.dvlc_set_row_color(disp, Some(status_color(&self.pal, &self.rows[ri])));
|
||||
}
|
||||
// Re-apply the selection (a refresh clears the control's selection).
|
||||
let sel: Vec<usize> = self
|
||||
.view_idx
|
||||
@@ -295,11 +387,83 @@ impl App {
|
||||
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
|
||||
}
|
||||
|
||||
/// Re-apply the theme palette to the KPI cards and table rows after the OS
|
||||
/// switches light/dark while the app is open.
|
||||
fn repaint_theme(&mut self) {
|
||||
self.pal = palette();
|
||||
for (card, value, caption, kind) in &self.kpi_cards {
|
||||
let vc = kind_color(&self.pal, *kind);
|
||||
card.set_bg(self.pal.card_bg.0, self.pal.card_bg.1, self.pal.card_bg.2);
|
||||
value.set_bg(self.pal.card_bg.0, self.pal.card_bg.1, self.pal.card_bg.2);
|
||||
value.set_fg(vc.0, vc.1, vc.2);
|
||||
caption.set_bg(self.pal.card_bg.0, self.pal.card_bg.1, self.pal.card_bg.2);
|
||||
caption.set_fg(self.pal.label.0, self.pal.label.1, self.pal.label.2);
|
||||
}
|
||||
self.fill_rows(); // re-colour rows with the new palette
|
||||
self.table_parent.layout();
|
||||
}
|
||||
|
||||
/// Right-click: build a context menu of actions for the current selection.
|
||||
/// The menu is popped up outside the App borrow (see `dispatch`), because
|
||||
/// `popup_menu` runs a nested event loop that re-enters us.
|
||||
fn show_context_menu(&mut self) {
|
||||
let Some(t) = self.table else { return };
|
||||
let n = self.selected_ips.len();
|
||||
let menu = Widget::menu_new();
|
||||
if n >= 1 {
|
||||
let open = if n == 1 { "Open in browser".to_string() } else { format!("Open {n} miners in browser") };
|
||||
menu.menu_append(ID_CTX_OPEN, &open);
|
||||
menu.menu_append_separator();
|
||||
}
|
||||
menu.menu_append(ID_CTX_SELALL, "Select all");
|
||||
if n >= 1 {
|
||||
menu.menu_append(ID_CTX_CLEAR, &format!("Clear selection ({n})"));
|
||||
}
|
||||
self.pending_popup = Some((t, menu));
|
||||
}
|
||||
|
||||
fn take_pending_popup(&mut self) -> Option<(Widget, Widget)> {
|
||||
self.pending_popup.take()
|
||||
}
|
||||
|
||||
fn on_menu_item(&mut self, id: i32) {
|
||||
match id {
|
||||
ID_CTX_OPEN => {
|
||||
let ips: Vec<String> = self
|
||||
.rows
|
||||
.iter()
|
||||
.filter(|r| !r.ip.is_empty() && self.selected_ips.contains(&r.ip))
|
||||
.map(|r| r.ip.clone())
|
||||
.collect();
|
||||
for ip in ips {
|
||||
wx_rs::launch_browser(&format!("http://{ip}"));
|
||||
}
|
||||
}
|
||||
ID_CTX_SELALL => {
|
||||
let all: Vec<usize> = (0..self.view_idx.len()).collect();
|
||||
if let Some(t) = self.table {
|
||||
t.dvlc_select_rows(&all);
|
||||
}
|
||||
self.on_selection_changed();
|
||||
}
|
||||
ID_CTX_CLEAR => {
|
||||
self.selected_ips.clear();
|
||||
for r in &mut self.rows {
|
||||
r.selected = false;
|
||||
}
|
||||
if let Some(t) = self.table {
|
||||
t.dvlc_select_rows(&[]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn drain_scan(&mut self) {
|
||||
let Some(rx) = &self.scan_rx else { return };
|
||||
let Some(handle) = &self.scan else { return };
|
||||
let mut changed = false;
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
match handle.rx.try_recv() {
|
||||
Ok(ScanMsg::Started { total, targets }) => {
|
||||
// Drop miners no longer in the target range.
|
||||
let before = self.rows.len();
|
||||
@@ -359,7 +523,7 @@ impl App {
|
||||
self.table_parent.layout();
|
||||
self.countdown = if self.playing { self.auto_secs } else { 0 };
|
||||
}
|
||||
self.scan_rx = None;
|
||||
self.scan = None;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -396,11 +560,21 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a fresh scan of the saved ranges.
|
||||
fn start_new_scan(&mut self) {
|
||||
self.scan_rx = Some(scan::start_scan(scan::load_ranges()));
|
||||
/// Cancel any in-flight scan, then start a fresh one over `lines`. Signalling
|
||||
/// the old scan to stop before replacing it prevents two scan threads (and
|
||||
/// two tokio runtimes) probing the network at once.
|
||||
fn begin_scan(&mut self, lines: Vec<String>) {
|
||||
if let Some(old) = self.scan.take() {
|
||||
old.stop();
|
||||
}
|
||||
self.scan = Some(scan::start_scan(lines));
|
||||
self.scanning = true;
|
||||
self.countdown = 0;
|
||||
}
|
||||
|
||||
/// Start a fresh scan of the saved ranges.
|
||||
fn start_new_scan(&mut self) {
|
||||
self.begin_scan(scan::load_ranges());
|
||||
wx_rs::set_status_text("scanning...");
|
||||
}
|
||||
|
||||
@@ -483,6 +657,12 @@ impl App {
|
||||
}
|
||||
}
|
||||
self.view.apply_visible_reorder(&new_visible);
|
||||
// Rebuild so the control's column creation order matches the new display
|
||||
// order again (fill_rows/header_click/update_headers assume creation
|
||||
// order == display_columns()). Deferred: rebuild_table destroys the very
|
||||
// wxDataViewCtrl now delivering this reorder event, which is unsafe to do
|
||||
// from inside the event -- run it after the event unwinds.
|
||||
wx_rs::call_after(DEFER_TABLE);
|
||||
}
|
||||
|
||||
/// Build (but do not show) the ranges editor. The caller shows it modally
|
||||
@@ -501,7 +681,7 @@ impl App {
|
||||
root.add(edit, 1, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
// Auto-rescan interval (seconds; 0 = off).
|
||||
let auto_row = Widget::box_sizer(false);
|
||||
let auto_lbl = Widget::static_text(dlg, "Auto-rescan every (seconds, 0 = off):");
|
||||
let auto_lbl = Widget::static_text(dlg, "Rescan (s):");
|
||||
auto_row.add(auto_lbl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
|
||||
let auto_edit = Widget::text_ctrl(dlg, false);
|
||||
auto_edit.set_value(&self.auto_secs.to_string());
|
||||
@@ -543,9 +723,7 @@ impl App {
|
||||
let _ = scan::save_auto_secs(secs);
|
||||
}
|
||||
let _ = scan::save_ranges(&lines);
|
||||
self.scan_rx = Some(scan::start_scan(lines.clone()));
|
||||
self.scanning = true;
|
||||
self.countdown = 0;
|
||||
self.begin_scan(lines);
|
||||
wx_rs::set_status_text("scanning...");
|
||||
self.ranges_dialog.close(1);
|
||||
}
|
||||
@@ -623,103 +801,298 @@ impl App {
|
||||
self.rebuild_table();
|
||||
}
|
||||
|
||||
/// Build (but do not show) the Excel-style filter panel. Every visible
|
||||
/// column with more than one distinct value gets a per-column value
|
||||
/// checklist with All / None controls; filters AND across columns and OR
|
||||
/// within a column. Blank cells show as "(blank)".
|
||||
/// Operator labels offered for a column, by type.
|
||||
fn filter_ops(col: Column) -> &'static [&'static str] {
|
||||
if col.is_numeric() {
|
||||
&["between", "=", "!=", ">", ">=", "<", "<="]
|
||||
} else {
|
||||
&["is any of", "contains", "does not contain", "begins with", "ends with", "equals"]
|
||||
}
|
||||
}
|
||||
|
||||
/// The operator index that matches an existing filter (for prefilling).
|
||||
fn filter_op_index(existing: Option<&ColFilter>) -> i32 {
|
||||
match existing {
|
||||
Some(ColFilter::Values(_)) => 0,
|
||||
Some(ColFilter::Text { op, .. }) => match op {
|
||||
TextOp::Contains => 1,
|
||||
TextOp::NotContains => 2,
|
||||
TextOp::BeginsWith => 3,
|
||||
TextOp::EndsWith => 4,
|
||||
TextOp::Equals => 5,
|
||||
},
|
||||
Some(ColFilter::Num { op, .. }) => match op {
|
||||
NumOp::Between => 0,
|
||||
NumOp::Eq => 1,
|
||||
NumOp::Ne => 2,
|
||||
NumOp::Gt => 3,
|
||||
NumOp::Ge => 4,
|
||||
NumOp::Lt => 5,
|
||||
NumOp::Le => 6,
|
||||
},
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build (but do not show) the filter dialog: an Excel-style, one-column-at-
|
||||
/// a-time filter. A dropdown at the top-left picks the column; the controls
|
||||
/// below adapt to its type -- numeric columns get a comparator
|
||||
/// (between / = / != / > / >= / < / <=) with one or two number inputs; text
|
||||
/// columns get a value checklist ("is any of") or a text predicate (contains
|
||||
/// / does not contain / begins with / ends with / equals). Filters AND across
|
||||
/// columns; edits are held in a working copy and committed on Apply.
|
||||
fn build_filter_dialog(&mut self) -> Widget {
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, "Filter");
|
||||
let root = Widget::box_sizer(true);
|
||||
let content = Widget::box_sizer(false); // side-by-side column filters
|
||||
let mut lists = Vec::new();
|
||||
for c in self.view.display_columns() {
|
||||
// Value checklists only make sense for categorical columns; skip the
|
||||
// continuous numeric metrics.
|
||||
if c.is_numeric() {
|
||||
continue;
|
||||
}
|
||||
let mut values: Vec<String> = self.rows.iter().map(|r| c.cell(r)).collect();
|
||||
values.sort();
|
||||
values.dedup();
|
||||
if values.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let idx = lists.len() as i32;
|
||||
let colbox = Widget::box_sizer(true);
|
||||
let head = Widget::box_sizer(false);
|
||||
let lbl = Widget::static_text(dlg, c.title());
|
||||
lbl.set_bold();
|
||||
head.add(lbl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
head.add(Widget::button(dlg, "All", ID_FILTER_ALL_BASE + idx), 0, sf::BORDER_ALL, 1);
|
||||
head.add(Widget::button(dlg, "None", ID_FILTER_NONE_BASE + idx), 0, sf::BORDER_ALL, 1);
|
||||
colbox.add_sizer(head, 0, sf::EXPAND | sf::BORDER_ALL, 2);
|
||||
let lst = Widget::check_list_box(dlg);
|
||||
lst.set_min_size(140, 220); // so Fit gives the checklist real space
|
||||
let current: Option<HashSet<String>> = self.view.filters.get(&c).cloned();
|
||||
for v in &values {
|
||||
let shown = if v.is_empty() { "(blank)" } else { v.as_str() };
|
||||
lst.clb_append(shown);
|
||||
let checked = match ¤t {
|
||||
Some(allowed) => allowed.contains(v),
|
||||
None => true,
|
||||
};
|
||||
lst.clb_set_checked(lst.clb_count() - 1, checked);
|
||||
}
|
||||
colbox.add(lst, 1, sf::EXPAND | sf::BORDER_ALL, 2);
|
||||
content.add_sizer(colbox, 1, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
lists.push((c, lst));
|
||||
|
||||
self.filter_cols = self.view.display_columns();
|
||||
self.filter_working = self.view.filters.clone();
|
||||
self.filter_cur = 0;
|
||||
|
||||
let top = Widget::box_sizer(false);
|
||||
top.add(Widget::static_text(dlg, "Column:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
let col_choice = Widget::choice(dlg, ID_FILTER_COL);
|
||||
for c in &self.filter_cols {
|
||||
col_choice.choice_append(c.title());
|
||||
}
|
||||
if lists.is_empty() {
|
||||
let lbl = Widget::static_text(dlg, "Nothing to filter yet - run a scan first.");
|
||||
content.add(lbl, 0, sf::BORDER_ALL, 8);
|
||||
}
|
||||
root.add_sizer(content, 1, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
col_choice.choice_set_selection(0);
|
||||
top.add(col_choice, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
root.add_sizer(top, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
self.filter_col_choice = col_choice;
|
||||
|
||||
// The criterion controls live in this panel, rebuilt on column/op change.
|
||||
let controls = Widget::panel(dlg);
|
||||
controls.set_min_size(380, 250);
|
||||
root.add(controls, 1, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
self.filter_controls = controls;
|
||||
|
||||
let btns = Widget::box_sizer(false);
|
||||
btns.add_stretch(1);
|
||||
btns.add(Widget::button(dlg, "Apply", ID_FILTER_OK), 0, sf::BORDER_ALL, 6);
|
||||
btns.add(Widget::button(dlg, "Reset", ID_FILTER_RESET), 0, sf::BORDER_ALL, 6);
|
||||
btns.add(Widget::button(dlg, "Cancel", ID_FILTER_CANCEL), 0, sf::BORDER_ALL, 6);
|
||||
root.add_sizer(btns, 0, sf::BORDER_ALL, 6);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
// Size the dialog to fit however many category columns there are.
|
||||
dlg.set_min_size(460, 400);
|
||||
dlg.fit(dlg);
|
||||
self.filter_dialog = dlg;
|
||||
self.filter_lists = lists;
|
||||
|
||||
self.build_filter_controls(None);
|
||||
dlg
|
||||
}
|
||||
|
||||
/// Check or uncheck every value in one column's list (0-based index into
|
||||
/// `filter_lists`).
|
||||
fn filter_check_all(&self, idx: usize, checked: bool) {
|
||||
if let Some((_c, lst)) = self.filter_lists.get(idx) {
|
||||
for i in 0..lst.clb_count() {
|
||||
lst.clb_set_checked(i, checked);
|
||||
/// Rebuild the criterion controls for the current column (`filter_cur`). `op`
|
||||
/// picks the operator; `None` derives it from the working filter (or 0).
|
||||
fn build_filter_controls(&mut self, op: Option<i32>) {
|
||||
let col = self.filter_cols[self.filter_cur];
|
||||
let panel = self.filter_controls;
|
||||
panel.destroy_children();
|
||||
let ops = Self::filter_ops(col);
|
||||
let existing = self.filter_working.get(&col).cloned();
|
||||
let op_idx = op
|
||||
.unwrap_or_else(|| Self::filter_op_index(existing.as_ref()))
|
||||
.clamp(0, ops.len() as i32 - 1);
|
||||
self.filter_active_op = op_idx;
|
||||
|
||||
let cs = Widget::box_sizer(true);
|
||||
let oprow = Widget::box_sizer(false);
|
||||
oprow.add(Widget::static_text(panel, "Keep rows where value is"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
let op_choice = Widget::choice(panel, ID_FILTER_OP);
|
||||
for o in ops {
|
||||
op_choice.choice_append(o);
|
||||
}
|
||||
op_choice.choice_set_selection(op_idx);
|
||||
oprow.add(op_choice, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
cs.add_sizer(oprow, 0, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
self.filter_op = op_choice;
|
||||
// Unused input handles point at the panel and are never read (commit
|
||||
// dispatches on column type + active op).
|
||||
self.filter_values = panel;
|
||||
self.filter_values_data.clear();
|
||||
self.filter_text = panel;
|
||||
self.filter_num_a = panel;
|
||||
self.filter_num_b = panel;
|
||||
|
||||
if col.is_numeric() {
|
||||
let row = Widget::box_sizer(false);
|
||||
let a = Widget::text_ctrl(panel, false);
|
||||
a.set_min_size(120, -1);
|
||||
row.add(a, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
self.filter_num_a = a;
|
||||
if op_idx == 0 {
|
||||
row.add(Widget::static_text(panel, "and"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
let b = Widget::text_ctrl(panel, false);
|
||||
b.set_min_size(120, -1);
|
||||
row.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4);
|
||||
self.filter_num_b = b;
|
||||
}
|
||||
cs.add_sizer(row, 0, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
if let Some(ColFilter::Num { a: wa, b: wb, .. }) = &existing {
|
||||
self.filter_num_a.set_value(&fmt_num(*wa));
|
||||
if op_idx == 0 {
|
||||
self.filter_num_b.set_value(&fmt_num(*wb));
|
||||
}
|
||||
}
|
||||
} else if op_idx == 0 {
|
||||
let head = Widget::box_sizer(false);
|
||||
head.add(Widget::button(panel, "All", ID_FILTER_ALL_BASE), 0, sf::BORDER_ALL, 2);
|
||||
head.add(Widget::button(panel, "None", ID_FILTER_NONE_BASE), 0, sf::BORDER_ALL, 2);
|
||||
cs.add_sizer(head, 0, sf::BORDER_ALL, 2);
|
||||
let clb = Widget::check_list_box(panel);
|
||||
clb.set_min_size(340, 180);
|
||||
let mut values: Vec<String> = self.rows.iter().map(|r| col.cell(r)).collect();
|
||||
values.sort();
|
||||
values.dedup();
|
||||
let checked_set = match &existing {
|
||||
Some(ColFilter::Values(set)) => Some(set.clone()),
|
||||
_ => None,
|
||||
};
|
||||
for v in &values {
|
||||
let shown = if v.is_empty() { "(blank)" } else { v.as_str() };
|
||||
clb.clb_append(shown);
|
||||
let checked = match &checked_set {
|
||||
Some(s) => s.contains(v),
|
||||
None => true,
|
||||
};
|
||||
clb.clb_set_checked(clb.clb_count() - 1, checked);
|
||||
}
|
||||
cs.add(clb, 1, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
self.filter_values = clb;
|
||||
self.filter_values_data = values; // real values, indexed like the checklist
|
||||
} else {
|
||||
let inp = Widget::text_ctrl(panel, false);
|
||||
inp.set_min_size(340, -1);
|
||||
if let Some(ColFilter::Text { needle, .. }) = &existing {
|
||||
inp.set_value(needle);
|
||||
}
|
||||
cs.add(inp, 0, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
self.filter_text = inp;
|
||||
}
|
||||
cs.set_sizer_on(panel);
|
||||
panel.layout();
|
||||
self.filter_dialog.layout();
|
||||
}
|
||||
|
||||
/// Read the visible criterion controls into the working filter for the
|
||||
/// current column (removing it when the criterion is empty / matches all).
|
||||
fn commit_filter_current(&mut self) {
|
||||
if self.filter_cols.is_empty() {
|
||||
return;
|
||||
}
|
||||
let col = self.filter_cols[self.filter_cur];
|
||||
let op_idx = self.filter_active_op;
|
||||
let f: Option<ColFilter> = if col.is_numeric() {
|
||||
match self.filter_num_a.get_value().trim().parse::<f64>() {
|
||||
Err(_) => None,
|
||||
Ok(a) => {
|
||||
let op = match op_idx {
|
||||
0 => NumOp::Between,
|
||||
1 => NumOp::Eq,
|
||||
2 => NumOp::Ne,
|
||||
3 => NumOp::Gt,
|
||||
4 => NumOp::Ge,
|
||||
5 => NumOp::Lt,
|
||||
_ => NumOp::Le,
|
||||
};
|
||||
let b = if op_idx == 0 {
|
||||
self.filter_num_b.get_value().trim().parse::<f64>().unwrap_or(a)
|
||||
} else {
|
||||
a
|
||||
};
|
||||
Some(ColFilter::Num { op, a, b })
|
||||
}
|
||||
}
|
||||
} else if op_idx == 0 {
|
||||
let clb = self.filter_values;
|
||||
let count = clb.clb_count();
|
||||
let mut allowed = HashSet::new();
|
||||
for i in 0..count {
|
||||
if clb.clb_checked(i) {
|
||||
// Map back to the real value by index, so a genuine cell whose
|
||||
// text is literally "(blank)" is not confused with an empty one.
|
||||
allowed.insert(self.filter_values_data.get(i).cloned().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
if allowed.is_empty() || allowed.len() == count {
|
||||
None // all (or none) checked == no filter
|
||||
} else {
|
||||
Some(ColFilter::Values(allowed))
|
||||
}
|
||||
} else {
|
||||
let needle = self.filter_text.get_value().trim().to_string();
|
||||
if needle.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let op = match op_idx {
|
||||
1 => TextOp::Contains,
|
||||
2 => TextOp::NotContains,
|
||||
3 => TextOp::BeginsWith,
|
||||
4 => TextOp::EndsWith,
|
||||
_ => TextOp::Equals,
|
||||
};
|
||||
Some(ColFilter::Text { op, needle })
|
||||
}
|
||||
};
|
||||
match f {
|
||||
Some(f) => {
|
||||
self.filter_working.insert(col, f);
|
||||
}
|
||||
None => {
|
||||
self.filter_working.remove(&col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check or uncheck every value in the current column's checklist.
|
||||
fn filter_check_all(&self, checked: bool) {
|
||||
let clb = self.filter_values;
|
||||
for i in 0..clb.clb_count() {
|
||||
clb.clb_set_checked(i, checked);
|
||||
}
|
||||
}
|
||||
|
||||
fn on_choice_changed(&mut self, id: i32, sel: i32) {
|
||||
match id {
|
||||
ID_FILTER_COL => {
|
||||
self.commit_filter_current();
|
||||
self.filter_cur = (sel.max(0) as usize).min(self.filter_cols.len().saturating_sub(1));
|
||||
self.build_filter_controls(None);
|
||||
}
|
||||
ID_FILTER_OP => {
|
||||
// The op dropdown lives inside the controls panel that
|
||||
// build_filter_controls destroys, so rebuilding here would delete
|
||||
// this very wxChoice mid-event. Defer it off the choice event.
|
||||
self.commit_filter_current();
|
||||
self.filter_pending_op = Some(sel);
|
||||
wx_rs::call_after(DEFER_FILTER);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A deferred rebuild requested via `wx_rs::call_after`, run after the
|
||||
/// triggering widget's own event has unwound.
|
||||
fn on_deferred(&mut self, id: i32) {
|
||||
match id {
|
||||
DEFER_TABLE => self.rebuild_table(),
|
||||
DEFER_FILTER => {
|
||||
let op = self.filter_pending_op.take();
|
||||
self.build_filter_controls(op);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_filter(&mut self) {
|
||||
for (c, lst) in &self.filter_lists {
|
||||
let count = lst.clb_count();
|
||||
let mut allowed = HashSet::new();
|
||||
for i in 0..count {
|
||||
if lst.clb_checked(i) {
|
||||
// map the shown "(blank)" back to the empty string
|
||||
let v = lst.clb_string(i).unwrap_or_default();
|
||||
allowed.insert(if v == "(blank)" { String::new() } else { v });
|
||||
}
|
||||
}
|
||||
if allowed.is_empty() || allowed.len() == count {
|
||||
self.view.filters.remove(c); // all (or none) checked = no filter
|
||||
} else {
|
||||
self.view.filters.insert(*c, allowed);
|
||||
}
|
||||
}
|
||||
self.commit_filter_current();
|
||||
self.view.filters = self.filter_working.clone();
|
||||
self.filter_dialog.close(1);
|
||||
self.fill_rows();
|
||||
}
|
||||
|
||||
fn reset_filters(&mut self) {
|
||||
self.filter_working.clear();
|
||||
self.view.filters.clear();
|
||||
self.filter_dialog.close(1);
|
||||
self.fill_rows();
|
||||
@@ -757,21 +1130,20 @@ impl App {
|
||||
wx_rs::set_status_text(&format!("{} miners - paused", self.rows.len()));
|
||||
}
|
||||
ID_STOP => {
|
||||
// Halt the loop and drop any in-flight scan.
|
||||
// Halt the loop and cancel any in-flight scan (dropping
|
||||
// the receiver alone would leave the thread probing).
|
||||
self.playing = false;
|
||||
self.countdown = 0;
|
||||
self.scanning = false;
|
||||
self.scan_rx = None;
|
||||
if let Some(old) = self.scan.take() {
|
||||
old.stop();
|
||||
}
|
||||
self.progress.show(false);
|
||||
self.table_parent.layout();
|
||||
wx_rs::set_status_text(&format!("{} miners - stopped", self.rows.len()));
|
||||
}
|
||||
_ if (ID_FILTER_ALL_BASE..ID_FILTER_NONE_BASE).contains(&id) => {
|
||||
self.filter_check_all((id - ID_FILTER_ALL_BASE) as usize, true);
|
||||
}
|
||||
_ if (ID_FILTER_NONE_BASE..ID_FILTER_NONE_BASE + 200).contains(&id) => {
|
||||
self.filter_check_all((id - ID_FILTER_NONE_BASE) as usize, false);
|
||||
}
|
||||
ID_FILTER_ALL_BASE => self.filter_check_all(true),
|
||||
ID_FILTER_NONE_BASE => self.filter_check_all(false),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -779,6 +1151,11 @@ impl App {
|
||||
WxEventKind::DvlcSelectionChanged => self.on_selection_changed(),
|
||||
WxEventKind::DvlcActivated => self.activate_row(ev.p1 as usize),
|
||||
WxEventKind::DvlcReordered => self.column_reordered(),
|
||||
WxEventKind::DvlcContextMenu => self.show_context_menu(),
|
||||
WxEventKind::MenuItem => self.on_menu_item(ev.p1 as i32),
|
||||
WxEventKind::ChoiceChanged => self.on_choice_changed(ev.p1 as i32, ev.p2 as i32),
|
||||
WxEventKind::SysColour => self.repaint_theme(),
|
||||
WxEventKind::Deferred => self.on_deferred(ev.p1 as i32),
|
||||
WxEventKind::TimerTick if ev.p1 as i32 == TIMER_SCAN => self.tick(),
|
||||
_ => {}
|
||||
}
|
||||
@@ -912,4 +1289,14 @@ pub fn dispatch(ev: WxEvent) {
|
||||
dlg.show_modal(); // nested loop, no App borrow held; blocks until EndModal
|
||||
dlg.destroy(); // tear the dialog down (needs no App borrow, so none is taken)
|
||||
}
|
||||
// Phase 3: a pending right-click context menu. popup_menu runs its own nested
|
||||
// loop and its MenuItem event re-enters dispatch, so it must run with no App
|
||||
// borrow held (like a modal). The menu is deleted by popup_menu itself.
|
||||
let popup = APP.with(|cell| {
|
||||
let Ok(mut app_ref) = cell.try_borrow_mut() else { return None };
|
||||
app_ref.as_mut().and_then(|app| app.take_pending_popup())
|
||||
});
|
||||
if let Some((on, menu)) = popup {
|
||||
on.popup_menu(menu);
|
||||
}
|
||||
}
|
||||
|
||||
+84
-1
@@ -10,7 +10,7 @@
|
||||
+pub use widgets::*;
|
||||
--- a/src/widgets.rs
|
||||
+++ b/src/widgets.rs
|
||||
@@ -0,0 +1,561 @@
|
||||
@@ -0,0 +1,644 @@
|
||||
+// 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).
|
||||
@@ -77,6 +77,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 +97,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 +139,9 @@
|
||||
+ DvlcSelectionChanged,
|
||||
+ DvlcContextMenu,
|
||||
+ MenuItem,
|
||||
+ ChoiceChanged,
|
||||
+ SysColour,
|
||||
+ Deferred,
|
||||
+}
|
||||
+
|
||||
+impl WxEventKind {
|
||||
@@ -144,6 +157,9 @@
|
||||
+ 9 => WxEventKind::DvlcSelectionChanged,
|
||||
+ 10 => WxEventKind::DvlcContextMenu,
|
||||
+ 11 => WxEventKind::MenuItem,
|
||||
+ 12 => WxEventKind::ChoiceChanged,
|
||||
+ 13 => WxEventKind::SysColour,
|
||||
+ 14 => WxEventKind::Deferred,
|
||||
+ _ => return None,
|
||||
+ })
|
||||
+ }
|
||||
@@ -154,6 +170,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();
|
||||
@@ -472,6 +495,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 +598,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) }
|
||||
+ }
|
||||
+}
|
||||
|
||||
+206
-62
@@ -1,6 +1,6 @@
|
||||
--- a/cpp_src/widgets_bridge.cpp
|
||||
+++ b/cpp_src/widgets_bridge.cpp
|
||||
@@ -0,0 +1,598 @@
|
||||
@@ -0,0 +1,742 @@
|
||||
+// 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,19 @@
|
||||
+#include <wx/app.h>
|
||||
+#include <wx/rearrangectrl.h>
|
||||
+#include <wx/menu.h>
|
||||
+#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 <cstring>
|
||||
+#ifdef __WXGTK__
|
||||
+#include <gtk/gtk.h>
|
||||
+#endif
|
||||
+#include <cstdio>
|
||||
+#include <vector>
|
||||
+
|
||||
+typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
||||
+static WxWidgetEventFn g_widget_event = nullptr;
|
||||
@@ -43,6 +52,27 @@
|
||||
+ 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;
|
||||
+ }
|
||||
+};
|
||||
+
|
||||
+extern "C" {
|
||||
@@ -269,63 +299,73 @@
|
||||
+
|
||||
+// ---- 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);
|
||||
+}
|
||||
+
|
||||
+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 +374,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 +426,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 +466,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 +644,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"
|
||||
|
||||
+205
-61
@@ -20,10 +20,19 @@
|
||||
#include <wx/app.h>
|
||||
#include <wx/rearrangectrl.h>
|
||||
#include <wx/menu.h>
|
||||
#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 <cstring>
|
||||
#ifdef __WXGTK__
|
||||
#include <gtk/gtk.h>
|
||||
#endif
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
||||
static WxWidgetEventFn g_widget_event = nullptr;
|
||||
@@ -40,6 +49,27 @@ 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;
|
||||
}
|
||||
};
|
||||
|
||||
extern "C" {
|
||||
@@ -266,63 +296,73 @@ void wxbr_dialog_close(void* win, int code) {
|
||||
|
||||
// ---- 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);
|
||||
}
|
||||
|
||||
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 +371,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 +423,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 +463,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 +641,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"
|
||||
|
||||
@@ -64,6 +64,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 +84,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 +126,9 @@ pub enum WxEventKind {
|
||||
DvlcSelectionChanged,
|
||||
DvlcContextMenu,
|
||||
MenuItem,
|
||||
ChoiceChanged,
|
||||
SysColour,
|
||||
Deferred,
|
||||
}
|
||||
|
||||
impl WxEventKind {
|
||||
@@ -131,6 +144,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 +157,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();
|
||||
@@ -459,6 +482,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 +585,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) }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user