Compare commits

...
73 Commits
Author SHA1 Message Date
noah c3b0dc6c8a Merge pull request 'Say in the Windows zip README whether the executable is signed' (#18) from windows-signed-readme into main 2026-11-03 07:21:11 -07:00
noahandClaude Opus 5.5 bfda29a845 Say in the Windows zip's README whether the executable is signed
Signing is now on (Azure Artifact Signing profile alkane-toolkit); the README
tells site users how to confirm the Blueflare signature, or that an unsigned
build will trip SmartScreen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:07:21 -06:00
noah 2c58cbac48 Merge pull request 'Sign the Windows build with Azure Artifact Signing' (#17) from windows-signing into main 2026-11-02 19:51:15 -07:00
noahandClaude Opus 5.5 174b162dfd Sign the Windows build with Azure Artifact Signing
- ci/sign-windows.sh signs alkane-toolkit.exe from Linux with jsign through
  the blueflaresigning account (RFC 3161 timestamped), using the
  least-privilege CI service principal alkane-toolkit-ci-signer. It is a
  no-op until the repository variable AZURE_SIGNING_PROFILE names a
  certificate profile; after that any signing failure fails the build.
- release.yml and next.yml sign before packaging; windows-native.yml checks
  the signature with Get-AuthenticodeSignature on real Windows and requires
  Valid once signing is on.
- CI image adds a Java runtime and a checksum-pinned jsign 7.6 (re-pinned);
  windows-ci.sh fetches the same jar on older images.
- scripts/enable-windows-signing.sh turns signing on after Microsoft
  approves the publisher identity validation: creates the PublicTrust
  certificate profile, narrows the signer role to it, sets the variable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:38:21 -06:00
noah cbf0f70cf6 Merge pull request 'Run the native Windows job past the default execution policy' (#16) from fix/windows-native-shell into main 2026-11-02 18:30:31 -07:00
noahandClaude Opus 5.5 332a3f7419 Scope the PR private-key check to first-party sources
The documentation- and workflow-only PR checks grepped every tracked file
for private-key headers, so the test fixtures inside vendored upstream
crates (openssl, rustls-pemfile, aws-lc) failed every such PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:29:05 -06:00
noahandClaude Opus 5.5 3931b6348f Run the native Windows job's steps past the default execution policy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:25:54 -06:00
noah 69b1b6e6fb Merge pull request 'Add a native Windows build, tested and released by CI' (#15) from windows-port into main
Merge pull request 'Add a native Windows build, tested and released by CI' (#15) from windows-port into main
2026-11-02 18:00:26 -07:00
noahandClaude Opus 5.5 a732f01ac9 Document the Windows build, its CI and the native test runner
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:32:56 -06:00
noahandClaude Opus 5.5 6da34a55e8 Build, test and release the Windows build in CI
- ci/windows-ci.sh is the one definition of every Windows step (toolchain,
  clippy, build, tests and UI self-test under Wine, packaging, test bundle);
  verify, release and next only call it.
- release.yml: a windows job builds, tests and packages
  alkane-toolkit-vX.Y.Z-windows-x86_64.zip; the release job waits for it
  and attaches the zip next to the Linux tarball. next.yml does the same
  for -rc candidates, verify.yml runs the Windows gates on PRs.
- windows-native.yml (advisory, never gates a release) runs main's
  cross-built unit tests and UI self-test on real Windows 11 through the
  self-hosted VM runner (label alkane-windows).
- CI image: ci/images/alkane-ci.Dockerfile layers mingw-w64, Wine with a
  ready prefix, the rustup target and a prebuilt wxMSW prefix on the
  previously verified image; ci/images/build-image.sh pushes it and pins
  the digest. wx prefix/cache scripts take a linux|windows argument.
- CI checks the wx-rs patch queue; versioning treats the GUI build script,
  Windows resources and assets as release-relevant; the workflow contract
  test covers the Windows gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:32:55 -06:00
noahandClaude Opus 5.5 be5edfc2bf Port the toolkit GUI to Windows (wxMSW, cross-built with mingw-w64)
Build: the wx-rs build script chose the platform with cfg!(), which in a
build script describes the build host, so a Linux-to-Windows build took the
GTK path. It now reads CARGO_CFG_TARGET_*, and Windows/GNU builds through
wx-config exactly like GTK, against a static wxMSW from
scripts/build-wx-windows.sh. The C++ runtime is linked statically, so the
.exe imports only Windows system DLLs. crates/alkane-gui/build.rs embeds an
application manifest (Common Controls v6, per-monitor DPI v2, UTF-8 code
page, Windows 10/11), the icon and version info.

Bridge on wxMSW (patches 0007/0008):
- the upstream frame's invisible "OSX key events" child sat above the UI on
  MSW and swallowed every click and key; it is no longer created there
- light/dark is chosen before the first window (wxMSW ignores it later) and
  follows the Windows app mode, with dark grid rules for the data view
- the generic wxDataViewCtrl gets mouse input in its inner main window, so
  drag-select and the per-cell / per-icon tooltips bind there (GTK keeps
  its native GtkTreeView paths; the icon hit-test is shared)
- sizes cross the Rust/C++ boundary in DIPs (identity on GTK), so columns,
  icons, KPI cards and the status bar scale at 125-200 %
- vector shapes go through GDI+ (anti-aliased like Cairo on GTK); selected
  rows use the themed list-view text colour like the native renderer
- the frame never opens larger than the monitor work area; title-bar icon
  from the executable; upstream menu insert no longer reads UTF-8 as UTF-16

App: OS differences live in alkane_core::platform (settings in
%APPDATA%\alkane-toolkit, owner-only secret files, NUL, console-less helper
processes). SSH password logins use SSH_ASKPASS with the toolkit itself as
the helper on every platform, replacing sshpass, which Windows lacks.
Release builds are GUI-subsystem; headless modes attach to the parent
console.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:32:44 -06:00
noahandClaude Opus 5.5 569ef9dcd8 Make the wx-rs patch queue reproducible and checkable
The queue had drifted from the patched tree it describes: 0003 predated
rounds 12-19 of bridge work, 0005 no longer applied on top of it, and the
Cargo.toml note and the case-duplicate readme.md were in no patch at all.
Vendor the pristine crates.io crate (sha256 pinned in VERSION) and add
scripts/wx_rs_patches.py: 'check' rebuilds the tree from upstream + patches
and requires an exact match, 'capture' records an edit as the next patch.
0002/0003 are regenerated to the current bridge files (0005's GTK tooltip
fix is folded into 0003); 0005 now carries the packaging leftovers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:32:30 -06:00
noahandClaude Opus 5.5 b1313fd059 Restore wxWidgets files the tarball's own .gitignores kept out of git
The vendored wxWidgets 3.3.3 tree was missing 44 files of the pinned release
tarball (pnglibconf.h, PCRE2's configure and libtool files, libtiff build/):
the tarball ships nested .gitignore files, so a plain git add dropped them.
Linux links the system libpng/pcre2 and never noticed; the builtin libraries
the Windows build uses need them. The tree now matches the tarball
(sha256 81b09d6d...) byte for byte; VERSION says how to re-vendor safely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:32:14 -06:00
noah 9ad8b56c1f Gate first-party Toolkit Rust formatting 2026-10-20 19:42:41 -06:00
noah 28f8f9ce80 Install rustfmt before CI format gates 2026-10-20 19:32:20 -06:00
noah d35cedd056 Describe formatting in quality badge 2026-10-20 19:30:25 -06:00
noah a825299ebc Format first-party GUI and gate Rust style 2026-10-20 19:29:43 -06:00
noah a17f108050 Clarify Toolkit quality badge scope 2026-10-20 19:28:47 -06:00
noah 3faa35ea70 Clarify Toolkit quality badge scope 2026-10-20 19:11:50 -06:00
noah 16490dd3b9 Merge pull request 'Isolate trusted toolkit jobs from fast runner' (#10) from ci/isolate-fast-runner-main into main 2026-10-20 18:58:53 -06:00
noah e6ae9d9d50 Isolate trusted toolkit jobs from fast runner 2026-10-20 18:45:04 -06:00
noah fc1ed3e4e5 Merge pull request 'Clarify Toolkit control and flashing scope' (#8) from docs/readme-scope into main 2026-10-19 23:52:32 -06:00
noah d7a914258e ci: close documentation-only verification block 2026-10-19 23:42:07 -06:00
noah 2108f47eea docs: clarify toolkit control and flash scope 2026-10-19 23:38:44 -06:00
noah d4a1db7243 Merge pull request 7: ci benchmark input context 2026-10-19 07:23:37 -06:00
noah 18acc31a28 ci: mark benchmark deltas with unchanged build inputs 2026-10-19 07:04:44 -06:00
noah d780fe007a Merge pull request 'ci: scope Toolkit workflow-only pull request checks' (#6) from ci/workflow-only-pr into main 2026-10-19 06:45:20 -06:00
noah f18bad36f3 ci: scope Toolkit workflow-only pull request checks 2026-10-19 06:31:16 -06:00
noah d7ae81dce9 Merge pull request 'ci: restore Toolkit main release to Alkane build pool' (#5) from ci/restore-main-release-pool into main 2026-10-19 06:30:16 -06:00
noah 10c93a3246 ci: route full Toolkit main release to Alkane build pool 2026-10-19 06:18:28 -06:00
noah 50ff6c60ce Merge pull request 'Use persistent Alkane cache for Toolkit main releases' (#4) from ci/static-main-release into main 2026-10-19 05:11:16 -06:00
noah cfe1f5be3b Run Toolkit main release on persistent Alkane verifier 2026-10-19 04:13:38 -06:00
noah 22e9106606 Merge pull request 'Use bounded Rust cache in Toolkit main and next CI' (#3) from ci/cache-main-and-next into main
Use bounded Rust cache on Toolkit main and next
2026-10-19 00:04:50 -06:00
noah c6b67c3b86 Bound Toolkit release compiler parallelism to measured memory 2026-10-18 23:53:33 -06:00
noah 77aacef528 Use bounded Rust cache in Toolkit main and next CI 2026-10-18 23:51:54 -06:00
noah 9bab162d64 Merge pull request 'Scope Toolkit PR checks and use prebuilt CI tools' (#2) from ci/docs-pr-fast-path into main
Speed Toolkit CI with scoped PR checks and bounded compiler caching
2026-10-18 23:49:27 -06:00
noah d0bbed568c Pilot bounded Rust compiler cache in Toolkit verification 2026-10-18 23:01:58 -06:00
noah 41142e707a Avoid duplicate source job for Toolkit main PRs 2026-10-18 22:35:04 -06:00
noah 7f106e2deb Use prebuilt CI tools and skip redundant wx cache transfer 2026-10-18 22:28:35 -06:00
noah 5cdce25329 Skip wx cache upload when image supplies the library 2026-10-18 22:15:27 -06:00
noah 01dd9ca287 Reject symlinked wx prefix markers 2026-10-18 22:02:48 -06:00
noah cb4c56679d Verify wx source provenance before reusing prefix 2026-10-18 21:56:00 -06:00
noah d0ecaea174 Publish Toolkit benchmarks on Pages runner after main CI 2026-10-18 21:50:25 -06:00
noah a77cd3a682 Include every Toolkit crate in unit coverage 2026-10-18 21:31:36 -06:00
noah c3efda87c3 Cover all Toolkit crates and pin CI image 2026-10-18 21:29:33 -06:00
noah afbaac0c0e Scope headless crate PR checks to reverse dependencies 2026-10-18 21:04:36 -06:00
noah c287aaaf58 Save wxWidgets cache before later quality checks 2026-10-18 21:04:35 -06:00
noah 6e09624120 Key wxWidgets cache to available native packages 2026-10-18 21:04:33 -06:00
noah 1edc446940 Skip redundant Toolkit package setup on prepared runners 2026-10-18 21:04:32 -06:00
noah f86f34bd90 Skip heavyweight Toolkit checks for documentation-only PRs 2026-10-18 21:04:30 -06:00
noah ff0724f96a Merge pull request 'Consolidate Toolkit CI setup and gate benchmark publication' (#1) from ci/release-setup-pages-order into main 2026-10-18 21:02:52 -06:00
noah 41d2bd6d91 Key wxWidgets cache to source and toolchain inputs 2026-10-18 20:15:24 -06:00
noah 8a75ee40bc Isolate Toolkit pull request verification from release queue 2026-10-18 20:13:17 -06:00
noah 75be20163d Stop scheduled Toolkit benchmark republishing 2026-10-18 20:03:45 -06:00
noah 0013dd45c2 Separate fast Toolkit checks from full main verification 2026-10-18 20:01:37 -06:00
noah a3ee239900 Route short Toolkit checks to Alkane fast runner 2026-10-18 20:01:35 -06:00
noah 5fc08e408e Use lightweight checks for Toolkit feature and next changes 2026-10-18 20:01:32 -06:00
noah 5098be30d1 Consolidate setup and gate benchmark publication 2026-10-18 20:01:26 -06:00
noah 1323dc1571 Add bounded read-only SSH board probes 2026-10-17 08:00:36 -06:00
noah 848a78ed5f docs: shorten Toolkit entry guide 2026-10-17 01:42:12 -06:00
noah 8d092ae417 Publish Toolkit benchmarks on the standing Alkane runner 2026-10-17 01:21:21 -06:00
noah 7445b05e57 Validate public benchmark page before upload 2026-10-16 08:46:06 -06:00
noah faae4ee145 Publish Toolkit benchmarks to public Pages site 2026-10-16 07:19:42 -06:00
noah 942801ee4b Bound queued Toolkit CI attempts per branch 2026-10-16 07:08:39 -06:00
noah 8de1bdffd4 Average benchmark improvements equally in Toolkit badge 2026-10-16 06:02:42 -06:00
noah 77237023e3 Require complete Toolkit benchmarks before release 2026-10-16 05:11:44 -06:00
noah fc573f075a Benchmark health diagnostics on representative miners 2026-10-15 20:19:18 -06:00
noah 1c364d4ff1 Guard UTF-8 naming and repair headless screenshots 2026-10-15 20:10:19 -06:00
noah d54bd6473f Stage verified flash images before device writes 2026-10-15 19:10:28 -06:00
noah a5b07d22ae Grade Toolkit code quality from static checks 2026-10-15 19:03:34 -06:00
Noah 3d17326460 Simplify Toolkit docs and update installer status 2026-10-15 14:36:09 -06:00
noah 56339a5eca Clean candidate build after prerelease decision 2026-10-15 12:43:30 -06:00
noah 00bb760451 Clean generated Toolkit builds after CI and local GUI builds 2026-10-15 11:51:55 -06:00
137 changed files with 77582 additions and 1749 deletions
+35
View File
@@ -0,0 +1,35 @@
name: public-benchmark-pages
on:
workflow_run:
workflows: [build-test-release]
types: [completed]
workflow_dispatch:
concurrency:
group: alkane-toolkit-public-benchmark-pages
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: bash ci/ensure-build-deps.sh ssh
- name: Render measured benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py render
- name: Publish public benchmark page
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
run: python3 ci/publish-bench-pages.py toolkit
- name: Clean generated page
if: always()
run: python3 ci/cleanup-generated.py
+3 -1
View File
@@ -7,7 +7,9 @@ on:
jobs:
publish:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
actions: read
contents: write
+129 -11
View File
@@ -4,32 +4,129 @@ on:
push:
branches: [next]
concurrency:
group: alkane-toolkit-next
cancel-in-progress: false
permissions:
contents: write
jobs:
candidate:
# Windows build of the candidate (see release.yml's windows job); the
# candidate job attaches its zip next to the Linux tarball.
windows:
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Select candidate version
id: version
run: bash ci/compute-rc-version.sh >> "$GITHUB_OUTPUT"
- name: Install Windows toolchain
if: steps.version.outputs.release == 'true'
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
if: steps.version.outputs.release == 'true'
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
if: steps.version.outputs.release == 'true'
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
if: steps.version.outputs.release == 'true'
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- id: wx-cache
if: steps.version.outputs.release == 'true' && steps.wx-image.outputs.available != 'true'
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW
if: steps.version.outputs.release == 'true'
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.version.outputs.release == 'true' && steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build Windows candidate
if: steps.version.outputs.release == 'true'
run: bash ci/windows-ci.sh build
- name: Sign Windows candidate (Azure Artifact Signing)
if: steps.version.outputs.release == 'true'
env:
AZURE_SIGNING_PROFILE: ${{ vars.AZURE_SIGNING_PROFILE }}
AZURE_SIGNING_TENANT_ID: ${{ secrets.AZURE_SIGNING_TENANT_ID }}
AZURE_SIGNING_CLIENT_ID: ${{ secrets.AZURE_SIGNING_CLIENT_ID }}
AZURE_SIGNING_CLIENT_SECRET: ${{ secrets.AZURE_SIGNING_CLIENT_SECRET }}
run: bash ci/windows-ci.sh sign
- name: Package Windows candidate
if: steps.version.outputs.release == 'true'
run: bash ci/windows-ci.sh package "${{ steps.version.outputs.version }}"
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
if: steps.version.outputs.release == 'true'
with:
name: alkane-toolkit-windows
path: dist/alkane-toolkit-v*-windows-x86_64.zip
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
candidate:
needs: windows
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Install build dependencies
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends libssl-dev pkg-config ca-certificates
- uses: actions/cache@v4
run: bash ci/ensure-build-deps.sh base
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxWidgets cache key
id: wx-key
run: bash ci/wx-cache-key.sh
- name: Check prebuilt wxWidgets
id: wx-image
run: bash ci/check-wx-image-prefix.sh
- id: wx-cache
if: steps.wx-image.outputs.available != 'true'
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxWidgets
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
fi
id: wx-build
run: bash ci/ensure-wx-prefix.sh
- name: Save vendored wxWidgets build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
- name: Build release candidate
run: cargo build --release -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli --offline
- name: Select candidate version
@@ -41,8 +138,29 @@ jobs:
mkdir -p dist
cp target/release/alkane-toolkit dist/
tar -C dist -czf "dist/alkane-toolkit-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz" alkane-toolkit
- name: Fetch Windows candidate
if: steps.version.outputs.release == 'true'
uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7
with:
name: alkane-toolkit-windows
path: dist/windows
- name: Create private prerelease
if: steps.version.outputs.release == 'true'
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/release-rc.py "${{ steps.version.outputs.tag }}" true "dist/alkane-toolkit-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz"
run: |
set -euo pipefail
V="${{ steps.version.outputs.version }}"
WIN="dist/windows/alkane-toolkit-v${V}-windows-x86_64.zip"
[ -s "$WIN" ] || { echo "Windows candidate for ${V} is missing" >&2; exit 1; }
python3 ci/release-rc.py "${{ steps.version.outputs.tag }}" true \
"dist/alkane-toolkit-${V}-linux-x86_64.tar.gz" "$WIN"
- name: Rust compiler cache statistics
if: always()
run: |
if [ -n "${SCCACHE_DIR:-}" ]; then
sccache --show-stats
fi
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+209 -44
View File
@@ -1,19 +1,137 @@
name: build-test-release
# Runs on every merge/push to main: build the GUI, run tests + a microbenchmark,
# and (when the change warrants it) cut an X.Y.Z release with the binary attached.
# Runs on every merge/push to main: build the GUI for Linux and Windows, run the
# tests + a microbenchmark, and (when the change warrants it) cut an X.Y.Z
# release with both binaries attached.
on:
push:
branches: [main]
concurrency:
group: alkane-toolkit-main
cancel-in-progress: false
permissions:
contents: write
actions: write
jobs:
release:
# Windows build of the same commit: cross-compiled with mingw-w64 against the
# vendored wxMSW, unit-tested and UI-self-tested under Wine, packaged as a
# zip. The release job below waits for it and attaches the zip next to the
# Linux tarball, so a release never ships one platform without the other.
windows:
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- name: Checkout (full history for tags)
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Compute version
id: ver
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
- name: Install Windows toolchain
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- name: Cache vendored wxMSW build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (Windows target, warnings are errors)
run: bash ci/windows-ci.sh clippy
- name: Set crate version to ${{ steps.ver.outputs.version }}
if: steps.ver.outputs.release == 'true'
run: |
sed -i "0,/^version = \".*\"/s//version = \"${{ steps.ver.outputs.version }}\"/" Cargo.toml
grep -m1 '^version' Cargo.toml
- name: Build release (Windows)
run: bash ci/windows-ci.sh build
- name: Unit tests (Windows build, under Wine)
run: bash ci/windows-ci.sh test
- name: Headless UI self-test (Windows build, under Wine)
run: bash ci/windows-ci.sh selftest
- name: Sign Windows executable (Azure Artifact Signing)
env:
AZURE_SIGNING_PROFILE: ${{ vars.AZURE_SIGNING_PROFILE }}
AZURE_SIGNING_TENANT_ID: ${{ secrets.AZURE_SIGNING_TENANT_ID }}
AZURE_SIGNING_CLIENT_ID: ${{ secrets.AZURE_SIGNING_CLIENT_ID }}
AZURE_SIGNING_CLIENT_SECRET: ${{ secrets.AZURE_SIGNING_CLIENT_SECRET }}
run: bash ci/windows-ci.sh sign
- name: Package Windows artifact
if: steps.ver.outputs.release == 'true'
run: bash ci/windows-ci.sh package "${{ steps.ver.outputs.version }}"
- name: Bundle Windows test executables
run: bash ci/windows-ci.sh test-bundle
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
if: steps.ver.outputs.release == 'true'
with:
name: alkane-toolkit-windows
path: dist/alkane-toolkit-v*-windows-x86_64.zip
# Consumed by .gitea/workflows/windows-native.yml on the Windows VM runner.
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-toolkit-windows-tests
path: |
dist/alkane-toolkit-windows-tests.zip
target/x86_64-pc-windows-gnu/release/alkane-toolkit.exe
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
release:
needs: windows
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
# Set once for the whole job so build/clippy/test/bench steps don't each
# re-export it (round 18 #12).
@@ -24,6 +142,18 @@ jobs:
with:
fetch-depth: 0
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Check wx-rs patch queue reproduces the patched tree
run: python3 scripts/wx_rs_patches.py check
- name: Check first-party Rust formatting
run: |
rustup component add rustfmt >/dev/null
cargo fmt -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli -p alkane-access -p alkane-core -- --check
- name: Compute version
id: ver
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
@@ -37,32 +167,49 @@ jobs:
- name: Benchmark history checks
run: python3 ci/test-bench-history.py
- name: Benchmark suite checks
run: python3 ci/test-bench-badge.py
- name: Install build dependencies
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
libssl-dev pkg-config ca-certificates >/dev/null
echo "libssl-dev + pkg-config installed (openssl-sys needs them)"
run: bash ci/ensure-build-deps.sh all
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxWidgets cache key
id: wx-key
run: bash ci/wx-cache-key.sh
- name: Check prebuilt wxWidgets
id: wx-image
run: bash ci/check-wx-image-prefix.sh
- name: Cache vendored wxWidgets build
uses: actions/cache@v4
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxWidgets (once, then cached)
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
else
echo "wx prefix restored from cache"
fi
id: wx-build
run: bash ci/ensure-wx-prefix.sh
- name: Save vendored wxWidgets build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (our crate, warnings are errors)
run: |
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --offline -- -D warnings
cargo clippy -p alkane-artifacts -p alkane-flash -p alkane-cli --all-targets --offline -- -D warnings
cargo clippy --workspace --exclude alkane-gui --exclude wx-rs --all-targets --offline -- -D warnings
- name: Set crate version to ${{ steps.ver.outputs.version }}
if: steps.ver.outputs.release == 'true'
@@ -78,7 +225,7 @@ jobs:
run: |
set -o pipefail
cargo test -p alkane-gui --offline 2>&1 | tee tests-gui.txt
cargo test -p alkane-artifacts -p alkane-flash -p alkane-cli --offline 2>&1 | tee tests-core.txt
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline 2>&1 | tee tests-core.txt
cat tests-gui.txt tests-core.txt > tests-current.txt
- name: Load previous main benchmark measurement
@@ -88,27 +235,15 @@ jobs:
- name: Microbenchmarks
run: |
# Capture the bench stdout for the weighted-average delta badge (round 19
# #1) while keeping the step a hard gate: pipefail preserves cargo's exit
# code (each bench asserts its own absolute ceiling) even through tee.
# Require every declared benchmark before publishing history or a release.
set -o pipefail
cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1 \
| tee bench-current.txt
- name: Record private benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py publish
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-toolkit-benchmark-site-preview
path: bench-site/index.html
python3 ci/bench-badge.py --current bench-current.txt \
--baseline badges/bench-baseline.json --no-write
- name: Headless UI self-test
run: |
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"
@@ -121,6 +256,13 @@ jobs:
echo "cargo-audit not installed on this runner; skipping"
fi
- name: Rust compiler cache statistics
if: always()
run: |
if [ -n "${SCCACHE_DIR:-}" ]; then
sccache --show-stats
fi
# Merge coverage from unit tests and the headless UI self-test. A failed
# measurement must not publish a stale badge or create a release.
- name: Coverage
@@ -128,15 +270,7 @@ jobs:
run: |
set -euo pipefail
rustup component add llvm-tools-preview >/dev/null 2>&1 || true
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
V=0.8.7
URL="https://github.com/taiki-e/cargo-llvm-cov/releases/download/v${V}/cargo-llvm-cov-x86_64-unknown-linux-gnu.tar.gz"
DEST="${CARGO_HOME:-$HOME/.cargo}/bin"
mkdir -p "$DEST"
curl -fsSL "$URL" | tar -xz -C "$DEST"
export PATH="$DEST:$PATH"
fi
command -v cargo-llvm-cov >/dev/null
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
PCT=$(bash ci/coverage.sh --summary-only \
| awk '/^TOTAL/{gsub(/%/,"",$10); print $10}')
[ -n "$PCT" ] || { echo "coverage report produced no TOTAL line" >&2; exit 1; }
@@ -166,13 +300,22 @@ jobs:
python3 ci/gen-badges.py --tests "$PASS" \
--coverage "${{ steps.cov.outputs.pct }}" \
--bench-coverage "${{ steps.benchcov.outputs.pct }}" \
--bench-delta "$BENCH_DELTA"
--bench-delta "$BENCH_DELTA" --clippy clean
- name: Publish measured badges
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/publish-metrics.py
- name: Record private benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py publish
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-toolkit-benchmark-site-preview
path: bench-site/index.html
- name: Package artifact
if: steps.ver.outputs.release == 'true'
id: pkg
@@ -194,12 +337,34 @@ jobs:
echo "asset=dist/${NAME}.tar.gz" >> "$GITHUB_OUTPUT"
echo "assetname=${NAME}.tar.gz" >> "$GITHUB_OUTPUT"
- name: Fetch Windows artifact
if: steps.ver.outputs.release == 'true'
uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7
with:
name: alkane-toolkit-windows
path: dist/windows
- name: Locate Windows artifact
if: steps.ver.outputs.release == 'true'
id: winpkg
run: |
set -euo pipefail
V="${{ steps.ver.outputs.version }}"
ZIP="dist/windows/alkane-toolkit-v${V}-windows-x86_64.zip"
[ -s "$ZIP" ] || { echo "Windows artifact for v${V} is missing" >&2; ls -lR dist/windows >&2; exit 1; }
echo "asset=$ZIP" >> "$GITHUB_OUTPUT"
- name: Create Gitea release + upload artifact
if: steps.ver.outputs.release == 'true'
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/release-rc.py "${{ steps.ver.outputs.tag }}" false "${{ steps.pkg.outputs.asset }}"
run: |
python3 ci/release-rc.py "${{ steps.ver.outputs.tag }}" false \
"${{ steps.pkg.outputs.asset }}" "${{ steps.winpkg.outputs.asset }}"
- name: No release needed
if: steps.ver.outputs.release != 'true'
run: echo "No backend/UI change since ${{ steps.ver.outputs.last_tag }} - skipping release."
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+27
View File
@@ -0,0 +1,27 @@
name: source
on:
pull_request:
branches: [next]
workflow_dispatch:
concurrency:
group: alkane-toolkit-source-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_BUILD_JOBS: 2
steps:
- uses: actions/checkout@v4
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Source checks
run: cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+215 -27
View File
@@ -1,66 +1,173 @@
name: verify
# Pre-merge quality gate: clippy + build + tests + microbenchmarks + the headless
# UI self-test, plus a best-effort dependency audit. Runs on pull requests and on
# pushes to any branch EXCEPT main (main is gated by release.yml, which repeats
# these checks before it cuts a release -- so no work is duplicated on main).
# Full quality gate for pull requests to main.
on:
pull_request:
branches-ignore: [next]
push:
branches-ignore: [main, next]
branches: [main]
concurrency:
group: alkane-toolkit-verify-${{ github.ref }}
cancel-in-progress: true
jobs:
verify:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
outputs:
surface: ${{ steps.surface.outputs.surface }}
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install build dependencies
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
libssl-dev pkg-config ca-certificates >/dev/null
- name: Cache vendored wxWidgets build
uses: actions/cache@v4
with:
path: /root/.cache/wx-3.3.3-linux
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
fetch-depth: 0
- name: Build wxWidgets (once, then cached)
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Check wx-rs patch queue reproduces the patched tree
run: python3 scripts/wx_rs_patches.py check
- name: Detect changed surface
id: surface
run: python3 ci/pr-surface.py >> "$GITHUB_OUTPUT"
- name: Check documentation change
if: steps.surface.outputs.surface == 'documentation'
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
# Vendored upstream trees carry their own test-fixture keys (openssl,
# rustls-pemfile, aws-lc); only first-party sources are checked.
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' -- ':!vendor' ':!thirdparty'; then
echo "private key material found in tracked source" >&2
exit 1
else
echo "wx prefix restored from cache"
status=$?
[ "$status" -eq 1 ]
fi
- name: Check CI change surface
if: steps.surface.outputs.surface != 'documentation'
run: python3 ci/test-pr-surface.py
- name: Check first-party Rust formatting
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
run: |
rustup component add rustfmt >/dev/null
cargo fmt -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli -p alkane-access -p alkane-core -- --check
- name: Check workflow-only change
if: steps.surface.outputs.surface == 'workflow'
run: |
python3 - <<'PY'
from pathlib import Path
import yaml
for path in Path('.gitea/workflows').glob('*.yml'):
yaml.load(path.read_text(), Loader=yaml.BaseLoader)
PY
python3 ci/check-runner-image.py
for script in ci/*.sh; do bash -n "$script"; done
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
# Vendored upstream trees carry their own test-fixture keys (openssl,
# rustls-pemfile, aws-lc); only first-party sources are checked.
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' -- ':!vendor' ':!thirdparty'; then
echo "private key material found in tracked source" >&2
exit 1
else
status=$?
[ "$status" -eq 1 ]
fi
- name: Install build dependencies
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
run: bash ci/ensure-build-deps.sh base
- name: Configure bounded Rust compiler cache
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
run: bash ci/configure-rust-cache.sh
- name: Compute wxWidgets cache key
id: wx-key
if: steps.surface.outputs.surface == 'full'
run: bash ci/wx-cache-key.sh
- name: Check prebuilt wxWidgets
id: wx-image
if: steps.surface.outputs.surface == 'full'
run: bash ci/check-wx-image-prefix.sh
- name: Cache vendored wxWidgets build
if: steps.surface.outputs.surface == 'full' && steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxWidgets (once, then cached)
if: steps.surface.outputs.surface == 'full'
id: wx-build
run: bash ci/ensure-wx-prefix.sh
- name: Save vendored wxWidgets build
if: steps.surface.outputs.surface == 'full' && steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (our crate, warnings are errors)
if: steps.surface.outputs.surface == 'full'
run: |
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --offline -- -D warnings
cargo clippy -p alkane-artifacts -p alkane-flash -p alkane-cli --all-targets --offline -- -D warnings
cargo clippy --workspace --exclude alkane-gui --exclude wx-rs --all-targets --offline -- -D warnings
- name: Headless crate checks
if: steps.surface.outputs.surface == 'headless'
env:
PACKAGES: ${{ steps.surface.outputs.packages }}
run: |
rustup component add clippy >/dev/null 2>&1 || true
args=()
for package in $PACKAGES; do
case "$package" in
alkane-access|alkane-artifacts|alkane-cli|alkane-flash) args+=(-p "$package") ;;
*) echo "unrecognized crate: $package" >&2; exit 1 ;;
esac
done
[ "${#args[@]}" -gt 0 ]
cargo clippy "${args[@]}" --all-targets --offline -- -D warnings
cargo test "${args[@]}" --offline
- name: Build
if: steps.surface.outputs.surface == 'full'
run: cargo build --release -p alkane-gui --offline
- name: Unit tests
if: steps.surface.outputs.surface == 'full'
run: |
cargo test -p alkane-gui --offline
cargo test -p alkane-artifacts -p alkane-flash -p alkane-cli --offline
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
- name: Microbenchmarks
if: steps.surface.outputs.surface == 'full'
run: cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1
- name: Headless UI self-test
if: steps.surface.outputs.surface == 'full'
run: |
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
xvfb xauth dbus-x11 fonts-dejavu-core >/dev/null
bash ci/ensure-build-deps.sh ui
BIN=target/release/alkane-toolkit
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
@@ -69,6 +176,7 @@ jobs:
# runner must not fail the gate on it. Accepted advisories live in
# .cargo/audit.toml.
- name: Dependency audit (best-effort)
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
continue-on-error: true
run: |
if command -v cargo-audit >/dev/null 2>&1; then
@@ -76,3 +184,83 @@ jobs:
else
echo "cargo-audit not installed on this runner; skipping"
fi
- name: Rust compiler cache statistics
if: always() && (steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full')
run: |
if [ -n "${SCCACHE_DIR:-}" ]; then
sccache --show-stats
fi
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
# The Windows build of the same change (main's release gate, run on the PR):
# clippy for the Windows target, the release .exe, every unit test under
# Wine, and the headless UI self-test under Wine. Only for changes that can
# affect the binary (the "full" surface).
verify-windows:
needs: verify
if: needs.verify.outputs.surface == 'full'
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Windows toolchain
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- name: Cache vendored wxMSW build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (Windows target, warnings are errors)
run: bash ci/windows-ci.sh clippy
- name: Build (Windows)
run: bash ci/windows-ci.sh build
- name: Unit tests (Windows build, under Wine)
run: bash ci/windows-ci.sh test
- name: Headless UI self-test (Windows build, under Wine)
run: bash ci/windows-ci.sh selftest
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+101
View File
@@ -0,0 +1,101 @@
name: windows-native
# Smoke test on real Windows. The self-hosted runner in the Windows 11 test VM
# (label alkane-windows, host mode; see docs/windows.md) takes the Windows
# build that main's build-test-release run cross-compiled -- the release .exe
# and every unit-test executable, which already passed under Wine there -- and
# runs them natively: real Win32, real comctl32/visual styles, real DPI and
# real Windows networking.
#
# Advisory by design: a separate workflow, so it never gates or delays a
# release, and while the VM is off the job simply waits for the runner.
on:
workflow_run:
workflows: [build-test-release]
types: [completed]
workflow_dispatch:
inputs:
run_id:
description: build-test-release run whose Windows build to test
required: true
permissions:
actions: read
contents: read
jobs:
native:
if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success'
runs-on: alkane-windows
timeout-minutes: 30
env:
RUN_ID: ${{ github.event.workflow_run.id || inputs.run_id }}
# Windows' default execution policy (Restricted) refuses the script files
# the runner writes for each step; bypass it for these steps only, so the
# runner works without changing the machine's policy.
defaults:
run:
shell: powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File {0}
steps:
- name: Fetch the cross-built Windows build
env:
TOKEN: ${{ github.token }}
API: ${{ github.api_url }}/repos/${{ github.repository }}
run: |
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$work = Join-Path ([IO.Path]::GetTempPath()) "alkane-native-$env:RUN_ID"
Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue
New-Item -ItemType Directory $work | Out-Null
$auth = @{ Authorization = "token $env:TOKEN" }
$list = Invoke-RestMethod -Headers $auth "$env:API/actions/runs/$env:RUN_ID/artifacts"
$art = $list.artifacts | Where-Object { $_.name -eq 'alkane-toolkit-windows-tests' } |
Select-Object -First 1
if (-not $art) { throw "run $env:RUN_ID has no alkane-toolkit-windows-tests artifact" }
Invoke-WebRequest -Headers $auth -Uri $art.archive_download_url -OutFile "$work\artifact.zip"
Expand-Archive "$work\artifact.zip" "$work\artifact"
$bundle = Get-ChildItem -Recurse "$work\artifact" -Filter alkane-toolkit-windows-tests.zip |
Select-Object -First 1
Expand-Archive $bundle.FullName "$work\tests"
$exe = Get-ChildItem -Recurse "$work\artifact" -Filter alkane-toolkit.exe | Select-Object -First 1
Copy-Item $exe.FullName "$work\alkane-toolkit.exe"
"ALKANE_NATIVE=$work" | Out-File -Append -Encoding utf8 $env:GITHUB_ENV
$os = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
"Testing run $env:RUN_ID on Windows $($os.DisplayVersion) build $($os.CurrentBuild)"
- name: Authenticode signature (native Windows)
env:
SIGNING_ENABLED: ${{ vars.AZURE_SIGNING_PROFILE }}
run: |
# Windows itself judges the signature: chain to a trusted root,
# intact file hash, valid timestamp. Required once signing is on.
$sig = Get-AuthenticodeSignature "$env:ALKANE_NATIVE\alkane-toolkit.exe"
Write-Host "Signature: $($sig.Status) $($sig.StatusMessage)"
if ($sig.SignerCertificate) { Write-Host "Signer: $($sig.SignerCertificate.Subject)" }
if ($sig.TimeStamperCertificate) { Write-Host "Timestamp: $($sig.TimeStamperCertificate.Subject)" }
if ($env:SIGNING_ENABLED -and $sig.Status -ne 'Valid') { exit 1 }
- name: Unit tests (native Windows)
run: |
$failed = @()
foreach ($test in Get-Content "$env:ALKANE_NATIVE\tests\tests.txt") {
Write-Host "== $test"
& "$env:ALKANE_NATIVE\tests\$test"
if ($LASTEXITCODE -ne 0) { $failed += $test }
}
if ($failed) { Write-Host "FAILED: $($failed -join ', ')"; exit 1 }
- name: Headless UI self-test (native Windows)
run: |
# A GUI-subsystem executable: wait for it and read its redirected output.
$env:ALKANE_SELFTEST = '1'
$out = "$env:ALKANE_NATIVE\selftest.txt"
$p = Start-Process -FilePath "$env:ALKANE_NATIVE\alkane-toolkit.exe" -Wait -PassThru `
-NoNewWindow -RedirectStandardOutput $out -RedirectStandardError "$out.err"
Get-Content $out, "$out.err"
if ($p.ExitCode -ne 0) { exit $p.ExitCode }
- name: Remove the downloaded build
if: always()
run: |
if ($env:ALKANE_NATIVE) { Remove-Item -Recurse -Force $env:ALKANE_NATIVE -ErrorAction SilentlyContinue }
Generated
+1
View File
@@ -75,6 +75,7 @@ dependencies = [
"alkane-artifacts",
"alkane-core",
"sha2",
"tempfile",
"thiserror",
]
+37 -95
View File
@@ -1,4 +1,4 @@
# alkane-toolkit
# Alkane Toolkit
[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
![tests](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/tests.svg)
@@ -10,118 +10,60 @@
![dependencies](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/dependencies.svg)
![license](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/license.svg)
The CI badge shows the last completed attempt for this branch while newer
runs are queued. Badge SVGs are stored in a private, machine-maintained branch.
The code-quality letter requires warnings-denied Clippy and measured test plus
UI self-test line coverage: A at 90%, B at 80%, C at 70%, D at 60%, and F
below 60%. A missing coverage measurement displays pending.
The benchmark delta compares an earlier commit only when its CPU class
matches the current dedicated runner; otherwise it establishes a new
baseline. Main CI runs microbenchmarks serially to avoid test contention.
The code quality grade reports GUI Clippy and first-party Rust formatting checks
from the last successful main build. Test coverage has a separate badge.
A cross-platform desktop toolkit for discovering, monitoring, and re-flashing
ASIC miners. It scans a fleet over the network, shows live health and hashrate
in a sortable table. The install path is under development for **stock** and
**alkaneOS** firmware on boards running stock, VNish/AnthillOS, Braiins OS+,
LuxOS, ePIC, HiveOn, BixBit, WardenOS).
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled
while that path is reworked.
The core and UI are pure Rust; the native window is wxWidgets driven through a
vendored, patched [wx-rs](thirdparty/wx-rs) bridge, so there is no Electron,
no web view, and a single self-contained binary per platform.
## What it does
- **Discover** a fleet by CIDR or IP range and identify each miner's make,
model, control board, and firmware (via a vendored [asic-rs](vendor/asic-rs)).
- **Monitor** hashrate vs. expected, per-board health, chip temperatures, fans,
PSU state, and pool workers, with an Excel-style filter and drag-reorderable
columns.
- **Operate** miners from a right-click menu: flash the locate light, pause /
resume, restart, set a power or hashrate target, select a firmware profile
(LuxOS/VNish presets), configure pools, set the timezone, and change the
password -- each action offered only when every selected miner supports it.
- **Install firmware**: push stock or aftermarket images, or revert an
aftermarket miner to stock, behind a typed confirmation.
Discovery and telemetry are read-only and safe to run against any fleet; every
mutating action is capability-gated and, where destructive, confirmed.
## Build and run (Debian/Ubuntu)
## Run locally
```sh
scripts/build-wx-linux.sh # once: builds the vendored wxWidgets 3.3.3 into ~/.cache
scripts/build-gui-linux.sh # cargo build --release -p alkane-gui
~/.cache/alkane-tk-target/release/alkane-toolkit
scripts/build-wx-linux.sh
scripts/build-gui-linux.sh
ALKANE_FAKE_SCAN=1 ~/.cache/alkane-tk-target/release/alkane-toolkit
```
Runtime needs GTK 3: `sudo apt install libgtk-3-0`. To explore the UI with no
hardware, run the offline demo fleet:
The first command builds wxWidgets 3.3.3 once. Linux needs GTK 3. Fake scan
uses offline fixtures and does not contact hardware.
```sh
ALKANE_FAKE_SCAN=1 alkane-toolkit
```
Windows 10/11 builds are cross-compiled on Linux (`scripts/build-wx-windows.sh`,
then `scripts/build-gui-windows.sh`) and attached to every release as a
self-contained `alkane-toolkit.exe`; see [docs/windows.md](docs/windows.md).
macOS is not built.
Windows and macOS share all GUI code; only the C++ bridge and wx build differ
(`scripts/build-gui-windows.sh` needs an msys2 toolchain, `-macos.sh` needs a
Mac).
## Current scope
## Command-line probe
- Discover miners by CIDR or IP range with vendored [asic-rs](vendor/asic-rs).
- Show model, firmware, health, hashrate, temperatures, fans, PSU, and workers.
- Filter and sort the desktop table; inspect probes with `miner_probe`.
- Use controls supported by the selected firmware and restore supported
aftermarket firmware to stock.
`miner_probe` is a headless companion for hardware checks that should not go
through the window event loop -- discovery, telemetry, and each write action:
```sh
miner_probe scan 10.0.0.0/24 # discover + telemetry (TSV)
miner_probe presets 10.0.0.5 # list a firmware's selectable profiles
miner_probe setpreset 10.0.0.5 540MHz
```
Run `miner_probe` with no arguments for the full verb list.
Discovery is read-only. Control and restore actions change miners. Check the
selected devices before applying them. See the [implementation plan](docs/IMPLEMENTATION-PLAN.md)
and [firmware matrix](docs/aftermarket-parity-roadmap.md) for planned coverage.
## Development
```sh
export WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config"
export CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target" # keep the target tree off the source share
cargo test -p alkane-gui # unit tests
cargo test -p alkane-gui --release -- --ignored bench_ # microbenchmarks
cargo clippy -p alkane-gui --no-deps --bins -- -D warnings # lint gate
xvfb-run -a env ALKANE_SELFTEST=1 \
"$CARGO_TARGET_DIR/release/alkane-toolkit" # headless UI self-test
ci/coverage.sh --summary-only # coverage (tests + self-test)
WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config" \
CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target" \
cargo test -p alkane-gui --offline
```
CI mirrors these: `verify.yml` runs lint, tests, benchmarks, the self-test, and
a dependency audit on development branches. `release.yml` runs the full gate
on every `main` push and cuts an `X.Y.Z` release when the change warrants it.
`next.yml` builds release candidates with little testing and publishes `-rc`
releases. Dependencies are vendored under `vendor/`, so builds never touch the
network.
Keep build output off the source share. `main` runs full CI and publishes
qualifying releases; `next` builds `-rc` candidates. Badges measure host
code, not installation support. See the public
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/toolkit/).
## Architecture
## Firmware safety
- `crates/alkane-gui` -- the application: scan engine, data model, wxWidgets UI,
and the `miner_probe` CLI (the other `crates/alkane-*` are early scaffolding).
- `vendor/asic-rs` -- the miner-discovery and control library, vendored and
extended through numbered patches under `thirdparty/asic-rs/patches`.
- `thirdparty/wx-rs` -- the patched wxWidgets bridge (see `docs/adr/0002`,
`0003`).
See [`docs/IMPLEMENTATION-PLAN.md`](docs/IMPLEMENTATION-PLAN.md) for the roadmap
and [`docs/aftermarket-parity-roadmap.md`](docs/aftermarket-parity-roadmap.md)
for the firmware config/scan parity work.
## Firmware safety rules
Encoded in code, from alkane-sdk `docs/install-methods.md`:
1. Never write the bootloader or secure region.
2. Verify on a channel the installer does not control.
3. Reboot is root-only; a dropped SSH connection can still be success.
4. A packer is per board; never reuse one across boards.
5. Boot-switch handling is an explicit, verified step.
Installation must follow the [SDK install rules](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/docs/install-methods.md):
use the exact board's packer and boot-switch procedure, verify through an
independent channel, and never write bootloader or secure regions.
## License
Licensed under the [MIT license](LICENSE).
[MIT](LICENSE). Vendored dependencies keep their own terms.
+57 -45
View File
@@ -1,27 +1,8 @@
#!/usr/bin/env python3
"""Compute the weighted-average microbenchmark delta versus the previous release.
Reads the captured stdout of `cargo test ... --ignored --nocapture bench_` (whose
timings are Rust `Duration` Debug strings: "12.3ms", "512us"/"512µs", "840ns",
"1.2s"), compares each bench to a committed baseline of the previous release's
numbers, and prints the time-weighted average change as a signed percentage:
(sum(current) / sum(baseline) - 1) * 100 over benches present in both
Weighting by duration means the slow benches dominate, so the number tracks
overall wall-time change rather than giving a tiny bench equal say. Then the
baseline is rewritten with the current numbers, so the next release compares
against this one ("the previous commit").
Usage:
bench-badge.py --current bench-current.txt --baseline badges/bench-baseline.json
Prints the delta as a plain number (e.g. "-3.2", or "NEW" when there is no
usable baseline) to stdout. The baseline JSON lives under badges/ so committing
it back does not trip compute-version.sh's path-based release bump.
"""
"""Check the Toolkit benchmark suite and compare it with the prior release."""
import argparse
import json
import math
import os
import re
import sys
@@ -29,9 +10,17 @@ import sys
# A Duration Debug token: a number immediately followed by a time unit, with the
# multi-char units listed before the bare "s" so alternation prefers them. The
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching.
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|µs|us|ms|s)(?![a-zA-Z])")
_UNIT_NS = {"ns": 1.0, "us": 1e3, "µs": 1e3, "ms": 1e6, "s": 1e9}
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|\u00b5s|us|ms|s)(?![a-zA-Z])")
_UNIT_NS = {"ns": 1.0, "us": 1e3, "\u00b5s": 1e3, "ms": 1e6, "s": 1e9}
_NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
EXPECTED_BENCHES = {
"bench_verify_artifact", "bench_naming_transforms",
"bench_parse_line_near_max_addrs", "bench_parse_targets_many_ranges_near_cap",
"bench_targets_to_cidrs_large_range", "bench_view_pipeline",
"bench_render_cells", "bench_health_diagnostics",
"bench_view_pipeline_default_sort", "bench_sort_by_each_column",
"bench_view_pipeline_with_filter", "bench_upsert_cold_start_population",
}
def parse_bench(text: str) -> dict:
@@ -44,12 +33,33 @@ def parse_bench(text: str) -> dict:
continue
durs = _DUR.findall(line)
if not durs:
continue
raise ValueError(f"missing timing for {m.group(1)}")
val, unit = durs[-1]
out[m.group(1)] = float(val) * _UNIT_NS[unit]
elapsed = float(val) * _UNIT_NS[unit]
if m.group(1) in out or not math.isfinite(elapsed) or elapsed <= 0:
raise ValueError(f"duplicate or invalid timing for {m.group(1)}")
out[m.group(1)] = elapsed
return out
def require_suite(results: dict) -> dict:
if results.keys() != EXPECTED_BENCHES:
raise ValueError("microbenchmark results differ from the declared suite")
return results
def benchmark_delta(current: dict, baseline: dict) -> float | None:
"""Average each comparable benchmark's percentage improvement."""
if not baseline:
return None
changes = [(baseline[name] - current[name]) / baseline[name]
for name in baseline]
delta = math.fsum(changes) / len(changes) * 100
if not math.isfinite(delta):
raise ValueError("benchmark comparison is not finite")
return delta
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--current", required=True, help="captured bench stdout")
@@ -59,32 +69,34 @@ def main() -> int:
try:
with open(args.current, encoding="utf-8") as fh:
current = parse_bench(fh.read())
except OSError as e:
current = require_suite(parse_bench(fh.read()))
except (OSError, ValueError) as e:
print(f"bench-badge: cannot read current results: {e}", file=sys.stderr)
print("NEW")
return 0
if not current:
print("bench-badge: no bench lines parsed from current results", file=sys.stderr)
print("NEW")
return 0
return 1
baseline = {}
try:
with open(args.baseline, encoding="utf-8") as fh:
baseline = {k: float(v) for k, v in json.load(fh).items()}
except (OSError, ValueError):
baseline = {}
baseline = json.load(fh)
except FileNotFoundError:
pass
except (OSError, ValueError) as e:
print(f"bench-badge: invalid baseline: {e}", file=sys.stderr)
return 1
if (not isinstance(baseline, dict)
or not set(baseline).issubset(current)
or any(not isinstance(value, (int, float)) or isinstance(value, bool)
or not math.isfinite(value) or value <= 0
for value in baseline.values())):
print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr)
return 1
common = [k for k in current if k in baseline and baseline[k] > 0]
if common:
sum_new = sum(current[k] for k in common)
sum_old = sum(baseline[k] for k in common)
delta = (sum_new / sum_old - 1.0) * 100.0 if sum_old > 0 else 0.0
print(f"{delta:.1f}")
else:
print("NEW")
try:
delta = benchmark_delta(current, baseline)
except ValueError as error:
print(f"bench-badge: {error}", file=sys.stderr)
return 1
print("NEW" if delta is None else f"{delta:.1f}")
if not args.no_write:
os.makedirs(os.path.dirname(args.baseline) or ".", exist_ok=True)
+79 -11
View File
@@ -15,6 +15,7 @@ import subprocess
import importlib.util
from urllib.error import HTTPError
from urllib.parse import quote
import yaml
from badge_store import BADGE_BRANCH, publish_file, request_json
from bench_host import identity as benchmark_host
@@ -26,6 +27,12 @@ bench_spec.loader.exec_module(bench_badge)
INDEX = "history/index.json"
MAX_INDEX_ENTRIES = 50
BENCH_INPUT_PATHS = (
"Cargo.toml", "Cargo.lock", ".cargo", "crates", "thirdparty", "vendor",
"rust-toolchain.toml", "ci/bench-badge.py", "ci/bench_host.py",
"ci/ensure-build-deps.sh", "ci/ensure-wx-prefix.sh",
"ci/configure-rust-cache.sh", "ci/wx-cache-key.sh",
)
def read_artifact(api: str, repo: str, token: str, filename: str):
@@ -51,6 +58,8 @@ def valid_benches(metrics: dict) -> dict[str, float]:
def git_distance(ancestor: str, sha: str) -> int | None:
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
return None
result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"),
capture_output=True, text=True, check=False)
if result.returncode != 0:
@@ -60,7 +69,7 @@ def git_distance(ancestor: str, sha: str) -> int | None:
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
def previous_entry(index: dict, sha: str, distance=None, host=None) -> dict | None:
distance = distance or git_distance
choices = []
for entry in index.get("entries", []):
@@ -73,8 +82,41 @@ def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dic
if gap is not None and gap > 0:
choices.append((gap, entry))
if not choices:
return {}
return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"])
return None
return min(choices, key=lambda item: item[0])[1]
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
entry = previous_entry(index, sha, distance, host)
return valid_benches(entry["metrics"]) if entry else {}
def benchmark_build_settings(sha: str, root: Path | str = ".") -> dict:
source = subprocess.check_output(
("git", "show", f"{sha}:.gitea/workflows/release.yml"),
cwd=root, text=True)
job = yaml.load(source, Loader=yaml.BaseLoader)["jobs"]["release"]
commands = {step.get("name", ""): step.get("run") for step in job["steps"]}
selected = ("Install build dependencies", "Configure bounded Rust compiler cache",
"Build wxWidgets (once, then cached)", "Build release", "Microbenchmarks")
return {"image": job["container"]["image"], "env": job.get("env", {}),
"commands": {name: commands.get(name) for name in selected}}
def same_benchmark_inputs(ancestor: str, sha: str, root: Path | str = ".") -> bool:
"""Identify changes that only reroute CI without changing benchmark inputs."""
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ValueError("invalid benchmark comparison commit")
diff = subprocess.run(("git", "diff", "--quiet", ancestor, sha, "--",
*BENCH_INPUT_PATHS), cwd=root, check=False)
if diff.returncode not in (0, 1):
raise ValueError("cannot inspect benchmark input changes")
if diff.returncode == 1:
return False
try:
return benchmark_build_settings(ancestor, root) == benchmark_build_settings(sha, root)
except (KeyError, TypeError, subprocess.CalledProcessError, yaml.YAMLError):
return False
def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict:
@@ -101,6 +143,12 @@ def render_html(index: dict) -> str:
host = entry["metrics"].get("bench_host", {})
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
cells.append(f'<td>{html.escape(str(host_label))}</td>')
context = entry["metrics"].get("bench_context", {})
if isinstance(context, dict) and context.get("schema") == 1:
context_label = "same inputs" if context.get("same_inputs") else "changed inputs"
else:
context_label = "unclassified"
cells.append(f'<td>{context_label}</td>')
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
for name in names]
rows.append("<tr>" + "".join(cells) + "</tr>")
@@ -115,18 +163,20 @@ def render_html(index: dict) -> str:
"th{background:#edf2f6;position:sticky;top:0}a{color:#145a9a}"
".scroll{overflow-x:auto}small{color:#55616d}</style></head><body>"
"<h1>Alkane Toolkit microbenchmarks</h1>"
"<p>Measured on main CI. Lower ns/op is faster. Results depend on runner load and are "
"not board performance. A new benchmark has no earlier comparison.</p>"
"<p>Measured on main CI. Lower ns/op is faster. Runner load affects results. "
"Same inputs marks a repeat of the benchmark source and build settings. "
"A new benchmark has no earlier comparison.</p>"
f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained "
"in the private ci-badges branch.</small></p>"
f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>"
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>{headings}</tr></thead><tbody>{''.join(rows)}"
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>"
f"<th scope=\"col\">Inputs</th>{headings}</tr></thead><tbody>{''.join(rows)}"
"</tbody></table></div></body></html>\n")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("prepare", "publish"))
parser.add_argument("action", choices=("prepare", "publish", "render"))
args = parser.parse_args()
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
@@ -136,13 +186,31 @@ def main() -> None:
if index.get("schema") != 1 or not isinstance(index.get("entries"), list):
raise ValueError("unsupported benchmark history index")
if args.action == "prepare":
baseline = previous_measurement(index, sha, host=benchmark_host())
entry = previous_entry(index, sha, host=benchmark_host())
baseline = valid_benches(entry["metrics"]) if entry else {}
same_inputs = same_benchmark_inputs(entry["sha"], sha) if entry else False
Path("badges").mkdir(exist_ok=True)
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
print(f"Loaded {len(baseline)} prior benchmark measurements")
Path("badges/bench-context.json").write_text(
json.dumps({"schema": 1, "same_inputs": same_inputs,
"baseline_sha": entry["sha"] if entry else None}) + "\n")
print(f"Loaded {len(baseline)} prior benchmark measurements; "
f"same inputs: {str(same_inputs).lower()}")
return
metrics = {"bench_ns_per_op": bench_badge.parse_bench(
Path("bench-current.txt").read_text()), "bench_host": benchmark_host()}
if args.action == "render":
if not index["entries"]:
raise ValueError("no measured benchmark history to publish")
Path("bench-site").mkdir(exist_ok=True)
Path("bench-site/index.html").write_text(render_html(index))
print(f"Rendered {len(index['entries'])} measured benchmark commits")
return
context = json.loads(Path("badges/bench-context.json").read_text())
if (not isinstance(context, dict) or context.get("schema") != 1 or
not isinstance(context.get("same_inputs"), bool)):
raise ValueError("invalid benchmark comparison context")
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
Path("bench-current.txt").read_text())), "bench_host": benchmark_host(),
"bench_context": context}
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
index = updated_index(index, sha, metrics, timestamp)
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Keep Toolkit CI on the verified Alkane runner image."""
from pathlib import Path
import re
import sys
import yaml
ROOT = Path(__file__).resolve().parents[1]
IMAGE = (ROOT / "ci/runner-image.txt").read_text().strip()
def main() -> int:
if not re.fullmatch(
r"gitea\.bluefla\.re/blueflare/alkane-ci@sha256:[0-9a-f]{64}", IMAGE
):
print("Runner image must be pinned by Gitea registry digest", file=sys.stderr)
return 1
for path in sorted((ROOT / ".gitea/workflows").glob("*.yml")):
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
for name, job in workflow.get("jobs", {}).items():
if (job.get("runs-on") in {"alkane-fast", "alkane-pages"}
and "secrets." in str(job)):
print(f"{path.name}: {name} exposes a secret to the fast runner", file=sys.stderr)
return 1
if job.get("runs-on") not in {"alkane-ci", "alkane-fast", "alkane-verify"}:
continue
if job.get("container", {}).get("image") != IMAGE:
print(f"{path.name}: {name} has a different runner image", file=sys.stderr)
return 1
pages = yaml.load(
(ROOT / ".gitea/workflows/bench-pages.yml").read_text(),
Loader=yaml.BaseLoader,
)
if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"]
or pages["jobs"]["publish"].get("runs-on") != "alkane-verify"):
print("Benchmark Pages must follow main CI on the trusted verifier", file=sys.stderr)
return 1
release = yaml.load(
(ROOT / ".gitea/workflows/release.yml").read_text(),
Loader=yaml.BaseLoader,
)
if release["jobs"]["release"].get("runs-on") != "alkane-ci":
print("Main release must use the dedicated Alkane build pool", file=sys.stderr)
return 1
if any("ci/publish-bench-pages.py" in step.get("run", "")
for step in release["jobs"]["release"]["steps"]):
print("Main release must not publish Pages from GARM", file=sys.stderr)
return 1
source = yaml.load(
(ROOT / ".gitea/workflows/source.yml").read_text(),
Loader=yaml.BaseLoader,
)
triggers = source["on"]
if (triggers.get("pull_request", {}).get("branches") != ["next"]
or "push" in triggers or "workflow_dispatch" not in triggers):
print("Source checks must not duplicate main pull request verification",
file=sys.stderr)
return 1
print("Toolkit runner image pins: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Avoid a runner-local cache download when the pinned image has this source.
# check-wx-image-prefix.sh [linux|windows]
set -euo pipefail
case "${1:-linux}" in
linux) prefix="${WX_PREFIX:?WX_PREFIX is required}"; library=lib/libwx_gtk3u-3.3.a ;;
windows) prefix="${WX_WINDOWS_PREFIX:?WX_WINDOWS_PREFIX is required}"
library=lib/libwx_mswu-3.3-x86_64-w64-mingw32.a ;;
*) echo "unknown wx platform: $1" >&2; exit 2 ;;
esac
expected="$(awk '$1 == "sha256:" {print $2}' thirdparty/wxwidgets/VERSION)"
[[ "$expected" =~ ^[0-9a-f]{64}$ ]]
available=false
if [ ! -L "$prefix" ] && [ ! -L "$prefix/.alkane-source-sha256" ] &&
[ -x "$prefix/bin/wx-config" ] &&
[ -s "$prefix/$library" ] &&
[ "$(cat "$prefix/.alkane-source-sha256" 2>/dev/null || true)" = "$expected" ]; then
available=true
fi
printf 'available=%s\n' "$available" >> "${GITHUB_OUTPUT:?GITHUB_OUTPUT is required}"
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Remove generated Toolkit CI work after the release asset is uploaded."""
import os
from pathlib import Path
import shutil
import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
FILES = ("bench-current.txt",)
BADGE_FILES = ("bench-baseline.json", "bench-context.json")
def cleanup() -> None:
if not os.environ.get("GITHUB_RUN_ID"):
raise ValueError("cleanup is restricted to CI runs")
for name in DIRECTORIES:
path = ROOT / name
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
raise ValueError(f"unsafe generated directory: {path}")
if path.is_dir():
shutil.rmtree(path)
print(f"Removed generated directory: {name}")
elif path.exists():
raise ValueError(f"expected a generated directory: {path}")
for name in FILES:
path = ROOT / name
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
raise ValueError(f"unsafe generated file: {path}")
if path.is_file():
path.unlink()
print(f"Removed generated file: {name}")
badge_dir = ROOT / "badges"
if badge_dir.is_symlink():
raise ValueError("unsafe generated badge directory")
for name in BADGE_FILES:
path = badge_dir / name
if path.is_symlink() or path.parent.resolve() != badge_dir.resolve():
raise ValueError(f"unsafe generated badge file: {path}")
if path.is_file():
path.unlink()
print(f"Removed generated badge file: {name}")
if __name__ == "__main__":
try:
cleanup()
except (OSError, ValueError) as error:
print(f"ERROR: Toolkit cleanup: {error}", file=sys.stderr)
raise SystemExit(1)
+6 -2
View File
@@ -36,10 +36,14 @@ crates/alkane-gui/src/bin/*)
ui=true ;;
crates/alkane-core/*|crates/alkane-discovery/*|crates/alkane-access/*|\
crates/alkane-flash/*|crates/alkane-artifacts/*|crates/alkane-cli/*|\
crates/alkane-gui/src/*|Cargo.toml|Cargo.lock|.gitea/*|ci/*|scripts/*|\
crates/alkane-gui/src/*|crates/alkane-gui/Cargo.toml|crates/alkane-gui/build.rs|\
crates/alkane-gui/windows/*|crates/alkane-gui/assets/*|\
Cargo.toml|Cargo.lock|.gitea/*|ci/*|scripts/*|\
vendor/*|thirdparty/asic-rs/*)
# Any other GUI source file (naming, scan, model, pool_prefs, restore,
# access_probe, credentials, ...) is backend logic. ui.rs/fixtures.rs/bin
# access_probe, credentials, ...) is backend logic, as is how the binary
# is built and packaged (build.rs, the Windows manifest/icon/version
# resources, embedded assets). ui.rs/fixtures.rs/bin
# match the UI arm above first, so they still bump Z, not Y.
backend=true ;;
*) : ;; # docs, HANDOFF, README, thirdparty/wxwidgets tree: no bump
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Reuse Rust compiler results on persistent CI runners.
set -euo pipefail
[ "$(sccache --version)" = 'sccache 0.18.0' ] || {
echo 'CI image has an unexpected sccache version' >&2
exit 1
}
toolcache="${RUNNER_TOOL_CACHE:-}"
if [ -z "$toolcache" ] || [ -L "$toolcache" ] ||
[ ! -d "$toolcache" ] || [ ! -w "$toolcache" ]; then
echo 'Persistent runner tool cache is unavailable; compiling without sccache'
exit 0
fi
cache_dir="$toolcache/alkane-toolkit-rust-sccache"
if [ -L "$cache_dir" ]; then
echo 'Rust cache path is a symlink' >&2
exit 1
fi
umask 077
mkdir -p "$cache_dir"
if [ ! -d "$cache_dir" ] || [ ! -w "$cache_dir" ]; then
echo 'Rust cache directory is unavailable' >&2
exit 1
fi
chmod 0700 "$cache_dir"
{
printf 'RUSTC_WRAPPER=%s\n' "$(command -v sccache)"
printf 'SCCACHE_DIR=%s\n' "$cache_dir"
printf 'SCCACHE_CACHE_SIZE=2G\n'
printf 'CARGO_INCREMENTAL=0\n'
} >> "${GITHUB_ENV:?GITHUB_ENV is required}"
echo 'Bounded Rust compiler cache configured for Alkane Toolkit'
+15 -14
View File
@@ -2,10 +2,11 @@
# Measure line coverage from BOTH the unit tests AND the headless UI self-test.
#
# The self-test (ALKANE_SELFTEST=1) builds the real wxWidgets table, renders every
# fixture through the real widgets, and checks each cell against the model -- it
# exercises most of ui.rs. Because it runs as a separate binary invocation, a plain
# `cargo llvm-cov` (which only runs the #[test]s) never counts it, so ui.rs shows
# ~4% even though it is integration-tested. This combines both runs' coverage.
# fixture through the real widgets, and checks each cell against the model.
# It covers the fixture-rendering path, while interactive event handlers need
# separate tests. Because it runs as a separate binary invocation, a plain
# `cargo llvm-cov` (which only runs the #[test]s) never counts it. This
# combines both runs' coverage.
#
# Usage: ci/coverage.sh [extra `cargo llvm-cov report` args, e.g. --summary-only]
set -euo pipefail
@@ -16,23 +17,23 @@ export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$HOME/.cache/wx-3.3.3-linux/bin/wx-conf
# default; override with CARGO_LLVM_COV_FLAGS if you need something else.
read -ra CARGO_FLAGS <<<"${CARGO_LLVM_COV_FLAGS:---offline}"
# A display for the self-test's real widgets.
need_xvfb() { command -v xvfb-run >/dev/null 2>&1; }
# A display is required for the self-test; skipping it would publish an
# incomplete coverage number as if the measured test set had run.
if ! command -v xvfb-run >/dev/null 2>&1; then
echo "coverage.sh: xvfb-run is required for the UI self-test" >&2
exit 1
fi
cargo llvm-cov clean --workspace
# 1. Unit tests for the GUI and the artifact/flash/CLI crates.
# 1. Unit tests for the GUI and all first-party headless crates.
cargo llvm-cov --no-report "${CARGO_FLAGS[@]}" -p alkane-gui --bin alkane-toolkit
cargo llvm-cov --no-report "${CARGO_FLAGS[@]}" \
-p alkane-artifacts -p alkane-flash -p alkane-cli
--workspace --exclude alkane-gui --exclude wx-rs
# 2. Headless UI self-test, under the same instrumentation, its coverage appended.
if need_xvfb; then
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
cargo llvm-cov run --no-report "${CARGO_FLAGS[@]}" --bin alkane-toolkit
else
echo "coverage.sh: xvfb-run not found; skipping the self-test run (unit tests only)" >&2
fi
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
cargo llvm-cov run --no-report "${CARGO_FLAGS[@]}" --bin alkane-toolkit
# 3. Merged report, our source only (vendored asic-rs + the patched wx-rs bridge
# are out of scope).
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Use the preinstalled CI image or install missing packages on older runners.
set -euo pipefail
mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows}"
case "$mode" in
base) packages=(libssl-dev pkg-config ca-certificates) ;;
ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;;
ssh) packages=(openssh-client) ;;
all) packages=(libssl-dev pkg-config ca-certificates openssh-client
xvfb xauth dbus-x11 fonts-dejavu-core) ;;
# Windows cross build (mingw-w64, posix threads) + Wine for its tests.
windows) packages=(libssl-dev pkg-config ca-certificates
gcc-mingw-w64-x86-64-posix g++-mingw-w64-x86-64-posix
binutils-mingw-w64-x86-64 mingw-w64-x86-64-dev wine wine64 xvfb xauth
openjdk-21-jre-headless) ;;
*) echo "unknown dependency set: $mode" >&2; exit 2 ;;
esac
installed="$(dpkg-query -W -f='${Package} ${Status}\n' "${packages[@]}" 2>/dev/null || true)"
missing=()
for package in "${packages[@]}"; do
if ! grep -Fxq "$package install ok installed" <<< "$installed"; then
missing+=("$package")
fi
done
if [ "${#missing[@]}" -eq 0 ]; then
printf 'Build packages already installed: %s\n' "$mode"
exit 0
fi
printf 'Installing %s missing build packages\n' "${#missing[@]}"
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends "${packages[@]}"
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Use the matching image or cache prefix; rebuild after a vendored source bump.
# ensure-wx-prefix.sh [linux|windows] (default linux: wxGTK in $WX_PREFIX;
# windows: the mingw wxMSW prefix in $WX_WINDOWS_PREFIX)
set -euo pipefail
platform="${1:-linux}"
case "$platform" in
linux)
prefix="${WX_PREFIX:?WX_PREFIX is required}"
allowed=/root/.cache/wx-3.3.3-linux
library=lib/libwx_gtk3u-3.3.a
build=scripts/build-wx-linux.sh ;;
windows)
prefix="${WX_WINDOWS_PREFIX:?WX_WINDOWS_PREFIX is required}"
allowed=/root/.cache/wx-3.3.3-mingw
library=lib/libwx_mswu-3.3-x86_64-w64-mingw32.a
build=scripts/build-wx-windows.sh ;;
*) echo "unknown wx platform: $platform" >&2; exit 2 ;;
esac
if [ -L "$prefix" ] || [ -L "$prefix/.alkane-source-sha256" ]; then
echo 'refusing symlinked wxWidgets prefix or source marker' >&2
exit 1
fi
expected="$(awk '$1 == "sha256:" {print $2}' thirdparty/wxwidgets/VERSION)"
[[ "$expected" =~ ^[0-9a-f]{64}$ ]] || {
echo 'invalid pinned wxWidgets source digest' >&2
exit 1
}
marker="$prefix/.alkane-source-sha256"
if [ -e "$marker" ] && [ "$(cat "$marker")" != "$expected" ]; then
python3 - "$prefix" "$allowed" <<'PY'
from pathlib import Path
import shutil
import sys
prefix = Path(sys.argv[1])
allowed = Path(sys.argv[2])
if prefix != allowed or prefix.is_symlink():
raise SystemExit('refusing unsafe wxWidgets prefix reset')
if prefix.is_dir():
shutil.rmtree(prefix)
PY
fi
built=false
if [ ! -x "$prefix/bin/wx-config" ] ||
[ ! -s "$prefix/$library" ]; then
WX_WINDOWS_PREFIX="$prefix" sh "$build"
built=true
else
echo 'wx prefix available from matching image or cache'
fi
[ -s "$prefix/$library" ]
printf '%s\n' "$expected" > "$marker"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
printf 'built=%s\n' "$built" >> "$GITHUB_OUTPUT"
fi
+39 -29
View File
@@ -11,8 +11,10 @@ Metrics not passed on the command line are computed here (LOC from the source
tree, dependency count from Cargo.lock, license from Cargo.toml).
"""
import argparse
import json
import math
import os
from pathlib import Path
import re
import sys
@@ -38,7 +40,8 @@ def text_width(s: str) -> float:
return len(s) * CHAR_W + 2 * PAD
def badge_svg(label: str, message: str, color: str) -> str:
def badge_svg(label: str, message: str, color: str,
description: str | None = None) -> str:
color = COLORS.get(color, color)
lw = round(text_width(label), 1)
mw = round(text_width(message), 1)
@@ -46,8 +49,9 @@ def badge_svg(label: str, message: str, color: str) -> str:
lx = round(lw / 2, 1)
mx = round(lw + mw / 2, 1)
# Text is drawn twice (a dark shadow then the light glyphs) for the shields look.
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{label}: {message}">
<title>{label}: {message}</title>
description = description or f"{label}: {message}"
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{description}">
<title>{description}</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -108,13 +112,13 @@ def loc_color(n: int) -> str:
def bench_color(delta_pct: float) -> str:
# Negative delta = faster than the previous release. A +/-2% dead band absorbs
# the run-to-run jitter of microbenchmarks on a shared CI runner.
if delta_pct <= -2.0:
# Positive delta means faster than the previous release. A +/-2% band
# absorbs run-to-run jitter on the dedicated CI runner.
if delta_pct >= 2.0:
return "brightgreen"
if delta_pct < 2.0:
if delta_pct > -2.0:
return "blue"
if delta_pct < 10.0:
if delta_pct > -10.0:
return "yellow"
return "orange"
@@ -131,15 +135,10 @@ def cov_color(pct: float) -> str:
return "red"
def quality_grade(clippy: str, coverage: float | None) -> str:
if clippy != "clean":
return "F"
if coverage is None:
def quality_grade(clippy: str | None) -> str:
if clippy is None:
return "pending"
for minimum, grade in ((90, "A"), (80, "B"), (70, "C"), (60, "D")):
if coverage >= minimum:
return grade
return "F"
return "A" if clippy == "clean" else "F"
def human(n: int) -> str:
@@ -166,11 +165,10 @@ def main() -> int:
ap.add_argument("--coverage", type=float, default=None)
ap.add_argument("--bench-coverage", type=float, default=None)
ap.add_argument("--bench", default=None)
# Weighted-average microbench delta vs the previous release, as a signed
# percentage string (e.g. "-3.2"), or "NEW"/"" when there is no baseline yet
# (round 19 #1). Takes precedence over --bench for the bench badge.
# Mean per-benchmark improvement vs the previous release, as a signed
# percentage string, or "NEW" when there is no baseline.
ap.add_argument("--bench-delta", default=None)
ap.add_argument("--clippy", default="clean")
ap.add_argument("--clippy", choices=("clean", "failed"))
args = ap.parse_args()
for value in (args.coverage, args.bench_coverage):
if value is not None and (not math.isfinite(value) or not 0 <= value <= 100):
@@ -178,10 +176,10 @@ def main() -> int:
os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
def write(name, label, message, color):
def write(name, label, message, color, description=None):
path = os.path.join(args.root, args.out, name + ".svg")
with open(path, "w", encoding="utf-8") as fh:
fh.write(badge_svg(label, message, color))
fh.write(badge_svg(label, message, color, description))
print(f"wrote {path}: {label}={message}")
loc = count_loc(args.root)
@@ -191,10 +189,11 @@ def main() -> int:
write("loc", "lines of code", human(loc), loc_color(loc))
write("license", "license", lic, "blue")
write("dependencies", "dependencies", str(deps), "blue")
grade = quality_grade(args.clippy, args.coverage)
grade = quality_grade(args.clippy)
write("quality", "code quality", grade,
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
"D": "orange", "F": "red", "pending": "lightgrey"}[grade])
"D": "orange", "F": "red", "pending": "lightgrey"}[grade],
f"code quality: {grade} (GUI Clippy and first-party rustfmt)")
if args.tests is not None:
write("tests", "tests", f"{args.tests} passing", "brightgreen")
if args.coverage is not None:
@@ -202,8 +201,16 @@ def main() -> int:
write("bench-coverage", "bench coverage",
f"{args.bench_coverage:.0f}%" if args.bench_coverage is not None else "pending",
cov_color(args.bench_coverage) if args.bench_coverage is not None else "lightgrey")
# Bench badge: prefer the weighted-average delta vs the previous release; fall
# back to the static label (first run, or when the delta could not be computed).
context_path = Path(args.root) / args.out / "bench-context.json"
same_inputs = False
if context_path.is_file():
context = json.loads(context_path.read_text())
if (not isinstance(context, dict) or context.get("schema") != 1 or
not isinstance(context.get("same_inputs"), bool)):
raise ValueError("invalid benchmark comparison context")
same_inputs = context["same_inputs"]
# Bench badge: prefer the mean per-benchmark improvement vs the previous
# release. Use the static label when no comparison is available.
delta = None
if args.bench_delta not in (None, "", "NEW"):
try:
@@ -211,9 +218,12 @@ def main() -> int:
except ValueError:
delta = None
if delta is not None:
# Negative = faster than the previous release (good).
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
write("bench", "bench", msg, bench_color(delta))
# Positive = faster than the previous release.
msg = f"{'+' if delta > 0 else ''}{delta:.1f}%"
if same_inputs:
write("bench", "bench", msg + " same inputs", "lightgrey")
else:
write("bench", "bench", msg + " vs prev", bench_color(delta))
elif args.bench_delta == "NEW":
write("bench", "bench", "baseline set", "blue")
elif args.bench is not None:
+59
View File
@@ -0,0 +1,59 @@
# syntax=docker/dockerfile:1
# Alkane Toolkit CI image (ci/runner-image.txt pins the pushed digest).
#
# Layered on the previously verified image, so every Linux job keeps exactly
# the toolchain it had (Rust 1.97.1, prebuilt wxGTK prefix, sccache,
# cargo-llvm-cov), and adds what the Windows jobs need:
# - mingw-w64 (posix threads) and the rustup target x86_64-pc-windows-gnu
# - a prebuilt static wxMSW 3.3.3 prefix, built from the vendored source by
# scripts/build-wx-windows.sh and stamped with the source digest the same
# way as the wxGTK prefix (ci/ensure-wx-prefix.sh rebuilds on a mismatch)
# - Wine with an initialised prefix, to run the Windows tests and self-test
# - a Java runtime and jsign (checksum-pinned), to Authenticode-sign the .exe
# through Azure Artifact Signing (ci/sign-windows.sh)
#
# Build and push from the workstation with ci/images/build-image.sh.
ARG BASE=gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
FROM ${BASE}
RUN DEBIAN_FRONTEND=noninteractive apt-get update -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
gcc-mingw-w64-x86-64-posix g++-mingw-w64-x86-64-posix \
binutils-mingw-w64-x86-64 mingw-w64-x86-64-dev \
wine wine64 xvfb xauth openjdk-21-jre-headless \
&& rm -rf /var/lib/apt/lists/*
# jsign (Maven Central net.jsign:jsign; keep in step with ci/windows-ci.sh).
ARG JSIGN_VERSION=7.6
ARG JSIGN_SHA256=6cf58aa080e7ff82656f320cff8d4a3bff30408df8766806dcba3740dd839fa5
RUN mkdir -p /opt/jsign \
&& curl -sSfL -o /opt/jsign/jsign.jar \
"https://repo1.maven.org/maven2/net/jsign/jsign/${JSIGN_VERSION}/jsign-${JSIGN_VERSION}.jar" \
&& echo "${JSIGN_SHA256} /opt/jsign/jsign.jar" | sha256sum -c - \
&& java -jar /opt/jsign/jsign.jar --help >/dev/null
RUN rustup target add x86_64-pc-windows-gnu
# The build context is the repository root, filtered by
# alkane-ci.Dockerfile.dockerignore down to the wx source and its build script.
COPY thirdparty/wxwidgets /tmp/alkane/thirdparty/wxwidgets
COPY scripts/build-wx-windows.sh /tmp/alkane/scripts/build-wx-windows.sh
RUN HOME=/root WX_WINDOWS_PREFIX=/root/.cache/wx-3.3.3-mingw \
sh /tmp/alkane/scripts/build-wx-windows.sh \
&& awk '$1 == "sha256:" {print $2}' /tmp/alkane/thirdparty/wxwidgets/VERSION \
> /root/.cache/wx-3.3.3-mingw/.alkane-source-sha256 \
&& rm -rf /tmp/alkane
# A ready Wine prefix saves ~10 s per job (scripts/wine-run.sh reuses it).
RUN WINEPREFIX=/root/.cache/alkane-wine WINEDEBUG=-all \
WINEDLLOVERRIDES='winemenubuilder.exe=d;mscoree=d;mshtml=d' \
sh -c 'wineboot --init; wineboot --shutdown; wineserver -w' >/dev/null 2>&1; \
test -f /root/.cache/alkane-wine/system.reg
RUN test -s /root/.cache/wx-3.3.3-mingw/lib/libwx_mswu-3.3-x86_64-w64-mingw32.a \
&& test "$(/root/.cache/wx-3.3.3-mingw/bin/wx-config --version)" = 3.3.3 \
&& test -s /root/.cache/wx-3.3.3-linux/lib/libwx_gtk3u-3.3.a \
&& x86_64-w64-mingw32-g++-posix --version >/dev/null \
&& wine --version \
&& test -s /opt/jsign/jsign.jar \
&& rustup target list --installed | grep -qx x86_64-pc-windows-gnu
@@ -0,0 +1,4 @@
# Only what the image build copies: the vendored wx tree and its build script.
*
!thirdparty/wxwidgets/**
!scripts/build-wx-windows.sh
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Build the CI image from ci/images/alkane-ci.Dockerfile, push it to the Gitea
# registry, and pin the pushed digest in ci/runner-image.txt and every
# workflow (ci/check-runner-image.py enforces the pin).
#
# Run on the workstation, which holds the registry credential; it is passed to
# a throwaway Docker config that is deleted afterwards, never to a runner.
# ci/images/build-image.sh TAG e.g. ci/images/build-image.sh windows-2026-11-02
set -eu
TAG=${1:?usage: build-image.sh TAG}
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
REGISTRY=gitea.bluefla.re
IMAGE=$REGISTRY/blueflare/alkane-ci
TOKEN_FILE=${GITEA_TOKEN_FILE:-$HOME/.config/gitea/token}
cd "$REPO"
DOCKER_CONFIG=$(mktemp -d)
export DOCKER_CONFIG
trap 'rm -rf "$DOCKER_CONFIG"' 0
user=$(curl -sS --config - "https://$REGISTRY/api/v1/user" <<CFG | python3 -c 'import json,sys; print(json.load(sys.stdin)["login"])'
header = "Authorization: token $(cat "$TOKEN_FILE")"
CFG
)
docker login "$REGISTRY" -u "$user" --password-stdin < "$TOKEN_FILE" >/dev/null
DOCKER_BUILDKIT=1 docker build -f ci/images/alkane-ci.Dockerfile -t "$IMAGE:$TAG" .
docker push "$IMAGE:$TAG" >/dev/null
digest=$(docker inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE:$TAG" \
| grep "^$IMAGE@sha256:" | head -1)
[ -n "$digest" ] || { echo "no registry digest for $IMAGE:$TAG" >&2; exit 1; }
old=$(cat ci/runner-image.txt)
printf '%s\n' "$digest" > ci/runner-image.txt
grep -rl "$old" .gitea/workflows | while read -r f; do
python3 - "$f" "$old" "$digest" <<'PY'
import pathlib, sys
p, old, new = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3]
p.write_text(p.read_text().replace(old, new))
PY
done
python3 ci/check-runner-image.py
echo "pinned $digest"
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Package the cross-built Windows toolkit for release and for native testing.
package-windows.py release VERSION EXE OUT_DIR
dist/alkane-toolkit-vVERSION-windows-x86_64.zip: one folder holding
alkane-toolkit.exe, LICENSE and a README.txt. Prints the zip path.
package-windows.py tests CARGO_JSON OUT_ZIP
A bundle of the test executables `cargo test --no-run
--message-format=json` reported (CARGO_JSON is that output), plus
tests.txt naming each one. The native Windows job runs every listed
executable on real Windows; the same binaries already ran under Wine.
"""
import json
import pathlib
import struct
import sys
import zipfile
ROOT = pathlib.Path(__file__).resolve().parents[1]
TARGET = "x86_64-pc-windows-gnu"
def release(version: str, exe: str, out_dir: str) -> None:
exe_path = pathlib.Path(exe)
if exe_path.suffix != ".exe" or not exe_path.is_file():
sys.exit(f"not a Windows executable: {exe}")
signed = _has_authenticode_signature(exe_path)
name = f"alkane-toolkit-v{version}-windows-x86_64"
out = pathlib.Path(out_dir) / f"{name}.zip"
out.parent.mkdir(parents=True, exist_ok=True)
readme = (
f"alkane-toolkit v{version} (Windows x86_64)\r\n"
"\r\n"
"Run alkane-toolkit.exe. No installer and no extra runtime are needed:\r\n"
"the executable is self-contained and runs on Windows 10 and 11.\r\n"
"\r\n"
+ (
"The executable is signed by Blueflare (Azure Artifact Signing). To check:\r\n"
"right-click alkane-toolkit.exe > Properties > Digital Signatures.\r\n"
if signed else
"This build is not code-signed, so Windows SmartScreen may warn on first\r\n"
"run: choose More info > Run anyway.\r\n"
)
+ "\r\n"
"Settings are kept in %APPDATA%\\alkane-toolkit.\r\n"
"SSH-based actions use the OpenSSH client built into Windows (ssh.exe);\r\n"
"HTTP actions use curl.exe, also built in.\r\n"
"\r\n"
"Offline demo: run from a Command Prompt with\r\n"
" set ALKANE_FAKE_SCAN=1 && alkane-toolkit.exe\r\n"
)
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
z.write(exe_path, f"{name}/alkane-toolkit.exe")
z.write(ROOT / "LICENSE", f"{name}/LICENSE.txt")
z.writestr(f"{name}/README.txt", readme)
print(out)
def _has_authenticode_signature(exe: pathlib.Path) -> bool:
"""True if the PE file carries a certificate table (an Authenticode signature)."""
data = exe.read_bytes()
pe = struct.unpack_from("<I", data, 0x3C)[0]
magic = struct.unpack_from("<H", data, pe + 24)[0]
dirs = pe + 24 + (96 if magic == 0x10B else 112)
return struct.unpack_from("<II", data, dirs + 4 * 8)[1] > 0
def tests(cargo_json: str, out_zip: str) -> None:
executables = []
for line in pathlib.Path(cargo_json).read_text().splitlines():
try:
message = json.loads(line)
except json.JSONDecodeError:
continue
if (message.get("reason") == "compiler-artifact"
and message.get("profile", {}).get("test")
and message.get("executable")):
executables.append(pathlib.Path(message["executable"]))
executables = sorted(set(executables))
if not executables:
sys.exit("no test executables in the cargo output")
out = pathlib.Path(out_zip)
out.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
names = []
for exe in executables:
if exe.suffix != ".exe" or TARGET not in exe.parts:
sys.exit(f"not a {TARGET} test executable: {exe}")
z.write(exe, exe.name)
names.append(exe.name)
z.writestr("tests.txt", "\n".join(names) + "\n")
print(f"{out} ({len(executables)} test executables)")
def main() -> None:
if len(sys.argv) == 5 and sys.argv[1] == "release":
release(*sys.argv[2:])
elif len(sys.argv) == 4 and sys.argv[1] == "tests":
tests(*sys.argv[2:])
else:
sys.exit(__doc__)
if __name__ == "__main__":
main()
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Classify a pull request for scoped CI checks."""
import os
from pathlib import Path
import subprocess
import sys
import tomllib
ROOT = Path(__file__).resolve().parents[1]
DOC_FILES = {"README.md", "CONTRIBUTING.md", "CHANGELOG.md"}
HEADLESS_CRATES = {"alkane-access", "alkane-artifacts", "alkane-cli", "alkane-flash"}
def documentation_only(paths: list[str]) -> bool:
return bool(paths) and all(
path in DOC_FILES or
(path.startswith("docs/") and Path(path).suffix in {".md", ".txt"})
for path in paths
)
def workflow_only(paths: list[str]) -> bool:
"""Limit the cheap PR check to workflow YAML, never policy code."""
return bool(paths) and all(
path.startswith(".gitea/workflows/") and
len(Path(path).parts) == 3 and Path(path).suffix == ".yml"
for path in paths
)
def headless_packages(paths: list[str]) -> list[str]:
"""Return tested reverse dependents for code outside the GUI graph."""
changed: set[str] = set()
if not paths:
return []
for path in paths:
parts = Path(path).parts
if (len(parts) < 4 or parts[0] != "crates" or
parts[1] not in HEADLESS_CRATES or
parts[2] not in {"src", "tests"} or
Path(path).suffix != ".rs"):
return []
changed.add(parts[1])
try:
manifests = {}
for path in (ROOT / "crates").glob("*/Cargo.toml"):
manifest = tomllib.loads(path.read_text())
name = manifest["package"]["name"]
if name != path.parent.name:
return []
manifests[name] = manifest
if not changed <= manifests.keys() or "alkane-gui" not in manifests:
return []
def dependencies(value: object) -> set[str]:
found: set[str] = set()
if isinstance(value, dict):
for key, nested in value.items():
if key in {"dependencies", "dev-dependencies", "build-dependencies"}:
for dep_name, spec in nested.items():
found.add(spec.get("package", dep_name) if isinstance(spec, dict)
else dep_name)
else:
found.update(dependencies(nested))
return found & manifests.keys()
graph = {name: dependencies(manifest) for name, manifest in manifests.items()}
affected = changed.copy()
while True:
added = {name for name, deps in graph.items() if deps & affected} - affected
if not added:
break
affected.update(added)
return [] if "alkane-gui" in affected else sorted(affected)
except (OSError, KeyError, TypeError, ValueError):
return []
def changed_paths() -> list[str]:
if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
raise ValueError("not a pull request")
if os.environ.get("GITHUB_BASE_REF") != "main":
raise ValueError("unknown base branch")
merge_base = subprocess.check_output(
["git", "-C", str(ROOT), "merge-base", "HEAD",
"refs/remotes/origin/main"],
stderr=subprocess.DEVNULL, text=True,
).strip()
if len(merge_base) != 40:
raise ValueError("missing merge base")
raw = subprocess.check_output(
["git", "-C", str(ROOT), "diff", "--no-renames", "--name-only", "-z",
merge_base, "HEAD"], stderr=subprocess.DEVNULL,
)
return [path.decode("utf-8", "surrogateescape")
for path in raw.split(b"\0") if path]
def main() -> None:
try:
paths = changed_paths()
docs = documentation_only(paths)
workflow = workflow_only(paths) if not docs else False
packages = headless_packages(paths) if not docs and not workflow else []
except (OSError, subprocess.CalledProcessError, ValueError):
paths = []
docs = False
workflow = False
packages = []
surface = ("documentation" if docs else "workflow" if workflow else
"headless" if packages else "full")
print(f"surface={surface}")
print(f"packages={' '.join(packages)}")
print(f"Changed paths: {len(paths)}", file=sys.stderr)
if __name__ == "__main__":
main()
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish a measured benchmark page to the public, data-only Pages repo."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
import tempfile
from urllib.request import Request, urlopen
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
PAGES_HOST = "gitea.bluefla.re"
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
def run(*args: str, env: dict[str, str] | None = None,
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, env=env, cwd=cwd, text=True,
capture_output=True, check=True)
def current_main_sha() -> str:
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
request = Request(f"{api}/repos/{repo}/branches/main",
headers={"Authorization": f"token {token}"})
with urlopen(request, timeout=20) as response:
branch = json.load(response)
return branch["commit"]["id"]
def publish(site: str) -> None:
if os.environ.get("GITHUB_REF") != "refs/heads/main":
raise ValueError("benchmark Pages publication requires main")
sha = os.environ["GITHUB_SHA"]
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
page = Path("bench-site/index.html").read_bytes()
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
raise ValueError("invalid benchmark page")
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
temporary = Path(directory)
guard_checkout = temporary / "guard"
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
GUARD_REPO, str(guard_checkout))
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
cwd=guard_checkout).stdout
guard_script = temporary / "validate_site.py"
guard_script.write_text(guard_source)
run("python3", str(guard_script), "--page", site,
str(Path("bench-site/index.html").resolve()))
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
raise ValueError("missing benchmark Pages deploy key")
key_path = temporary / "deploy_key"
key_path.write_text(key.rstrip("\n") + "\n")
key_path.chmod(0o600)
known_hosts = temporary / "known_hosts"
known_hosts.write_text(PAGES_HOST_KEY + "\n")
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
if fingerprint != PAGES_HOST_FINGERPRINT:
raise ValueError("benchmark Pages SSH host key changed")
git_env = os.environ.copy()
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
git_env["GIT_SSH_COMMAND"] = ssh_command
git_env["GIT_TERMINAL_PROMPT"] = "0"
checkout = temporary / "site"
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
PAGES_REPO, str(checkout), env=git_env)
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
for attempt in range(3):
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
cwd=checkout)
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
cwd=checkout)
destination = checkout / site / "index.html"
destination.parent.mkdir(exist_ok=True)
destination.write_bytes(page)
run("git", "add", f"{site}/index.html", cwd=checkout)
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
cwd=checkout, check=False)
if changed.returncode == 0:
print(f"{site} benchmark page is already current")
return
if changed.returncode != 1:
raise RuntimeError("cannot compare benchmark page")
run("git", "commit", "-q", "-m",
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
pushed = subprocess.run(("git", "push", "--quiet", "origin",
"HEAD:gh-pages"), env=git_env, cwd=checkout,
text=True, capture_output=True, check=False)
if pushed.returncode == 0:
print(f"Published {site} benchmark page for {sha[:10]}")
return
if attempt == 2:
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
raise RuntimeError("benchmark Pages publication did not complete")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
publish(parser.parse_args().site)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Authenticode-sign Windows executables with Azure Artifact Signing (formerly
# Trusted Signing), from Linux, with jsign. Every signature is RFC 3161
# timestamped: the signing certificates live only a few days, the timestamp is
# what keeps a signature valid after that.
#
# ci/sign-windows.sh FILE.exe [FILE.exe ...]
#
# Configuration (environment):
# AZURE_SIGNING_PROFILE certificate profile name; EMPTY = signing not set
# up yet: the files are left unsigned (exit 0)
# AZURE_SIGNING_ACCOUNT signing account (default blueflaresigning)
# AZURE_SIGNING_ENDPOINT account endpoint (default https://wus2.codesigning.azure.net)
# Credentials, one of:
# AZURE_SIGNING_TENANT_ID + AZURE_SIGNING_CLIENT_ID + AZURE_SIGNING_CLIENT_SECRET
# (the CI service principal alkane-toolkit-ci-signer, role
# "Artifact Signing Certificate Profile Signer" on the account only)
# AZURE_SIGNING_TOKEN an access token for https://codesigning.azure.net,
# e.g. from `az account get-access-token --resource https://codesigning.azure.net`
# ALKANE_JSIGN_JAR jsign jar (default /opt/jsign/jsign.jar, from the CI image)
#
# Once a profile is configured, any failure fails the job: a release is never
# shipped half-signed or silently unsigned.
set -euo pipefail
[ "$#" -gt 0 ] || { sed -n '3,25p' "$0" >&2; exit 2; }
profile="${AZURE_SIGNING_PROFILE:-}"
if [ -z "$profile" ]; then
echo "Windows code signing is not enabled (AZURE_SIGNING_PROFILE unset); leaving $* unsigned"
exit 0
fi
account="${AZURE_SIGNING_ACCOUNT:-blueflaresigning}"
endpoint="${AZURE_SIGNING_ENDPOINT:-https://wus2.codesigning.azure.net}"
jar="${ALKANE_JSIGN_JAR:-/opt/jsign/jsign.jar}"
[ -f "$jar" ] || { echo "jsign not found at $jar" >&2; exit 1; }
if [ -z "${AZURE_SIGNING_TOKEN:-}" ]; then
: "${AZURE_SIGNING_TENANT_ID:?signing credentials missing}"
: "${AZURE_SIGNING_CLIENT_ID:?signing credentials missing}"
: "${AZURE_SIGNING_CLIENT_SECRET:?signing credentials missing}"
# Client-credentials token for the signing service. The secret and token
# stay in this process's environment, never on a command line.
AZURE_SIGNING_TOKEN="$(python3 - <<'PY'
import json, os, sys, urllib.parse, urllib.request
body = urllib.parse.urlencode({
"grant_type": "client_credentials",
"client_id": os.environ["AZURE_SIGNING_CLIENT_ID"],
"client_secret": os.environ["AZURE_SIGNING_CLIENT_SECRET"],
"scope": "https://codesigning.azure.net/.default",
}).encode()
url = f"https://login.microsoftonline.com/{os.environ['AZURE_SIGNING_TENANT_ID']}/oauth2/v2.0/token"
try:
with urllib.request.urlopen(url, body, timeout=60) as r:
print(json.load(r)["access_token"])
except Exception as e:
sys.exit(f"could not get a signing token: {e}")
PY
)"
fi
export AZURE_SIGNING_TOKEN
for file in "$@"; do
java -jar "$jar" \
--storetype TRUSTEDSIGNING \
--keystore "${endpoint#https://}" \
--storepass env:AZURE_SIGNING_TOKEN \
--alias "$account/$profile" \
--alg SHA-256 \
--tsaurl http://timestamp.acs.microsoft.com --tsmode RFC3161 \
--tsretries 3 --tsretrywait 10 \
--name "Alkane Toolkit" \
--url https://gitea.bluefla.re/blueflare/alkane-toolkit \
"$file"
# jsign fails on any error; also make sure a signature actually landed in
# the PE certificate table before the file goes anywhere.
python3 - "$file" <<'PY'
import struct, sys
data = open(sys.argv[1], "rb").read()
pe = struct.unpack_from("<I", data, 0x3C)[0]
magic = struct.unpack_from("<H", data, pe + 24)[0]
dirs = pe + 24 + (96 if magic == 0x10B else 112)
offset, size = struct.unpack_from("<II", data, dirs + 4 * 8) # IMAGE_DIRECTORY_ENTRY_SECURITY
if size == 0:
sys.exit(f"{sys.argv[1]}: no Authenticode signature after signing")
print(f"{sys.argv[1]}: signed ({size} byte certificate table)")
PY
done
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check that every Toolkit benchmark contributes to the release badge."""
import importlib.util
import re
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("bench_badge", ROOT / "ci/bench-badge.py")
assert spec is not None and spec.loader is not None
badge = importlib.util.module_from_spec(spec)
spec.loader.exec_module(badge)
badge_spec = importlib.util.spec_from_file_location("gen_badges", ROOT / "ci/gen-badges.py")
assert badge_spec is not None and badge_spec.loader is not None
gen_badges = importlib.util.module_from_spec(badge_spec)
badge_spec.loader.exec_module(gen_badges)
class BenchBadgeTests(unittest.TestCase):
def test_declared_suite_matches_rust_benchmarks(self):
names = set()
for directory in (ROOT / "crates/alkane-gui/src", ROOT / "crates/alkane-artifacts/src"):
for path in directory.rglob("*.rs"):
names.update(re.findall(
r'#\[test\]\s*#\[ignore(?:\s*=\s*"[^"]*")?\]\s*'
r'fn (bench_[A-Za-z0-9_]+)\s*\(', path.read_text()))
self.assertEqual(names, badge.EXPECTED_BENCHES)
def test_incomplete_duplicate_and_malformed_results_fail(self):
lines = [f"test tests::{name} ... {name}: 10ms/op"
for name in sorted(badge.EXPECTED_BENCHES)]
values = badge.require_suite(badge.parse_bench("\n".join(lines)))
self.assertEqual(len(values), 12)
with self.assertRaisesRegex(ValueError, "declared suite"):
badge.require_suite(badge.parse_bench("\n".join(lines[:-1])))
with self.assertRaisesRegex(ValueError, "duplicate"):
badge.parse_bench("\n".join(lines + [lines[0]]))
with self.assertRaisesRegex(ValueError, "missing timing"):
badge.parse_bench(lines[0].replace("10ms/op", "missing"))
def test_badge_averages_each_benchmark_improvement(self):
current = {"short": 50.0, "long": 900.0}
baseline = {"short": 100.0, "long": 1000.0}
self.assertEqual(badge.benchmark_delta(current, baseline), 30.0)
self.assertAlmostEqual(badge.benchmark_delta(baseline, current), -55.5555556)
self.assertIsNone(badge.benchmark_delta(current, {}))
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
def test_quality_grade_is_only_the_clippy_result(self):
self.assertEqual(gen_badges.quality_grade("clean"), "A")
self.assertEqual(gen_badges.quality_grade("failed"), "F")
self.assertEqual(gen_badges.quality_grade(None), "pending")
svg = gen_badges.badge_svg(
"code quality", "A", "brightgreen",
"code quality: A (GUI Clippy and first-party rustfmt)",
)
self.assertIn('aria-label="code quality: A (GUI Clippy and first-party rustfmt)"', svg)
self.assertIn('>A</text>', svg)
if __name__ == "__main__":
unittest.main()
+62 -2
View File
@@ -3,11 +3,15 @@
"""Exercise benchmark history selection and safe site rendering."""
import sys
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
from bench_history import bench_badge, previous_measurement, render_html, updated_index
from bench_history import (bench_badge, git_distance, previous_measurement, render_html,
same_benchmark_inputs, updated_index)
class HistoryTests(unittest.TestCase):
@@ -41,6 +45,7 @@ class HistoryTests(unittest.TestCase):
self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5)
def test_invalid_measurement_and_sha_rejected(self):
self.assertIsNone(git_distance("--bad", "a" * 40))
with self.assertRaises(ValueError):
updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now")
with self.assertRaises(ValueError):
@@ -56,14 +61,69 @@ class HistoryTests(unittest.TestCase):
{"hash": 10.0})
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
def test_routing_change_is_marked_same_inputs_but_code_or_build_change_is_not(self):
with tempfile.TemporaryDirectory(prefix="alkane-bench-inputs-") as directory:
root = Path(directory)
workflow = root / ".gitea/workflows/release.yml"
workflow.parent.mkdir(parents=True)
code = root / "crates/alkane-gui/src/main.rs"
code.parent.mkdir(parents=True)
code.write_text("fn main() {}\n")
workflow.write_text(
"jobs:\n release:\n runs-on: alkane-verify\n"
" container:\n image: pinned-image\n"
" env:\n RUSTFLAGS: stable\n steps:\n"
" - name: Build release\n run: cargo build --release\n"
" - name: Microbenchmarks\n run: cargo test --release bench_\n")
def git(*args):
return subprocess.check_output(("git", "-C", str(root), *args),
text=True, stderr=subprocess.DEVNULL).strip()
git("init", "-q")
git("config", "user.name", "CI Test")
git("config", "user.email", "ci@example.invalid")
git("add", ".")
git("commit", "-qm", "base")
base = git("rev-parse", "HEAD")
workflow.write_text(workflow.read_text().replace("alkane-verify", "alkane-ci"))
git("commit", "-qam", "route")
route = git("rev-parse", "HEAD")
self.assertTrue(same_benchmark_inputs(base, route, root))
code.write_text("fn main() { println!(\"changed\"); }\n")
git("commit", "-qam", "code")
changed_code = git("rev-parse", "HEAD")
self.assertFalse(same_benchmark_inputs(route, changed_code, root))
workflow.write_text(workflow.read_text().replace("RUSTFLAGS: stable", "RUSTFLAGS: tuned"))
git("commit", "-qam", "flags")
flags = git("rev-parse", "HEAD")
self.assertFalse(same_benchmark_inputs(changed_code, flags, root))
def test_badge_keeps_raw_delta_and_marks_identical_inputs(self):
with tempfile.TemporaryDirectory(prefix="alkane-bench-badge-context-") as directory:
root = Path(directory)
badges = root / "badges"
badges.mkdir()
(badges / "bench-context.json").write_text(
json.dumps({"schema": 1, "same_inputs": True, "baseline_sha": "a" * 40}))
command = (sys.executable, str(Path(__file__).with_name("gen-badges.py")),
"--root", str(root), "--bench-delta=-36.4")
subprocess.run(command, check=True, capture_output=True)
self.assertIn("-36.4% same inputs", (badges / "bench.svg").read_text())
(badges / "bench-context.json").unlink()
subprocess.run(command, check=True, capture_output=True)
self.assertIn("-36.4% vs prev", (badges / "bench.svg").read_text())
def test_site_escapes_history_content(self):
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
"metrics": {"bench_ns_per_op": {"hash": 10.0},
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
"bench_host": {"cpu_model": "<script>cpu</script>"},
"bench_context": {"schema": 1, "same_inputs": True}}}
page = render_html({"entries": [entry]})
self.assertIn("&lt;script&gt;", page)
self.assertNotIn("<script>", page)
self.assertIn("10.000", page)
self.assertIn("same inputs", page)
if __name__ == "__main__":
+6
View File
@@ -53,6 +53,12 @@ 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
# 3b. Windows packaging (build script / resources) is release-relevant: bumps Y
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/windows"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf '<assembly/>' > "$R/crates/alkane-gui/windows/alkane-toolkit.exe.manifest"; commit "$R" winres
run_case windows_resources_bump "$R" version=1.3.0 bump=backend 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
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check that unknown changes cannot take a scoped CI path."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import importlib.util
import yaml
SCRIPT = Path(__file__).with_name("pr-surface.py")
ROOT = SCRIPT.parents[1]
spec = importlib.util.spec_from_file_location("pr_surface", SCRIPT)
assert spec and spec.loader
pr_surface = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pr_surface)
def git(directory: Path, *args: str) -> str:
return subprocess.check_output(
["git", "-C", str(directory), *args], text=True,
stderr=subprocess.DEVNULL,
).strip()
def check_workflow_contract() -> None:
"""Keep the short workflow check from silently dropping release gates."""
required = [
("release.yml", "main", "release", (
"Check runner image pins", "Check first-party Rust formatting",
"Clippy (our crate, warnings are errors)",
"Build release", "Unit tests", "Microbenchmarks",
"Headless UI self-test", "Coverage", "Microbenchmark coverage",
"Generate measured badges", "Publish measured badges",
"Record private benchmark history", "Create Gitea release + upload artifact",
"Clean generated Toolkit build",
)),
("release.yml", "main", "windows", (
"Clippy (Windows target, warnings are errors)", "Build release (Windows)",
"Unit tests (Windows build, under Wine)",
"Headless UI self-test (Windows build, under Wine)",
"Sign Windows executable (Azure Artifact Signing)",
"Package Windows artifact", "Clean generated Toolkit build",
)),
("next.yml", "next", "candidate", (
"Check runner image pins", "Build release candidate",
"Create private prerelease", "Clean generated Toolkit build",
)),
("next.yml", "next", "windows", (
"Build Windows candidate", "Sign Windows candidate (Azure Artifact Signing)",
"Package Windows candidate",
"Clean generated Toolkit build",
)),
("verify.yml", "main", "verify", (
"Check runner image pins", "Detect changed surface",
"Check CI change surface", "Check first-party Rust formatting",
"Check workflow-only change",
"Clippy (our crate, warnings are errors)", "Build", "Unit tests",
"Microbenchmarks", "Headless UI self-test", "Clean generated Toolkit build",
)),
("verify.yml", "main", "verify-windows", (
"Clippy (Windows target, warnings are errors)", "Build (Windows)",
"Unit tests (Windows build, under Wine)",
"Headless UI self-test (Windows build, under Wine)",
"Clean generated Toolkit build",
)),
]
for filename, branch, job_name, gates in required:
path = ROOT / ".gitea/workflows" / filename
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
event = "pull_request" if filename == "verify.yml" else "push"
assert workflow["on"][event]["branches"] == [branch], path
job = workflow["jobs"][job_name]
assert job["runs-on"] in {"alkane-ci", "alkane-verify"}, path
steps = job["steps"]
names = [step.get("name") for step in steps]
positions = [names.index(gate) for gate in gates]
assert positions == sorted(positions), path
assert steps[positions[-1]].get("if") == "always()", path
for gate, position in zip(gates[:-1], positions[:-1]):
condition = steps[position].get("if")
if gate in {"Create Gitea release + upload artifact",
"Create private prerelease", "Package Windows artifact",
"Build Windows candidate", "Package Windows candidate",
"Sign Windows candidate (Azure Artifact Signing)"}:
assert condition is not None and "release == 'true'" in condition, path
elif filename == "verify.yml" and gate in {
"Build", "Unit tests", "Microbenchmarks",
"Clippy (our crate, warnings are errors)",
"Headless UI self-test"}:
assert condition == "steps.surface.outputs.surface == 'full'", path
elif filename == "verify.yml" and gate == "Check CI change surface":
assert condition == "steps.surface.outputs.surface != 'documentation'", path
elif filename == "verify.yml" and gate == "Check first-party Rust formatting":
assert condition == ("steps.surface.outputs.surface == 'headless' || "
"steps.surface.outputs.surface == 'full'"), path
elif filename == "verify.yml" and gate == "Check workflow-only change":
assert condition == "steps.surface.outputs.surface == 'workflow'", path
else:
assert condition is None, path
def main() -> None:
check_workflow_contract()
with tempfile.TemporaryDirectory(prefix="alkane-toolkit-workflow-policy-") as directory:
global ROOT
saved_root = ROOT
ROOT = Path(directory)
(ROOT / ".gitea/workflows").mkdir(parents=True)
for filename in ("release.yml", "next.yml", "verify.yml"):
shutil.copyfile(saved_root / ".gitea/workflows" / filename,
ROOT / ".gitea/workflows" / filename)
release = ROOT / ".gitea/workflows/release.yml"
original = release.read_text()
release.write_text(original.replace("- name: Coverage", "- name: Skipped coverage", 1))
try:
check_workflow_contract()
except ValueError:
pass
else:
raise AssertionError("removing the coverage gate passed workflow policy")
ROOT = saved_root
assert pr_surface.documentation_only(["README.md", "docs/setup.md"])
assert pr_surface.workflow_only([".gitea/workflows/release.yml"])
for paths in ([], ["ci/pr-surface.py"], ["ci/coverage.sh"],
["ci/check-runner-image.py"],
[".gitea/workflows/release.yml", "ci/check-runner-image.py"],
[".gitea/workflows/release.yml", "crates/alkane-gui/src/main.rs"],
[".gitea/workflows/../release.yml"]):
assert not pr_surface.workflow_only(paths), paths
for paths in ([], ["docs/generated.json"], ["src/main.rs"],
["README.md", "ci/pr-surface.py"]):
assert not pr_surface.documentation_only(paths), paths
assert pr_surface.headless_packages(["crates/alkane-cli/src/main.rs"]) == ["alkane-cli"]
assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == [
"alkane-artifacts", "alkane-cli", "alkane-flash",
]
assert pr_surface.headless_packages([
"crates/alkane-access/src/lib.rs", "crates/alkane-flash/tests/update.rs",
]) == ["alkane-access", "alkane-flash"]
for paths in ([], ["crates/alkane-core/src/lib.rs"],
["crates/alkane-discovery/src/lib.rs"],
["crates/alkane-gui/src/main.rs"],
["crates/alkane-artifacts/Cargo.toml"],
["crates/alkane-cli/src/main.rs", "Cargo.lock"],
["crates/alkane-cli/src/main.rs", "ci/pr-surface.py"],
["crates/alkane-cli/README.md"]):
assert pr_surface.headless_packages(paths) == [], paths
with tempfile.TemporaryDirectory(prefix="alkane-toolkit-graph-") as directory:
root = Path(directory)
for name, extra in (
("alkane-gui", ""),
("alkane-artifacts", ""),
("alkane-flash", 'alkane-artifacts = { path = "../alkane-artifacts" }\n'),
):
crate = root / "crates" / name
crate.mkdir(parents=True)
(crate / "Cargo.toml").write_text(
f'[package]\nname = "{name}"\nversion = "0.1.0"\n'
f'[dependencies]\n{extra}'
)
saved_root = pr_surface.ROOT
try:
pr_surface.ROOT = root
changed = ["crates/alkane-artifacts/src/lib.rs"]
assert pr_surface.headless_packages(changed) == [
"alkane-artifacts", "alkane-flash",
]
with (root / "crates/alkane-gui/Cargo.toml").open("a") as stream:
stream.write('alkane-flash = { path = "../alkane-flash" }\n')
assert pr_surface.headless_packages(changed) == []
finally:
pr_surface.ROOT = saved_root
with tempfile.TemporaryDirectory(prefix="alkane-toolkit-pr-surface-") as directory:
repo = Path(directory)
git(repo, "init", "-q")
git(repo, "config", "user.name", "CI Test")
git(repo, "config", "user.email", "ci@example.invalid")
(repo / "README.md").write_text("initial\n")
git(repo, "add", "README.md")
git(repo, "commit", "-qm", "base")
base = git(repo, "rev-parse", "HEAD")
git(repo, "update-ref", "refs/remotes/origin/main", base)
(repo / "README.md").write_text("documentation change\n")
git(repo, "commit", "-qam", "docs")
saved_root = pr_surface.ROOT
saved_env = dict(os.environ)
try:
pr_surface.ROOT = repo
os.environ["GITHUB_EVENT_NAME"] = "pull_request"
os.environ["GITHUB_BASE_REF"] = "main"
assert pr_surface.changed_paths() == ["README.md"]
git(repo, "checkout", "-q", "-b", "rename-check", base)
git(repo, "mv", "README.md", "code.rs")
git(repo, "commit", "-qm", "rename")
assert set(pr_surface.changed_paths()) == {"README.md", "code.rs"}
os.environ.pop("GITHUB_BASE_REF")
try:
pr_surface.changed_paths()
except ValueError:
pass
else:
raise AssertionError("missing base must fall back to full checks")
finally:
pr_surface.ROOT = saved_root
os.environ.clear()
os.environ.update(saved_env)
print("Toolkit PR change surface: documentation, workflow, headless, and fallback PASS")
if __name__ == "__main__":
main()
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Every Windows CI step in one place, so verify (PRs), the main release and the
# next-branch candidates build and test the .exe the same way:
#
# windows-ci.sh toolchain mingw-w64 + Wine + the rustup target
# windows-ci.sh clippy clippy for x86_64-pc-windows-gnu, -D warnings
# windows-ci.sh build release alkane-toolkit.exe
# windows-ci.sh test all unit tests, run under Wine
# windows-ci.sh selftest headless UI self-test under Wine + Xvfb
# windows-ci.sh sign Authenticode-sign alkane-toolkit.exe through
# Azure Artifact Signing (ci/sign-windows.sh;
# a no-op until AZURE_SIGNING_PROFILE is set)
# windows-ci.sh package VERSION dist/alkane-toolkit-vVERSION-windows-x86_64.zip
# windows-ci.sh test-bundle dist/alkane-toolkit-windows-tests.zip (for
# the native Windows job)
#
# The wxMSW prefix comes from the CI image or ci/ensure-wx-prefix.sh windows.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
export WX_WINDOWS_PREFIX="${WX_WINDOWS_PREFIX:-/root/.cache/wx-3.3.3-mingw}"
export ALKANE_WINEPREFIX="${ALKANE_WINEPREFIX:-/root/.cache/alkane-wine}"
# shellcheck source=../scripts/windows-cross-env.sh
. scripts/windows-cross-env.sh
target="$ALKANE_WIN_TARGET"
out_dir="${CARGO_TARGET_DIR:-target}"
exe="$out_dir/$target/release/alkane-toolkit.exe"
# The GUI crate's tests link wx and some create windows; Wine wants a display.
headless() { xvfb-run -a -s '-screen 0 1280x850x24' "$@"; }
case "${1:-}" in
toolchain)
bash ci/ensure-build-deps.sh windows
rustup target list --installed | grep -qx "$target" || rustup target add "$target"
# jsign ships in the CI image; fetch the same pinned jar on older images.
jsign_version=7.6
jsign_sha256=6cf58aa080e7ff82656f320cff8d4a3bff30408df8766806dcba3740dd839fa5
if [ ! -s /opt/jsign/jsign.jar ]; then
mkdir -p /opt/jsign
curl -sSfL -o /opt/jsign/jsign.jar \
"https://repo1.maven.org/maven2/net/jsign/jsign/$jsign_version/jsign-$jsign_version.jar"
echo "$jsign_sha256 /opt/jsign/jsign.jar" | sha256sum -c -
fi
;;
clippy)
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --target "$target" --offline -- -D warnings
cargo clippy --workspace --exclude alkane-gui --exclude wx-rs --all-targets \
--target "$target" --offline -- -D warnings
;;
build)
cargo build --release -p alkane-gui --target "$target" --offline
# One self-contained .exe: any toolchain DLL import would fail on a clean
# Windows machine, so refuse to ship one.
if x86_64-w64-mingw32-objdump -p "$exe" | grep -iE 'DLL Name: (libstdc|libgcc|libwinpthread)'; then
echo "alkane-toolkit.exe imports a mingw runtime DLL" >&2
exit 1
fi
;;
test)
headless cargo test --workspace --exclude wx-rs --target "$target" --offline 2>&1 \
| tee tests-windows.txt
;;
selftest)
bash scripts/ui-selftest-windows.sh "$exe"
;;
sign)
bash ci/sign-windows.sh "$exe"
;;
package)
python3 ci/package-windows.py release "${2:?usage: windows-ci.sh package VERSION}" "$exe" dist
;;
test-bundle)
mkdir -p dist
cargo test --workspace --exclude wx-rs --target "$target" --offline --no-run \
--message-format=json > "$out_dir/windows-tests.json"
python3 ci/package-windows.py tests "$out_dir/windows-tests.json" \
dist/alkane-toolkit-windows-tests.zip
;;
*)
sed -n '3,19p' "$0" >&2
exit 2
;;
esac
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Key a wxWidgets prefix to its tracked source and build toolchain.
# wx-cache-key.sh [linux|windows]
set -euo pipefail
platform="${1:-linux}"
if [ "$platform" = windows ]; then
material="$({
git rev-parse HEAD:thirdparty/wxwidgets/wxWidgets-3.3.3
git rev-parse HEAD:scripts/build-wx-windows.sh
x86_64-w64-mingw32-g++-posix -dumpmachine
x86_64-w64-mingw32-g++-posix -dumpfullversion
} )"
digest="$(printf '%s\n' "$material" | sha256sum | cut -c1-24)"
key="wx-3.3.3-mingw-$digest"
if [ -n "${GITHUB_OUTPUT:-}" ]; then printf 'key=%s\n' "$key" >> "$GITHUB_OUTPUT"; else printf '%s\n' "$key"; fi
exit 0
fi
material="$({
git rev-parse HEAD:thirdparty/wxwidgets/wxWidgets-3.3.3
git rev-parse HEAD:scripts/build-wx-linux.sh
cat thirdparty/wx-rs/VERSION
gcc -dumpmachine
gcc -dumpfullversion
pkg-config --modversion gtk+-3.0
mapfile -t modules < <(pkg-config --list-all | awk '{print $1}' | LC_ALL=C sort -u)
for module in "${modules[@]}"; do
printf '%s=%s\n' "$module" "$(pkg-config --modversion "$module" 2>/dev/null || printf unavailable)"
done
getconf GNU_LIBC_VERSION
} )"
digest="$(printf '%s\n' "$material" | sha256sum | cut -c1-24)"
key="wx-3.3.3-$digest"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
printf 'key=%s\n' "$key" >> "$GITHUB_OUTPUT"
else
printf '%s\n' "$key"
fi
+219 -1
View File
@@ -1 +1,219 @@
// alkane-access
// SPDX-License-Identifier: MIT
//! Bounded, read-only SSH probes for board identification.
use std::fs;
use std::io::{self, Read};
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
const MAX_PROBE_BYTES: usize = 64 * 1024;
const PROBE_TIMEOUT: Duration = Duration::from_secs(12);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Probe {
KernelRelease,
MtdTable,
DeviceTreeModel,
}
impl Probe {
fn command(self) -> &'static str {
match self {
Self::KernelRelease => "uname -r",
Self::MtdTable => "cat /proc/mtd",
Self::DeviceTreeModel => "cat /proc/device-tree/model",
}
}
}
#[derive(Debug)]
pub enum AccessError {
InvalidTarget,
InvalidKnownHosts,
Timeout,
OutputTooLarge,
RemoteFailure,
Io(io::Error),
}
impl From<io::Error> for AccessError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
pub struct SshTarget {
address: IpAddr,
port: u16,
user: String,
known_hosts: PathBuf,
}
impl SshTarget {
pub fn new(
address: IpAddr,
port: u16,
user: &str,
known_hosts: &Path,
) -> Result<Self, AccessError> {
if port == 0
|| user.is_empty()
|| !user
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
{
return Err(AccessError::InvalidTarget);
}
if !known_hosts.is_absolute()
|| !fs::metadata(known_hosts).is_ok_and(|metadata| metadata.is_file())
{
return Err(AccessError::InvalidKnownHosts);
}
Ok(Self {
address,
port,
user: user.to_owned(),
known_hosts: known_hosts.to_owned(),
})
}
fn command(&self, probe: Probe) -> Command {
let mut command = alkane_core::platform::quiet_command("ssh");
command
.arg("-F")
.arg("none")
.arg("-o")
.arg("BatchMode=yes")
.arg("-o")
.arg("StrictHostKeyChecking=yes")
.arg("-o")
.arg("GlobalKnownHostsFile=none")
.arg("-o")
.arg(format!("UserKnownHostsFile={}", self.known_hosts.display()))
.arg("-o")
.arg("ConnectTimeout=5")
.arg("-o")
.arg("ServerAliveInterval=5")
.arg("-o")
.arg("ServerAliveCountMax=1")
.arg("-o")
.arg("RequestTTY=no")
.arg("-p")
.arg(self.port.to_string())
.arg(format!("{}@{}", self.user, self.address))
.arg(probe.command());
command
}
pub fn probe(&self, probe: Probe) -> Result<Vec<u8>, AccessError> {
run_bounded(self.command(probe))
}
}
fn collect_bounded<R: Read + Send + 'static>(
mut reader: R,
) -> thread::JoinHandle<Result<Vec<u8>, AccessError>> {
thread::spawn(move || {
let mut data = Vec::new();
let mut chunk = [0_u8; 4096];
loop {
let count = reader.read(&mut chunk)?;
if count == 0 {
return Ok(data);
}
if data.len() + count > MAX_PROBE_BYTES {
return Err(AccessError::OutputTooLarge);
}
data.extend_from_slice(&chunk[..count]);
}
})
}
fn run_bounded(command: Command) -> Result<Vec<u8>, AccessError> {
run_bounded_with_timeout(command, PROBE_TIMEOUT)
}
fn run_bounded_with_timeout(
mut command: Command,
timeout: Duration,
) -> Result<Vec<u8>, AccessError> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let stdout = collect_bounded(child.stdout.take().expect("piped stdout"));
let stderr = collect_bounded(child.stderr.take().expect("piped stderr"));
let deadline = Instant::now() + timeout;
let result = loop {
if let Some(status) = child.try_wait()? {
break status.success();
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = stdout.join();
let _ = stderr.join();
return Err(AccessError::Timeout);
}
thread::sleep(Duration::from_millis(10));
};
let output = stdout.join().map_err(|_| AccessError::RemoteFailure)??;
let error_output = stderr.join().map_err(|_| AccessError::RemoteFailure)??;
if !result || !error_output.is_empty() {
return Err(AccessError::RemoteFailure);
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn target_rejects_injected_user_and_unknown_host_file() {
let address = "127.0.0.1".parse().unwrap();
assert!(matches!(
SshTarget::new(
address,
22,
"root;id",
Path::new("/etc/ssh/ssh_known_hosts")
),
Err(AccessError::InvalidTarget)
));
assert!(matches!(
SshTarget::new(address, 22, "root", Path::new("relative-known-hosts")),
Err(AccessError::InvalidKnownHosts)
));
}
#[cfg(unix)]
#[test]
fn bounded_runner_rejects_excess_output_and_failed_command() {
let mut success = Command::new("/bin/sh");
success.args(["-c", "printf board"]);
assert_eq!(run_bounded(success).unwrap(), b"board");
let mut overflow = Command::new("/bin/sh");
overflow.args(["-c", "head -c 70000 /dev/zero"]);
assert!(matches!(
run_bounded(overflow),
Err(AccessError::OutputTooLarge)
));
let mut failed = Command::new("/bin/sh");
failed.args(["-c", "exit 7"]);
assert!(matches!(
run_bounded(failed),
Err(AccessError::RemoteFailure)
));
let mut hanging = Command::new("/bin/sleep");
hanging.arg("1");
assert!(matches!(
run_bounded_with_timeout(hanging, Duration::from_millis(20)),
Err(AccessError::Timeout)
));
}
}
+2
View File
@@ -1 +1,3 @@
// alkane-core
pub mod platform;
+148
View File
@@ -0,0 +1,148 @@
//! The few places the toolkit's behaviour depends on the operating system,
//! kept together so the rest of the code stays platform-neutral.
//!
//! - where per-user settings live ([`config_dir`]),
//! - how a secret file is written so only its owner can read it
//! ([`write_private`]),
//! - the null device for tools that insist on an output path ([`NULL_DEVICE`]),
//! - how helper programs (`ssh`, `curl`) are started from the GUI without a
//! console window popping up on Windows ([`quiet_command`]).
use std::path::{Path, PathBuf};
use std::process::Command;
/// Directory name of the toolkit's settings under the per-user config root.
pub const APP_DIR: &str = "alkane-toolkit";
/// Environment variable whose value is the per-user config root on this
/// platform: `HOME` (settings in `$HOME/.config/alkane-toolkit`) on Unix,
/// `APPDATA` (settings in `%APPDATA%\alkane-toolkit`) on Windows. Tests point it
/// at a scratch directory.
#[cfg(not(windows))]
pub const CONFIG_ROOT_VAR: &str = "HOME";
#[cfg(windows)]
pub const CONFIG_ROOT_VAR: &str = "APPDATA";
/// The per-user settings directory (not created here).
///
/// Unix keeps the long-standing `$HOME/.config/alkane-toolkit`. Windows uses
/// the roaming application-data folder, `%APPDATA%\alkane-toolkit`, which is
/// where Windows applications keep per-user settings and which the user
/// profile's ACL already restricts to its owner. A missing variable falls back
/// to the working directory, as before.
pub fn config_dir() -> PathBuf {
let root = std::env::var_os(CONFIG_ROOT_VAR).unwrap_or_else(|| ".".into());
if cfg!(windows) {
PathBuf::from(root).join(APP_DIR)
} else {
PathBuf::from(root).join(".config").join(APP_DIR)
}
}
/// `config_dir()/file`.
pub fn config_path(file: &str) -> PathBuf {
config_dir().join(file)
}
/// The null device, for tools that want an output path (`curl -o`,
/// `ssh -o UserKnownHostsFile=`).
#[cfg(not(windows))]
pub const NULL_DEVICE: &str = "/dev/null";
#[cfg(windows)]
pub const NULL_DEVICE: &str = "NUL";
/// Write `data` to `path` so only the owner can read it.
///
/// On Unix the file is created 0600 (so a secret is never momentarily
/// world-readable between write and chmod), and a pre-existing file is
/// re-tightened while it is still empty, before the plaintext is written. On
/// Windows the settings directory inherits the user profile's owner-only ACL,
/// so a plain write already has the equivalent protection.
pub fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(data)
}
#[cfg(not(unix))]
{
std::fs::write(path, data)
}
}
/// A [`Command`] for a helper program run in the background of the GUI.
///
/// On Windows a console program (`ssh.exe`, `curl.exe`) started from a GUI
/// process gets a new console window by default, so every probe would flash a
/// black window; `CREATE_NO_WINDOW` suppresses that while keeping its piped
/// stdin/stdout/stderr. Elsewhere this is `Command::new`.
pub fn quiet_command(program: &str) -> Command {
#[allow(unused_mut)]
let mut command = Command::new(program);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
command
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_dir_is_under_the_platform_root() {
let dir = config_dir();
assert!(dir.ends_with(APP_DIR), "{dir:?}");
if cfg!(windows) {
assert!(!dir.to_string_lossy().contains(".config"), "{dir:?}");
} else {
assert!(dir.parent().unwrap().ends_with(".config"), "{dir:?}");
}
assert_eq!(config_path("x.txt"), dir.join("x.txt"));
}
#[test]
fn write_private_round_trips_and_restricts() {
let dir = std::env::temp_dir().join(format!("alkane-private-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("secret.txt");
write_private(&path, b"one").unwrap();
write_private(&path, b"two").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"two");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn quiet_command_runs_with_piped_output() {
// `cmd /C echo` and `sh -c echo` are the platform's own shells.
let mut command = if cfg!(windows) {
let mut c = quiet_command("cmd");
c.args(["/C", "echo alkane"]);
c
} else {
let mut c = quiet_command("sh");
c.args(["-c", "echo alkane"]);
c
};
let out = command.output().unwrap();
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stdout).contains("alkane"));
}
}
+1
View File
@@ -9,3 +9,4 @@ alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
sha2.workspace = true
thiserror.workspace = true
tempfile = "3"
+55 -7
View File
@@ -4,7 +4,7 @@
use alkane_artifacts::VerifiedArtifact;
use sha2::{Digest, Sha256};
use std::io::{Read, Seek, SeekFrom};
use std::io::{Read, Seek, SeekFrom, Write};
use thiserror::Error;
pub struct PartitionSpec {
@@ -90,6 +90,34 @@ fn digest_bytes(hex: &str) -> Result<[u8; 32], FlashError> {
Ok(result)
}
fn stage_verified_artifact(
artifact: &mut VerifiedArtifact,
size: u64,
expected: [u8; 32],
) -> Result<std::fs::File, FlashError> {
let mut staged = tempfile::tempfile().map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
artifact
.reader()
.seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
let mut source = DigestReader {
inner: artifact.reader(),
remaining: size,
digest: Sha256::new(),
};
std::io::copy(&mut source, &mut staged).map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
if source.remaining != 0 || <[u8; 32]>::from(source.digest.finalize()) != expected {
return Err(FlashError::ArtifactChanged);
}
staged
.flush()
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
staged
.seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
Ok(staged)
}
struct DigestReader<'a> {
inner: &'a mut dyn Read,
remaining: u64,
@@ -145,6 +173,10 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
artifact
.revalidate()
.map_err(|_| FlashError::ArtifactChanged)?;
let expected = digest_bytes(&artifact.record().sha256)?;
// The source path may change while backup or transport I/O runs. Copy and
// verify it before any device write; the anonymous file is removed on drop.
let mut staged = stage_verified_artifact(artifact, size, expected)?;
let backup = writer
.backup(partition)
.map_err(|e| FlashError::Write(e.to_string()))?;
@@ -154,13 +186,8 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
{
return Err(FlashError::BackupIncomplete);
}
let expected = digest_bytes(&artifact.record().sha256)?;
artifact
.reader()
.seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
let mut stream = DigestReader {
inner: artifact.reader(),
inner: &mut staged,
remaining: size,
digest: Sha256::new(),
};
@@ -203,6 +230,7 @@ mod tests {
max_read: Option<u64>,
writes: usize,
contents: Vec<u8>,
mutate_source_on_write: Option<PathBuf>,
}
impl Writer for MockWriter {
@@ -231,6 +259,9 @@ mod tests {
_: u64,
) -> Result<(), Self::Error> {
self.writes += 1;
if let Some(path) = &self.mutate_source_on_write {
std::fs::write(path, b"PK\x03\x04changed").map_err(|_| "mutation failed")?;
}
if let Some(limit) = self.max_read {
image
.take(limit)
@@ -285,6 +316,7 @@ mod tests {
max_read: None,
writes: 0,
contents: Vec::new(),
mutate_source_on_write: None,
}
}
@@ -395,4 +427,20 @@ mod tests {
assert_eq!(writer.writes, 1);
std::fs::remove_file(path).unwrap();
}
#[test]
fn writes_verified_snapshot_when_source_changes_during_transport() {
let (path, mut image) = artifact("mutated-during-write");
let mut writer = writer();
writer.mutate_source_on_write = Some(path.clone());
let mut readback = MockReadback {
channel: "serial",
digest: digest_bytes(SHA).unwrap(),
};
let receipt = write_verified(&partition(), &mut image, &mut writer, &mut readback).unwrap();
assert_eq!(receipt.image_sha256, digest_bytes(SHA).unwrap());
assert_eq!(writer.contents, IMAGE);
assert_eq!(std::fs::read(&path).unwrap(), b"PK\x03\x04changed");
std::fs::remove_file(path).unwrap();
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Build script for the alkane-toolkit binary. On Windows targets it compiles
//! windows/alkane-toolkit.rc (application manifest, icon, version info, and
//! wxMSW's stock resources) and links the result into the GUI executable only.
//! Other targets need nothing here.
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
for f in [
"alkane-toolkit.rc",
"alkane-toolkit.exe.manifest",
"alkane-toolkit.ico",
] {
println!("cargo:rerun-if-changed=windows/{f}");
}
println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
if let Err(e) = compile_resources() {
panic!("alkane-gui: Windows resources: {e}");
}
}
fn compile_resources() -> Result<(), String> {
// The resource compiler and wx's resource include path come from the same
// wx-config the wx-rs bridge builds against, so they always match the
// linked wxMSW (and the mingw cross windres when cross-compiling).
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| "wx-config".into());
let run = |arg: &str| -> Result<String, String> {
let out = Command::new(&wxconfig)
.arg(arg)
.output()
.map_err(|e| format!("cannot run {wxconfig} {arg}: {e}"))?;
if !out.status.success() {
return Err(format!("{wxconfig} {arg} failed"));
}
String::from_utf8(out.stdout).map_err(|e| e.to_string())
};
let rescomp = run("--rescomp")?;
let mut words = rescomp.split_whitespace();
let windres = words.next().ok_or("wx-config --rescomp printed nothing")?;
let mut args: Vec<String> = words.map(str::to_owned).collect();
// rcdefs.h lives in the build-specific setup directory, which --rescomp
// omits; it is the -I entry of --cxxflags.
for flag in run("--cxxflags")?.split_whitespace() {
if let Some(dir) = flag.strip_prefix("-I") {
args.push("--include-dir".into());
args.push(dir.into());
}
}
let version = env::var("CARGO_PKG_VERSION").unwrap_or_default();
let mut parts = version
.split(['.', '-', '+'])
.map(|p| p.parse::<u16>().unwrap_or(0));
let (major, minor, patch) = (
parts.next().unwrap_or(0),
parts.next().unwrap_or(0),
parts.next().unwrap_or(0),
);
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(|e| e.to_string())?);
let out =
PathBuf::from(env::var("OUT_DIR").map_err(|e| e.to_string())?).join("alkane-toolkit-res.o");
let status = Command::new(windres)
.args(&args)
.arg("--include-dir")
.arg(manifest_dir.join("windows"))
.arg(format!("--define=ALKANE_VER_MAJOR={major}"))
.arg(format!("--define=ALKANE_VER_MINOR={minor}"))
.arg(format!("--define=ALKANE_VER_PATCH={patch}"))
.arg(format!("--define=ALKANE_VER_STR=\\\"{version}\\\""))
.arg("--input")
.arg(manifest_dir.join("windows/alkane-toolkit.rc"))
.arg("--output-format=coff")
.arg("--output")
.arg(&out)
.status()
.map_err(|e| format!("cannot run {windres}: {e}"))?;
if !status.success() {
return Err(format!("{windres} failed ({status})"));
}
// Only the GUI binary carries the manifest/icon; miner_probe stays a plain
// console tool. A linked object (not an archive member) is never dropped by
// the linker, which is what keeps the resource section in the .exe.
println!("cargo:rustc-link-arg-bin=alkane-toolkit={}", out.display());
Ok(())
}
+69 -23
View File
@@ -29,10 +29,10 @@ use std::net::{SocketAddr, TcpStream};
use std::process::Command;
use std::time::Duration;
use aes::cipher::{block_padding::ZeroPadding, BlockEncryptMut, KeyInit};
use aes::Aes256;
use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use sha2::{Digest, Sha256};
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
@@ -42,9 +42,9 @@ type Aes256EcbEnc = ecb::Encryptor<Aes256>;
/// authenticated/unauthorized answer is `None`.
pub fn classify_http_code(code: &str) -> Option<bool> {
match code.trim() {
"200" | "204" => Some(false), // authenticated -> unlocked/writable
"401" | "403" => Some(true), // rejected -> locked/view-only
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
"200" | "204" => Some(false), // authenticated -> unlocked/writable
"401" | "403" => Some(true), // rejected -> locked/view-only
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
}
}
@@ -77,11 +77,11 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
return Ok(probe_whatsminer_access(ip, &candidates));
}
let url = format!("http://{ip}{}", endpoint(make));
let mut cmd = Command::new("curl");
let mut cmd = alkane_core::platform::quiet_command("curl");
cmd.args([
"-s",
"-o",
"/dev/null",
alkane_core::platform::NULL_DEVICE,
"-w",
"%{http_code}",
"--digest",
@@ -95,7 +95,10 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
]);
// The user:pass goes through a curl config on stdin, never argv, so it can't
// be read from the process list (round 18 #12).
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
let config = format!(
"user = \"{}\"\n",
curl_config_quote(&format!("{user}:{pass}"))
);
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
// curl prints the status code to stdout regardless of exit status (000 on a
// connection failure), so classify the code rather than the exit status.
@@ -113,7 +116,8 @@ fn wait_with_timeout(
stdin_data: Option<&[u8]>,
) -> Result<std::process::Output, String> {
use std::io::{Read, Write};
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
if stdin_data.is_some() {
cmd.stdin(std::process::Stdio::piped());
}
@@ -135,7 +139,11 @@ fn wait_with_timeout(
if let Some(mut e) = child.stderr.take() {
let _ = e.read_to_end(&mut stderr);
}
return Ok(std::process::Output { status, stdout, stderr });
return Ok(std::process::Output {
status,
stdout,
stderr,
});
}
None => {
if start.elapsed() >= timeout {
@@ -158,7 +166,8 @@ fn curl_config_quote(s: &str) -> String {
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
fn whatsminer_password_candidates() -> Vec<String> {
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock") {
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock")
{
if !pass.is_empty() {
return vec![pass.clone()];
}
@@ -170,9 +179,17 @@ fn whatsminer_password_candidates() -> Vec<String> {
/// get_error_code command and format them one per line for the log viewer
/// (round 12 #12). Returns None if the miner does not answer.
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?;
let resp = wm_rpc(
ip,
"{\"command\":\"get_error_code\"}",
Duration::from_secs(6),
)
.ok()?;
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array());
let codes = v
.get("Msg")
.and_then(|m| m.get("error_code"))
.and_then(|c| c.as_array());
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
match codes {
Some(arr) if !arr.is_empty() => {
@@ -198,7 +215,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?;
stream.set_read_timeout(Some(timeout)).ok();
stream.set_write_timeout(Some(timeout)).ok();
stream.write_all(payload.as_bytes()).map_err(|e| e.to_string())?;
stream
.write_all(payload.as_bytes())
.map_err(|e| e.to_string())?;
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
loop {
@@ -213,7 +232,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
Err(_) => break,
}
}
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
Ok(String::from_utf8_lossy(&buf)
.trim_matches('\u{0}')
.to_string())
}
/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact
@@ -278,15 +299,20 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
// 2. Derive the md5crypt password hash + write-token from the password.
let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes());
let full = String::from_utf8_lossy(&crypted);
let Some(pwd_md5) = full.split('$').nth(3) else { continue };
let sign_crypted = md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
let Some(pwd_md5) = full.split('$').nth(3) else {
continue;
};
let sign_crypted =
md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
let sign_full = String::from_utf8_lossy(&sign_crypted);
let host_sign = sign_full.split('$').nth(3).unwrap_or("");
// 3. Send an encrypted, read-only `summary`. If the AES key (from the
// password) is right the miner replies encrypted; if wrong it returns
// a plaintext "enc json load err".
let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}");
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else { continue };
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else {
continue;
};
let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}");
let resp = match wm_rpc(ip, &payload, timeout) {
Ok(s) => s,
@@ -302,7 +328,11 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
}
// Only report "locked" when we cleanly reached the miner and every candidate
// was rejected with no transient errors; otherwise the result is indeterminate.
if reachable && !errored { Some(true) } else { None }
if reachable && !errored {
Some(true)
} else {
None
}
}
#[cfg(test)]
@@ -311,14 +341,30 @@ mod tests {
#[test]
fn classify_codes() {
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
assert_eq!(
classify_http_code("200"),
Some(false),
"authenticated -> unlocked"
);
assert_eq!(classify_http_code("204"), Some(false));
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
assert_eq!(
classify_http_code("401"),
Some(true),
"unauthorized -> locked"
);
assert_eq!(classify_http_code("403"), Some(true));
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
assert_eq!(
classify_http_code("404"),
None,
"endpoint absent -> unknown"
);
assert_eq!(classify_http_code("500"), None);
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
assert_eq!(
classify_http_code(" 200 "),
Some(false),
"whitespace tolerated"
);
assert_eq!(classify_http_code(""), None);
}
+122
View File
@@ -0,0 +1,122 @@
//! Non-interactive SSH password logins without `sshpass`.
//!
//! OpenSSH (Linux, and the `ssh.exe` built into Windows 10/11) asks the
//! program named by `SSH_ASKPASS` for a password when `SSH_ASKPASS_REQUIRE=force`
//! (OpenSSH 8.4+). The toolkit names its own executable: when ssh runs it with
//! [`ROLE_ENV`] set, `main()` calls [`serve_if_askpass`] first thing, which
//! prints the password from [`SECRET_ENV`] and exits before any GUI starts.
//!
//! This replaces `sshpass`, which Windows does not have, with one mechanism for
//! every platform. Like `sshpass -e` the password travels in the child's
//! environment, never on a command line where the process list would show it.
use std::ffi::OsStr;
use std::process::{Command, Stdio};
/// Set (to "1") in the environment of an ssh child whose askpass helper is us.
pub const ROLE_ENV: &str = "ALKANE_SSH_ASKPASS";
/// The password the askpass helper hands back to ssh.
pub const SECRET_ENV: &str = "ALKANE_SSH_SECRET";
/// If this process is ssh's askpass helper, answer the prompt and return the
/// exit code to use; otherwise `None` and the app starts normally.
pub fn serve_if_askpass() -> Option<i32> {
std::env::var_os(ROLE_ENV)?;
let prompt = std::env::args_os().nth(1).unwrap_or_default();
Some(answer(&prompt, std::env::var_os(SECRET_ENV).as_deref()))
}
/// Print the secret for a password prompt. Anything else ssh might ask through
/// askpass (a host-key "yes/no" confirmation, a passphrase for a key we never
/// configured) is refused, so a changed prompt can never be answered with the
/// password by accident.
fn answer(prompt: &OsStr, secret: Option<&OsStr>) -> i32 {
let Some(secret) = secret else { return 1 };
if !is_password_prompt(&prompt.to_string_lossy()) {
return 1;
}
use std::io::Write;
let mut out = std::io::stdout().lock();
if out
.write_all(secret.to_string_lossy().as_bytes())
.and_then(|_| out.write_all(b"\n"))
.and_then(|_| out.flush())
.is_err()
{
return 1;
}
0
}
fn is_password_prompt(prompt: &str) -> bool {
let p = prompt.to_ascii_lowercase();
p.contains("password") && !p.contains("yes/no")
}
/// Configure an `ssh` command to log in with `password` and never block on a
/// terminal prompt. ssh tries password (and keyboard-interactive) auth once;
/// a wrong password fails fast with "Permission denied" instead of hanging.
pub fn ssh_with_password(cmd: &mut Command, password: &str) -> Result<(), String> {
let exe = std::env::current_exe().map_err(|e| format!("locate askpass helper: {e}"))?;
cmd.env("SSH_ASKPASS", exe)
.env("SSH_ASKPASS_REQUIRE", "force")
.env(ROLE_ENV, "1")
.env(SECRET_ENV, password)
.stdin(Stdio::null());
Ok(())
}
/// ssh `-o` options that go with [`ssh_with_password`].
pub const PASSWORD_AUTH_OPTIONS: [&str; 4] = [
"-o",
"PreferredAuthentications=password,keyboard-interactive",
"-o",
"NumberOfPasswordPrompts=1",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_password_prompts_are_answered() {
assert!(is_password_prompt("root@10.0.0.1's password: "));
assert!(is_password_prompt("Password:"));
assert!(!is_password_prompt(
"Are you sure you want to continue connecting (yes/no/[fingerprint])?"
));
assert!(!is_password_prompt(
"Enter passphrase for key '/x/id_ed25519':"
));
assert_eq!(
answer(OsStr::new("Password:"), None),
1,
"no secret -> refuse"
);
assert_eq!(
answer(OsStr::new("Continue (yes/no)?"), Some(OsStr::new("pw"))),
1
);
}
#[test]
fn ssh_command_gets_askpass_environment() {
let mut cmd = Command::new("ssh");
ssh_with_password(&mut cmd, "hunter2").unwrap();
let env: std::collections::HashMap<_, _> = cmd
.get_envs()
.map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned())))
.collect();
assert_eq!(
env[OsStr::new("SSH_ASKPASS_REQUIRE")].as_deref(),
Some(OsStr::new("force"))
);
assert_eq!(
env[OsStr::new(SECRET_ENV)].as_deref(),
Some(OsStr::new("hunter2"))
);
assert!(env[OsStr::new("SSH_ASKPASS")].is_some());
// The password is never an argument.
assert!(cmd.get_args().all(|a| a != "hunter2"));
}
}
+29 -12
View File
@@ -19,18 +19,19 @@
//! ALKANE_PROBE_USER / ALKANE_PROBE_PASS if set (so a test can authenticate
//! without touching the app's saved config).
use asic_rs::MinerFactory;
use asic_rs::core::traits::miner::MinerAuth;
use asic_rs::MinerFactory;
use futures_util::StreamExt;
use measurements::Power;
fn load_creds() -> Option<(String, String)> {
if let (Ok(u), Ok(pw)) = (std::env::var("ALKANE_PROBE_USER"), std::env::var("ALKANE_PROBE_PASS")) {
if let (Ok(u), Ok(pw)) = (
std::env::var("ALKANE_PROBE_USER"),
std::env::var("ALKANE_PROBE_PASS"),
) {
return Some((u, pw));
}
let home = std::env::var("HOME").ok()?;
let p = std::path::PathBuf::from(home)
.join(".config/alkane-toolkit/scan-credentials.txt");
let p = alkane_core::platform::config_path("scan-credentials.txt");
let s = std::fs::read_to_string(p).ok()?;
let mut l = s.lines();
let u = l.next()?.to_string();
@@ -92,8 +93,14 @@ async fn scan(cidrs: &[String]) {
.map(|c| c.to_string())
.unwrap_or_default();
let fw_ver = data.firmware_version.clone().unwrap_or_default();
let bs = data.best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
let sbs = data.session_best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
let bs = data
.best_share
.map(|v| format!("{v:.0}"))
.unwrap_or_default();
let sbs = data
.session_best_share
.map(|v| format!("{v:.0}"))
.unwrap_or_default();
println!(
"{ip}\t{}\t{}\t{}\t{}\t{}\t{watts:.0}\t{}\t{}\t{bs}\t{sbs}",
data.device_info.make,
@@ -281,7 +288,10 @@ async fn msgs(ip_s: &str) {
Ok(Some(m)) => {
let d = m.get_data().await;
let th = |h: &Option<asic_rs::core::data::hashrate::HashRate>| {
h.clone().map(|x| x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
h.clone().map(|x| {
x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
.value
})
};
println!(
"{ip}: {} {} hashboards={:?} expected={:?}",
@@ -389,7 +399,7 @@ async fn lifecycle(ip_s: &str, verb: &str) {
/// Read (no tz arg) or set the miner's timezone (round 16 / G10). Capability-gated.
async fn timezone(ip_s: &str, tz: Option<&str>) {
use asic_rs::core::config::timezone::{Tz, TimezoneConfig};
use asic_rs::core::config::timezone::{TimezoneConfig, Tz};
let Ok(ip) = ip_s.parse::<std::net::IpAddr>() else {
eprintln!("bad ip {ip_s}");
return;
@@ -566,7 +576,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
TuningTarget::HashRate(hr)
}
None => {
eprintln!("miner reports no current hashrate; cannot build a hashrate target");
eprintln!(
"miner reports no current hashrate; cannot build a hashrate target"
);
return;
}
},
@@ -593,7 +605,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
}
} else if kind == "power" && m.supports_set_power_limit() {
match m.set_power_limit(Power::from_watts(value)).await {
Ok(v) => println!("set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"),
Ok(v) => println!(
"set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"
),
Err(e) => println!("set_power_limit({value} W) -> Err: {e:#}"),
}
} else {
@@ -680,7 +694,10 @@ async fn setpreset(ip_s: &str, name: &str) {
fn main() {
let args: Vec<String> = std::env::args().collect();
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(e) => {
eprintln!("tokio runtime: {e}");
+77 -53
View File
@@ -6,11 +6,11 @@
//! firmware registry, so `scan`'s callers never have to think about it.
use std::collections::HashMap;
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use asic_rs::MinerFactory;
use alkane_core::platform::write_private;
use asic_rs::core::traits::miner::MinerAuth;
use asic_rs::MinerFactory;
use crate::scan::config_path;
@@ -40,20 +40,9 @@ fn save_creds_file(file: &str, user: &str, pass: &str) -> std::io::Result<()> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
// Open (and create) with mode 0600 up front so a freshly created file is
// never world/group-readable, even for the instant before the write. For a
// pre-existing file the create mode is ignored, so also tighten it to 0600
// while it is still empty (post-truncate, pre-write) -- the plaintext is
// never on disk under a looser mode.
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(format!("{user}\n{pass}\n").as_bytes())?;
Ok(())
// Owner-only from creation on (0600 on Unix, re-tightened if the file
// already existed): the plaintext is never on disk under a looser mode.
write_private(&p, format!("{user}\n{pass}\n").as_bytes())
}
fn clear_creds_file(file: &str) -> std::io::Result<()> {
@@ -164,20 +153,14 @@ pub fn save_firmware_credentials(map: &HashMap<String, (String, String)>) -> std
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
let mut names: Vec<&String> = map.keys().collect();
names.sort();
let mut body = String::new();
for name in names {
let (user, pass) = &map[name];
f.write_all(format!("{name}\t{user}\t{pass}\n").as_bytes())?;
body.push_str(&format!("{name}\t{user}\t{pass}\n"));
}
Ok(())
write_private(&p, body.as_bytes())
}
/// Remove the per-firmware overrides file, if any. Not an error if none exists.
@@ -195,8 +178,8 @@ pub fn configured_factory() -> MinerFactory {
// (round 18 #12: config actions / refresh / pools / flash previously used
// asic-rs's 10s default, so on a slow link they could fail to reach miners a
// longer-timeout scan had found). start_scan may still override it explicitly.
let mut factory =
MinerFactory::new().with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
let mut factory = MinerFactory::new()
.with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
let global = load_credentials();
let per_fw = load_firmware_credentials();
if global.is_none() && per_fw.is_empty() {
@@ -218,25 +201,47 @@ pub fn configured_factory() -> MinerFactory {
mod tests {
use super::*;
/// Unix: the file is mode 0600. Windows relies on the profile directory's
/// owner-only ACL (see `alkane_core::platform::write_private`), so only
/// existence is checked there.
fn assert_owner_only(path: &std::path::Path, why: &str) {
let meta = std::fs::metadata(path).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "{why}");
}
#[cfg(not(unix))]
assert!(meta.is_file(), "{why}");
}
#[test]
fn credentials_round_trip_and_file_perms() {
// config_path() reads $HOME; point it at a private temp dir. HOME is
// process-global, so serialise against other HOME-mutating tests via the
// shared lock and restore HOME afterward (round 18 #12).
let _home = crate::model::HOME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let prev = std::env::var_os("HOME");
let _home = crate::model::HOME_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let root_var = alkane_core::platform::CONFIG_ROOT_VAR;
let prev = std::env::var_os(root_var);
let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("HOME", &dir);
std::env::set_var(root_var, &dir);
assert_eq!(load_credentials(), None, "no file -> None");
save_credentials("admin", "hunter2").unwrap();
assert_eq!(load_credentials(), Some(("admin".to_string(), "hunter2".to_string())));
assert_eq!(
load_credentials(),
Some(("admin".to_string(), "hunter2".to_string()))
);
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600");
assert_owner_only(
&config_path(CREDENTIALS_FILE),
"credentials file must be 0600",
);
// configured_factory() must construct in both branches without panicking:
// with saved credentials (fans auth across every firmware backend) ...
@@ -246,15 +251,20 @@ mod tests {
// 0600 by save_credentials (the create-mode is ignored for an existing
// file, so the explicit set_permissions is what protects it).
let path = config_path(CREDENTIALS_FILE);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
}
save_credentials("admin2", "s3cr3t").unwrap();
let meta = std::fs::metadata(&path).unwrap();
assert_owner_only(
&path,
"save over a pre-existing 0644 file must re-tighten to 0600",
);
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"save over a pre-existing 0644 file must re-tighten to 0600"
load_credentials(),
Some(("admin2".to_string(), "s3cr3t".to_string()))
);
assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string())));
clear_credentials().unwrap();
// ... and with no saved credentials (plain MinerFactory::new()).
@@ -265,35 +275,49 @@ mod tests {
// Per-firmware overrides (round 12 #13). Kept in this same test because
// HOME is process-global: a second #[test] mutating it would race under
// cargo's default parallel runner.
assert!(load_firmware_credentials().is_empty(), "no file -> empty map");
assert!(
load_firmware_credentials().is_empty(),
"no file -> empty map"
);
let mut fw = HashMap::new();
fw.insert("WhatsMiner Stock".to_string(), ("super".to_string(), "sup3r".to_string()));
fw.insert(
"WhatsMiner Stock".to_string(),
("super".to_string(), "sup3r".to_string()),
);
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
save_firmware_credentials(&fw).unwrap();
// 0600, and it round-trips (an empty username survives the tab format).
let fwpath = config_path(FIRMWARE_CREDENTIALS_FILE);
assert_eq!(
std::fs::metadata(&fwpath).unwrap().permissions().mode() & 0o777,
0o600,
"per-firmware creds file must be 0600"
);
assert_owner_only(&fwpath, "per-firmware creds file must be 0600");
let back = load_firmware_credentials();
assert_eq!(back.get("WhatsMiner Stock"), Some(&("super".into(), "sup3r".into())));
assert_eq!(
back.get("WhatsMiner Stock"),
Some(&("super".into(), "sup3r".into()))
);
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
assert_eq!(back.len(), 2);
// Shipped-default lookup: known firmware resolves, unknown blanks.
assert_eq!(firmware_default_for("AntMiner Stock"), ("root".into(), "root".into()));
assert_eq!(firmware_default_for("nonexistent"), (String::new(), String::new()));
assert_eq!(
firmware_default_for("AntMiner Stock"),
("root".into(), "root".into())
);
assert_eq!(
firmware_default_for("nonexistent"),
(String::new(), String::new())
);
// Overrides + no global still builds a factory.
let _ = configured_factory();
// Saving an empty map clears the file (no stale overrides linger).
save_firmware_credentials(&HashMap::new()).unwrap();
assert!(load_firmware_credentials().is_empty(), "empty save -> cleared");
assert!(
load_firmware_credentials().is_empty(),
"empty save -> cleared"
);
clear_firmware_credentials().unwrap(); // idempotent
match prev {
Some(v) => std::env::set_var("HOME", v),
None => std::env::remove_var("HOME"),
Some(v) => std::env::set_var(root_var, v),
None => std::env::remove_var(root_var),
}
let _ = std::fs::remove_dir_all(&dir);
}
+77 -20
View File
@@ -100,28 +100,62 @@ fn scalar_columns() -> Vec<Col> {
("slow", |r| r.slow.to_string()),
("paused", |r| r.paused.to_string()),
("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")),
("write_locked", |r| opt_bool(r.write_locked, "locked", "unlocked")),
("light_flashing", |r| opt_bool(r.light_flashing, "on", "off")),
("write_locked", |r| {
opt_bool(r.write_locked, "locked", "unlocked")
}),
("light_flashing", |r| {
opt_bool(r.light_flashing, "on", "off")
}),
("hashrate_ths", |r| num(r.hashrate_ths)),
("expected_ths", |r| num(r.expected_ths)),
("efficiency_j_th", |r| num(r.efficiency)),
("power_w", |r| num(r.power_w)),
("tuning_percent", |r| r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()),
("tuning_percent", |r| {
r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()
}),
("chip_temp_c", |r| num(r.chip_temp_c)),
("fluid_temp_c", |r| num(r.fluid_temp_c)),
("env_temp_c", |r| num(r.env_temp_c)),
("outlet_temp_c", |r| num(r.outlet_temp_c)),
("psu_fan_rpm", |r| num(r.psu_fan_rpm)),
("fan_count", |r| r.fan_count.map(|v| v.to_string()).unwrap_or_default()),
("expected_fans", |r| r.expected_fans.map(|v| v.to_string()).unwrap_or_default()),
("total_chips", |r| r.total_chips.map(|v| v.to_string()).unwrap_or_default()),
("expected_chips", |r| r.expected_chips.map(|v| v.to_string()).unwrap_or_default()),
("hashboards", |r| r.hashboards.map(|v| v.to_string()).unwrap_or_default()),
("expected_hashboards", |r| r.expected_hashboards.map(|v| v.to_string()).unwrap_or_default()),
("uptime_secs", |r| if r.uptime_secs > 0 { r.uptime_secs.to_string() } else { String::new() }),
("fan_count", |r| {
r.fan_count.map(|v| v.to_string()).unwrap_or_default()
}),
("expected_fans", |r| {
r.expected_fans.map(|v| v.to_string()).unwrap_or_default()
}),
("total_chips", |r| {
r.total_chips.map(|v| v.to_string()).unwrap_or_default()
}),
("expected_chips", |r| {
r.expected_chips.map(|v| v.to_string()).unwrap_or_default()
}),
("hashboards", |r| {
r.hashboards.map(|v| v.to_string()).unwrap_or_default()
}),
("expected_hashboards", |r| {
r.expected_hashboards
.map(|v| v.to_string())
.unwrap_or_default()
}),
("uptime_secs", |r| {
if r.uptime_secs > 0 {
r.uptime_secs.to_string()
} else {
String::new()
}
}),
("best_share", |r| r.best_share.map(num).unwrap_or_default()),
("session_best_share", |r| r.session_best_share.map(num).unwrap_or_default()),
("pool_account", |r| r.worker.split_once('.').map(|(a, _)| a).unwrap_or(&r.worker).to_string()),
("session_best_share", |r| {
r.session_best_share.map(num).unwrap_or_default()
}),
("pool_account", |r| {
r.worker
.split_once('.')
.map(|(a, _)| a)
.unwrap_or(&r.worker)
.to_string()
}),
("pool_url", |r| r.pool_url.clone()),
("errors", |r| r.errors.join("; ")),
]
@@ -137,7 +171,10 @@ pub const GROUP_POOLS: &str = "pools";
/// Every selectable export field, in output order: each scalar column header,
/// then the four variable-length group keys.
pub fn export_field_names() -> Vec<String> {
let mut v: Vec<String> = scalar_columns().iter().map(|(h, _)| (*h).to_string()).collect();
let mut v: Vec<String> = scalar_columns()
.iter()
.map(|(h, _)| (*h).to_string())
.collect();
v.push(GROUP_BOARD_TEMPS.to_string());
v.push(GROUP_FANS.to_string());
v.push(GROUP_BOARD_STATUS.to_string());
@@ -152,16 +189,26 @@ pub fn rows_to_csv_selected(
rows: &[MinerRow],
selected: &std::collections::HashSet<String>,
) -> String {
let cols: Vec<Col> =
scalar_columns().into_iter().filter(|(h, _)| selected.contains(*h)).collect();
let cols: Vec<Col> = scalar_columns()
.into_iter()
.filter(|(h, _)| selected.contains(*h))
.collect();
// A group's columns appear only when it is selected; an unselected group's
// width stays 0, so the header/value loops below emit nothing for it.
let width = |want: bool, f: &dyn Fn(&MinerRow) -> usize| -> usize {
if want { rows.iter().map(f).max().unwrap_or(0) } else { 0 }
if want {
rows.iter().map(f).max().unwrap_or(0)
} else {
0
}
};
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| r.board_temps.len());
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| {
r.board_temps.len()
});
let max_fans = width(selected.contains(GROUP_FANS), &|r| r.fan_rpms.len());
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| r.board_status.len());
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| {
r.board_status.len()
});
let max_pools = width(selected.contains(GROUP_POOLS), &|r| r.pools.len());
// Header.
@@ -193,7 +240,13 @@ pub fn rows_to_csv_selected(
vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default());
}
for i in 0..max_boards {
vals.push(r.board_status.get(i).map(board_health_str).unwrap_or("").to_string());
vals.push(
r.board_status
.get(i)
.map(board_health_str)
.unwrap_or("")
.to_string(),
);
}
for i in 0..max_pools {
let (u, w) = r.pools.get(i).cloned().unwrap_or_default();
@@ -222,7 +275,11 @@ mod tests {
fan_rpms: vec![6000.0, 6100.0],
..Default::default()
},
MinerRow { ip: "10.0.0.2".into(), model: "M30S".into(), ..Default::default() },
MinerRow {
ip: "10.0.0.2".into(),
model: "M30S".into(),
..Default::default()
},
];
let all: std::collections::HashSet<String> = export_field_names().into_iter().collect();
let csv = rows_to_csv_selected(&rows, &all);
+203 -39
View File
@@ -42,9 +42,22 @@ impl Board {
let slow = is_slow(self.mining, self.hashrate, self.expected);
// A few extra metrics so the demo/offline mode shows non-empty values
// for some of the additional columns.
let last_octet: u8 = self.ip.rsplit('.').next().and_then(|s| s.parse().ok()).unwrap_or(0);
let last_octet: u8 = self
.ip
.rsplit('.')
.next()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let (boards, chips, efficiency) = if self.mining {
(Some(3u32), Some(210u32), if self.hashrate > 0.0 { self.power / self.hashrate } else { 0.0 })
(
Some(3u32),
Some(210u32),
if self.hashrate > 0.0 {
self.power / self.hashrate
} else {
0.0
},
)
} else {
(None, None, 0.0)
};
@@ -63,7 +76,11 @@ impl Board {
// Per-board hashrate for the R2 Health tooltip demo: split the total three
// ways with a little variety (index-aligned with the 3 boards).
let board_hashrates = if self.mining && self.hashrate > 0.0 {
vec![self.hashrate * 0.34, self.hashrate * 0.35, self.hashrate * 0.31]
vec![
self.hashrate * 0.34,
self.hashrate * 0.35,
self.hashrate * 0.31,
]
} else {
vec![]
};
@@ -147,7 +164,10 @@ impl Board {
slow,
paused: self.paused,
// offline defaults to false (online); these bench rows are reachable.
mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)),
mac: format!(
"AA:BB:CC:00:{:02X}:{last_octet:02X}",
last_octet.wrapping_mul(3)
),
hostname: format!("miner-{last_octet}"),
hashboards: boards,
expected_hashboards: Some(3),
@@ -156,22 +176,40 @@ impl Board {
psu_fan_rpm: if self.mining { self.fan * 0.9 } else { 0.0 },
// PSU info demo (round 17 R5): mining units show a version + rated
// envelope + live output, so the columns and the R2 PSU tooltip render.
psu_version: if self.mining { "22 (117)".to_string() } else { String::new() },
psu_version: if self.mining {
"22 (117)".to_string()
} else {
String::new()
},
psu_voltage_min_v: self.mining.then_some(11.88),
psu_voltage_max_v: self.mining.then_some(15.18),
psu_out_voltage_v: self.mining.then_some(13.2),
psu_out_current_a: self.mining.then_some(210.0),
uptime_secs: if self.mining { 3600 * 24 * 2 + 3600 * 5 } else { 0 },
uptime_secs: if self.mining {
3600 * 24 * 2 + 3600 * 5
} else {
0
},
// One unit is "being located" so the Light column's yellow dot is
// demonstrable offline (round 11 #10).
light_flashing: Some(self.ip == "10.255.1.167"),
pool_url: if self.worker.is_empty() { String::new() } else { "stratum+tcp://pool.blueflare:3333".to_string() },
pool_url: if self.worker.is_empty() {
String::new()
} else {
"stratum+tcp://pool.blueflare:3333".to_string()
},
pools: if self.worker.is_empty() {
Vec::new()
} else {
vec![
("stratum+tcp://pool.blueflare:3333".to_string(), self.worker.to_string()),
("stratum+tcp://backup.blueflare:3333".to_string(), format!("{}_bak", self.worker)),
(
"stratum+tcp://pool.blueflare:3333".to_string(),
self.worker.to_string(),
),
(
"stratum+tcp://backup.blueflare:3333".to_string(),
format!("{}_bak", self.worker),
),
]
},
operating_state: if self.paused {
@@ -223,9 +261,18 @@ impl Board {
// is exercisable offline on units that advertise preset support.
presets: if self.mining {
vec![
crate::model::MinerPreset { name: "default".into(), pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()) },
crate::model::MinerPreset { name: "540MHz".into(), pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()) },
crate::model::MinerPreset { name: "490MHz".into(), pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()) },
crate::model::MinerPreset {
name: "default".into(),
pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()),
},
crate::model::MinerPreset {
name: "540MHz".into(),
pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()),
},
crate::model::MinerPreset {
name: "490MHz".into(),
pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()),
},
]
} else {
Vec::new()
@@ -247,35 +294,152 @@ pub fn bench_fleet() -> Vec<MinerRow> {
let boards = [
// firmware families span the palette (Stock/VNish/Braiins/LuxOS/ePIC/
// Hive/BixBit/Alkane) so the offline demo shows the Firmware colouring.
Board { ip: "10.255.1.112", make: "Antminer", model_id: "S17", board: "Xilinx", firmware: "Stock", fw_version: "",
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
worker: "", mining: false, paused: false },
Board { ip: "10.255.1.166", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "VNish", fw_version: "1.2.8",
hashrate: 95.0, expected: 96.0, power: 3250.0, temp: 65.0, fan: 4200.0,
worker: "blueflare.s19", mining: true, paused: false },
Board { ip: "10.255.1.152", make: "Antminer", model_id: "S19jPro", board: "AMLogic", firmware: "Braiins", fw_version: "25.05.1",
hashrate: 100.0, expected: 104.0, power: 3100.0, temp: 62.0, fan: 3900.0,
worker: "blueflare.s19jpro", mining: true, paused: false },
Board { ip: "10.255.1.167", make: "Antminer", model_id: "S19KPro", board: "AMLogic", firmware: "LuxOS", fw_version: "2024.9.0",
hashrate: 120.0, expected: 128.0, power: 3300.0, temp: 68.0, fan: 4500.0,
worker: "blueflare.s19kpro", mining: true, paused: false },
Board { ip: "10.255.1.149", make: "Antminer", model_id: "S21Pro", board: "CVITek", firmware: "ePIC", fw_version: "1.0.3",
hashrate: 60.0, expected: 200.0, power: 1500.0, temp: 55.0, fan: 3000.0,
worker: "blueflare.s21pro", mining: true, paused: false }, // slow: 60/200 = 30%
Board { ip: "10.255.1.126", make: "Whatsminer", model_id: "M30SVE40", board: "H3", firmware: "Stock", fw_version: "H3.0.1",
hashrate: 92.0, expected: 96.0, power: 3400.0, temp: 70.0, fan: 4800.0,
worker: "blueflare.h3", mining: true, paused: false },
Board { ip: "10.255.1.131", make: "Whatsminer", model_id: "M30SPlusVE40", board: "H616", firmware: "Hiveon", fw_version: "1.05",
hashrate: 100.0, expected: 100.0, power: 3450.0, temp: 71.0, fan: 4900.0,
worker: "blueflare.h616", mining: true, paused: false },
Board { ip: "10.255.1.148", make: "Whatsminer", model_id: "M50VH50", board: "H6", firmware: "Bixbit", fw_version: "0.9.9.4",
hashrate: 118.0, expected: 122.0, power: 3300.0, temp: 66.0, fan: 4600.0,
worker: "blueflare.m50", mining: true, paused: false },
Board {
ip: "10.255.1.112",
make: "Antminer",
model_id: "S17",
board: "Xilinx",
firmware: "Stock",
fw_version: "",
hashrate: 0.0,
expected: 0.0,
power: 0.0,
temp: 0.0,
fan: 0.0,
worker: "",
mining: false,
paused: false,
},
Board {
ip: "10.255.1.166",
make: "Antminer",
model_id: "S19",
board: "BeagleBoneBlack",
firmware: "VNish",
fw_version: "1.2.8",
hashrate: 95.0,
expected: 96.0,
power: 3250.0,
temp: 65.0,
fan: 4200.0,
worker: "blueflare.s19",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.152",
make: "Antminer",
model_id: "S19jPro",
board: "AMLogic",
firmware: "Braiins",
fw_version: "25.05.1",
hashrate: 100.0,
expected: 104.0,
power: 3100.0,
temp: 62.0,
fan: 3900.0,
worker: "blueflare.s19jpro",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.167",
make: "Antminer",
model_id: "S19KPro",
board: "AMLogic",
firmware: "LuxOS",
fw_version: "2024.9.0",
hashrate: 120.0,
expected: 128.0,
power: 3300.0,
temp: 68.0,
fan: 4500.0,
worker: "blueflare.s19kpro",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.149",
make: "Antminer",
model_id: "S21Pro",
board: "CVITek",
firmware: "ePIC",
fw_version: "1.0.3",
hashrate: 60.0,
expected: 200.0,
power: 1500.0,
temp: 55.0,
fan: 3000.0,
worker: "blueflare.s21pro",
mining: true,
paused: false,
}, // slow: 60/200 = 30%
Board {
ip: "10.255.1.126",
make: "Whatsminer",
model_id: "M30SVE40",
board: "H3",
firmware: "Stock",
fw_version: "H3.0.1",
hashrate: 92.0,
expected: 96.0,
power: 3400.0,
temp: 70.0,
fan: 4800.0,
worker: "blueflare.h3",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.131",
make: "Whatsminer",
model_id: "M30SPlusVE40",
board: "H616",
firmware: "Hiveon",
fw_version: "1.05",
hashrate: 100.0,
expected: 100.0,
power: 3450.0,
temp: 71.0,
fan: 4900.0,
worker: "blueflare.h616",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.148",
make: "Whatsminer",
model_id: "M50VH50",
board: "H6",
firmware: "Bixbit",
fw_version: "0.9.9.4",
hashrate: 118.0,
expected: 122.0,
power: 3300.0,
temp: 66.0,
fan: 4600.0,
worker: "blueflare.m50",
mining: true,
paused: false,
},
// Rebucketed from idle/not-hashing to paused so the "paused"
// status/KPI bucket is exercisable in the fake-scan/offline demo.
Board { ip: "10.255.1.115", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "Alkane", fw_version: "0.1",
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
worker: "", mining: false, paused: true },
Board {
ip: "10.255.1.115",
make: "Antminer",
model_id: "S19",
board: "BeagleBoneBlack",
firmware: "Alkane",
fw_version: "0.1",
hashrate: 0.0,
expected: 0.0,
power: 0.0,
temp: 0.0,
fan: 0.0,
worker: "",
mining: false,
paused: true,
},
];
boards.into_iter().map(Board::into_row).collect()
}
+2 -3
View File
@@ -27,7 +27,7 @@ impl Lang {
pub fn label(self) -> &'static str {
match self {
Lang::En => "English",
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
Lang::Ru => "\u{0420}\u{0443}\u{0441}\u{0441}\u{043a}\u{0438}\u{0439}", // Русский
Lang::Fr => "Fran\u{e7}ais",
Lang::Es => "Espa\u{f1}ol",
@@ -71,8 +71,7 @@ static CURRENT: AtomicU8 = AtomicU8::new(0);
const LANG_FILE: &str = "language.txt";
fn config_path() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
PathBuf::from(home).join(".config/alkane-toolkit").join(LANG_FILE)
alkane_core::platform::config_path(LANG_FILE)
}
/// Load the saved language into the global (call once at startup).
+10 -3
View File
@@ -32,13 +32,17 @@ pub fn scan_log(ip: &str, brand: &str, timeout_secs: u64) -> Result<LogScan, Str
if brand.eq_ignore_ascii_case("whatsminer") {
let resp = crate::access_probe::whatsminer_get_error_code(ip)
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
return Ok(LogScan { text: tail(&resp, MAX_LOG_BYTES) });
return Ok(LogScan {
text: tail(&resp, MAX_LOG_BYTES),
});
}
let text = crate::scan::fetch_log(ip, timeout_secs)?;
if text.trim().is_empty() {
return Err("the miner returned an empty log".to_string());
}
Ok(LogScan { text: tail(&text, MAX_LOG_BYTES) })
Ok(LogScan {
text: tail(&text, MAX_LOG_BYTES),
})
}
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
@@ -55,7 +59,10 @@ fn tail(s: &str, max: usize) -> String {
start += 1;
}
// then advance to the next line boundary so we don't cut a line in half
let start = s[start..].find('\n').map(|i| start + i + 1).unwrap_or(start);
let start = s[start..]
.find('\n')
.map(|i| start + i + 1)
.unwrap_or(start);
format!("[... earlier log trimmed ...]\n{}", &s[start..])
}
+4 -1
View File
@@ -12,7 +12,10 @@ static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Local wall-clock HH:MM:SS for a log line. Uses the system clock offset from
/// UTC via the TZ-less epoch; good enough for an activity log timestamp.
fn stamp() -> String {
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let t = secs % 86_400;
format!("{:02}:{:02}:{:02}", t / 3600, (t % 3600) / 60, t % 60)
}
+53 -6
View File
@@ -1,13 +1,18 @@
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
//! alkane-toolkit: primary view (docs/UI-SPEC.md).
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
// A GUI application on Windows: no console window opens behind it. The
// headless modes below re-attach to the console they were started from.
#![cfg_attr(windows, windows_subsystem = "windows")]
mod access_probe;
mod askpass;
mod credentials;
mod export;
mod fixtures;
mod i18n;
mod logs;
mod log_scan;
mod logs;
mod model;
mod naming;
mod pool_prefs;
@@ -16,8 +21,16 @@ mod restore;
mod scan;
mod ui;
fn main() {
// ssh runs this executable as its askpass helper for password logins
// (askpass.rs); answer and exit before anything else starts.
if let Some(code) = askpass::serve_if_askpass() {
std::process::exit(code);
}
if headless_mode() {
attach_parent_console();
}
// Headless workflow self-test: render the bench-fleet fixtures through the
// real widgets and check the table + KPIs against the expected hardware
// output. Run under a virtual display (see scripts/ui-selftest.sh).
@@ -61,10 +74,10 @@ fn main() {
// Load the saved UI language before any strings are built (round 15 #13).
i18n::init();
// Bootstrap the wx app + main frame (upstream bridge).
// Bootstrap the wx app + main frame (upstream bridge). This also picks the
// light/dark appearance (system, or ALKANE_APPEARANCE=light|dark) before the
// frame exists, which wxMSW requires.
wx_rs::init_app("alkane-toolkit", 1280, 800);
// Follow the system light/dark appearance.
wx_rs::set_appearance_system();
// Build the UI-SPEC primary view into the frame.
let frame = wx_rs::Widget::main_frame();
@@ -93,3 +106,37 @@ fn run_selftest() -> i32 {
1
}
}
/// True when the process runs one of the headless check modes instead of the GUI.
fn headless_mode() -> bool {
["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"]
.iter()
.any(|v| std::env::var_os(v).is_some())
}
/// A Windows GUI-subsystem process has no console, so output from the headless
/// modes would vanish when they are run from a terminal. Attach to the parent's
/// console in that case. Redirected output (pipes, files, CI) already has valid
/// standard handles and is left alone.
#[cfg(windows)]
fn attach_parent_console() {
type Handle = *mut core::ffi::c_void;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
#[link(name = "kernel32")]
extern "system" {
fn GetStdHandle(which: u32) -> Handle;
fn AttachConsole(process_id: u32) -> i32;
}
// SAFETY: plain Win32 calls with constant arguments; failure (no parent
// console, already attached) is harmless and leaves the process unchanged.
unsafe {
let out = GetStdHandle(STD_OUTPUT_HANDLE);
if out.is_null() || out as isize == -1 {
AttachConsole(ATTACH_PARENT_PROCESS);
}
}
}
#[cfg(not(windows))]
fn attach_parent_console() {}
File diff suppressed because it is too large Load Diff
+102 -18
View File
@@ -58,7 +58,11 @@ pub fn firmware_family(raw: &str) -> (String, Option<String>) {
// Vendor prefixes asic-rs prepends on stock-firmware family strings, matched
// case-insensitively.
for vendor in ["AntMiner", "WhatsMiner"] {
if trimmed.len() > vendor.len() && trimmed[..vendor.len()].eq_ignore_ascii_case(vendor) {
if trimmed.len() > vendor.len()
&& trimmed
.get(..vendor.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(vendor))
{
let rest = trimmed[vendor.len()..].trim();
if !rest.is_empty() {
return (rest.to_string(), Some(vendor.to_string()));
@@ -230,7 +234,10 @@ fn clean_antminer(id: &str) -> String {
/// Normalise a raw control-board name for matching: drop spaces/punctuation and
/// uppercase, so "BeagleBone Black", "BeagleBoneBlack" and "BBB" all collapse.
fn compact_upper(s: &str) -> String {
s.chars().filter(|c| c.is_ascii_alphanumeric()).flat_map(|c| c.to_uppercase()).collect()
s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.flat_map(|c| c.to_uppercase())
.collect()
}
/// The control-board short code for the Control-board column, e.g.
@@ -361,7 +368,10 @@ mod tests {
assert_eq!(chip_type_for_model("Antminer", "S19"), Some("BM1398"));
assert_eq!(chip_type_for_model("Antminer", "T19"), Some("BM1398"));
// Raw "Unknown" passthrough with brand + parenthetical normalizes to S19.
assert_eq!(chip_type_for_model("Antminer", "ANTMINER S19 (88)"), Some("BM1398"));
assert_eq!(
chip_type_for_model("Antminer", "ANTMINER S19 (88)"),
Some("BM1398")
);
// WhatsMiner chips are not cleanly named -> never derived.
assert_eq!(chip_type_for_model("Whatsminer", "M30S+VE40"), None);
// Unknown Antminer model -> None (no guess).
@@ -427,23 +437,56 @@ mod tests {
#[test]
fn control_board_short_codes() {
// Antminer families (board name as asic-rs renders the enum variant).
assert_eq!(control_board_code("Antminer", "BeagleBoneBlack", "S19"), "BBB (C77)");
assert_eq!(
control_board_code("Antminer", "BeagleBoneBlack", "S19"),
"BBB (C77)"
);
// Also accept the spaced form some layers produce.
assert_eq!(control_board_code("Antminer", "BeagleBone Black", "S19"), "BBB (C77)");
assert_eq!(control_board_code("Antminer", "CVITek", "S21 Pro"), "CVI (C88)");
assert_eq!(control_board_code("Antminer", "Xilinx", "S17 Pro"), "XIL (C49)");
assert_eq!(
control_board_code("Antminer", "BeagleBone Black", "S19"),
"BBB (C77)"
);
assert_eq!(
control_board_code("Antminer", "CVITek", "S21 Pro"),
"CVI (C88)"
);
assert_eq!(
control_board_code("Antminer", "Xilinx", "S17 Pro"),
"XIL (C49)"
);
assert_eq!(control_board_code("Antminer", "Xilinx", "T17"), "XIL (C49)");
assert_eq!(control_board_code("Antminer", "Xilinx", "S19 Pro"), "XIL (C55)");
assert_eq!(control_board_code("Antminer", "AMLogic", "S19j Pro"), "AML (C76)");
assert_eq!(control_board_code("Antminer", "AMLogic", "S19k Pro"), "AML (CBE)");
assert_eq!(control_board_code("Antminer", "AMLogic", "S19 XP"), "AML (CBE)");
assert_eq!(
control_board_code("Antminer", "Xilinx", "S19 Pro"),
"XIL (C55)"
);
assert_eq!(
control_board_code("Antminer", "AMLogic", "S19j Pro"),
"AML (C76)"
);
assert_eq!(
control_board_code("Antminer", "AMLogic", "S19k Pro"),
"AML (CBE)"
);
assert_eq!(
control_board_code("Antminer", "AMLogic", "S19 XP"),
"AML (CBE)"
);
// WhatsMiner families.
assert_eq!(control_board_code("Whatsminer", "H3", "M30S"), "H3 (CB2)");
assert_eq!(control_board_code("Whatsminer", "H6", "M50"), "H6 (CB4)");
assert_eq!(control_board_code("Whatsminer", "H6OS", "M50"), "H6os (CB4)");
assert_eq!(control_board_code("Whatsminer", "H616", "M30S+"), "H616 (CB6)");
assert_eq!(
control_board_code("Whatsminer", "H6OS", "M50"),
"H6os (CB4)"
);
assert_eq!(
control_board_code("Whatsminer", "H616", "M30S+"),
"H616 (CB6)"
);
// Unknown / blank pass through.
assert_eq!(control_board_code("Antminer", "Unknown: FOO", "S19"), "Unknown: FOO");
assert_eq!(
control_board_code("Antminer", "Unknown: FOO", "S19"),
"Unknown: FOO"
);
assert_eq!(control_board_code("Antminer", "", "S19"), "");
}
@@ -451,23 +494,35 @@ mod tests {
fn control_board_cpu_and_board_split() {
// CPU column vs board-code column.
assert_eq!(control_board_cpu("Antminer", "AMLogic", "S19j Pro"), "AML");
assert_eq!(control_board_board("Antminer", "AMLogic", "S19j Pro"), "C76");
assert_eq!(
control_board_board("Antminer", "AMLogic", "S19j Pro"),
"C76"
);
assert_eq!(control_board_cpu("Antminer", "CVITek", "S21 Pro"), "CVI");
assert_eq!(control_board_board("Antminer", "CVITek", "S21 Pro"), "C88");
assert_eq!(control_board_cpu("Whatsminer", "H616", "M30S+"), "H616");
assert_eq!(control_board_board("Whatsminer", "H616", "M30S+"), "CB6");
// S21 Pro on an AMLogic board is the 140mm CBE, not C76.
assert_eq!(control_board_board("Antminer", "AMLogic", "S21 Pro"), "CBE");
assert_eq!(control_board_code("Antminer", "AMLogic", "S21 Pro"), "AML (CBE)");
assert_eq!(
control_board_code("Antminer", "AMLogic", "S21 Pro"),
"AML (CBE)"
);
// Unknown -> cpu holds the raw string, no board code.
assert_eq!(control_board_cpu("Antminer", "Unknown: FOO", "S19"), "Unknown: FOO");
assert_eq!(
control_board_cpu("Antminer", "Unknown: FOO", "S19"),
"Unknown: FOO"
);
assert_eq!(control_board_board("Antminer", "Unknown: FOO", "S19"), "");
}
#[test]
fn firmware_family_splits_vendor_prefix() {
// Stock firmware: vendor word moves out of the family word (round 11 #6).
assert_eq!(firmware_family("AntMiner Stock"), ("Stock".to_string(), Some("AntMiner".to_string())));
assert_eq!(
firmware_family("AntMiner Stock"),
("Stock".to_string(), Some("AntMiner".to_string()))
);
assert_eq!(
firmware_family("WhatsMiner Stock"),
("Stock".to_string(), Some("WhatsMiner".to_string()))
@@ -477,6 +532,35 @@ mod tests {
assert_eq!(firmware_family("Braiins"), ("Braiins".to_string(), None));
// A bare vendor word with nothing after it is left as-is (not emptied).
assert_eq!(firmware_family("AntMiner"), ("AntMiner".to_string(), None));
// Firmware strings arrive from the network and may contain UTF-8 at
// the byte position used to check a vendor prefix.
let non_ascii = "AntMine\u{e9} Stock";
assert_eq!(firmware_family(non_ascii), (non_ascii.to_string(), None));
}
#[test]
#[ignore = "microbenchmark"]
fn bench_naming_transforms() {
let cases = [
("Antminer", "S19jPro", "AntMiner Stock", "Xilinx"),
("Antminer", "S21Pro", "VNish", "CVITek"),
("Whatsminer", "M30SPlusVE40", "WhatsMiner Stock", "H616"),
("Whatsminer", "M50SPlusPlusVK30", "Braiins", "H6"),
];
let iterations = 20_000;
let started = std::time::Instant::now();
for index in 0..iterations {
let (make, model, firmware, board) = cases[index % cases.len()];
let clean = clean_model(make, model);
std::hint::black_box(firmware_family(firmware));
std::hint::black_box(control_board_code(make, board, &clean));
std::hint::black_box(chip_type_for_model(make, model));
std::hint::black_box(clean);
}
let elapsed = started.elapsed();
let per = elapsed / iterations as u32;
println!("bench_naming_transforms: {per:?}/record");
assert!(elapsed < std::time::Duration::from_millis(500));
}
#[test]
+34 -33
View File
@@ -6,8 +6,6 @@
use std::path::PathBuf;
const CONFIG_DIR: &str = ".config/alkane-toolkit";
/// Which pool field a "+" menu belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolField {
@@ -36,8 +34,20 @@ impl PoolField {
PoolField::Account => Vec::new(),
// Per-miner worker-name placeholders (see MinerRow::expand_worker_template).
PoolField::Worker => vec![
"{ip1}", "{ip2}", "{ip3}", "{ip4}", "{serial}", "{mac}", "{nameplate-hr}",
"{brand}", "{model}", "{submodel}", "{cpu}", "{cb}", "{firmware}", "{hostname}",
"{ip1}",
"{ip2}",
"{ip3}",
"{ip4}",
"{serial}",
"{mac}",
"{nameplate-hr}",
"{brand}",
"{model}",
"{submodel}",
"{cpu}",
"{cb}",
"{firmware}",
"{hostname}",
],
PoolField::Password => vec!["x"],
}
@@ -60,15 +70,20 @@ pub const POOL_STRATUMS: &[(&str, &str)] = &[
];
fn config_path(file: &str) -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
PathBuf::from(home).join(CONFIG_DIR).join(file)
alkane_core::platform::config_path(file)
}
/// The user's saved values for `field`, in save order (most recent last).
pub fn load_saved(field: PoolField) -> Vec<String> {
std::fs::read_to_string(config_path(field.saved_file()))
.ok()
.map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect())
.map(|s| {
s.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(String::from)
.collect()
})
.unwrap_or_default()
}
@@ -88,28 +103,9 @@ pub fn save_all(field: PoolField, values: &[String]) -> std::io::Result<usize> {
Ok(out.len())
}
/// Write `data` to `path` with owner-only (0600) permissions from creation on
/// Unix, so a secret is never momentarily world-readable between write and chmod.
/// `mode()` only takes effect when the file is created, so an already-existing
/// file is also re-tightened; elsewhere this is a plain write.
/// Saved pool values can carry worker passwords, so they are written owner-only.
fn write_private(path: &std::path::Path, data: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
f.write_all(data)
}
#[cfg(not(unix))]
{
std::fs::write(path, data)
}
alkane_core::platform::write_private(path, data)
}
/// Trim every value, then drop empties, values equal to a built-in preset, and
@@ -153,13 +149,18 @@ mod tests {
#[test]
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
let presets = ["x", "{ip1}"];
let vals: Vec<String> = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"]
.iter()
.map(|s| s.to_string())
.collect();
let vals: Vec<String> = [
" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep",
]
.iter()
.map(|s| s.to_string())
.collect();
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
// "keep" all drop; " keep " is trimmed and kept.
assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]);
assert_eq!(
dedupe_saved(&presets, &vals),
vec!["myworker".to_string(), "keep".to_string()]
);
}
#[test]
+20 -4
View File
@@ -43,7 +43,12 @@ impl PresetView {
PresetView {
order: v.order.clone(),
// keep the visible columns in display order for stability
visible: v.order.iter().copied().filter(|c| v.visible.contains(c)).collect(),
visible: v
.order
.iter()
.copied()
.filter(|c| v.visible.contains(c))
.collect(),
sort: v.sort,
filters: v.filters.iter().map(|(k, f)| (*k, f.clone())).collect(),
}
@@ -62,7 +67,12 @@ impl PresetView {
let mut visible: HashSet<Column> = self.visible.iter().copied().collect();
visible.insert(Column::Ip); // IP is always shown
let filters: HashMap<Column, ColFilter> = self.filters.iter().cloned().collect();
ViewState { order, visible, sort: self.sort, filters }
ViewState {
order,
visible,
sort: self.sort,
filters,
}
}
}
@@ -134,8 +144,14 @@ mod tests {
// The Health column (round 13 #3) replaced these in the default profile.
assert!(!view.visible.contains(&Column::Error));
// Columns dropped from the default profile in round 11.
assert!(!view.visible.contains(&Column::BoardCode), "not in the default profile");
assert!(!view.visible.contains(&Column::Fan1), "not in the default profile");
assert!(
!view.visible.contains(&Column::BoardCode),
"not in the default profile"
);
assert!(
!view.visible.contains(&Column::Fan1),
"not in the default profile"
);
// to_view covers every column in `order`.
assert_eq!(view.order.len(), ALL_COLUMNS.len());
// Round-trip a snapshot back out.
+123 -37
View File
@@ -16,16 +16,20 @@
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use std::time::Duration;
use crate::scan::fake_scan_enabled;
pub enum RestoreMsg {
Started,
Result { ip: String, ok: bool, detail: String },
Result {
ip: String,
ok: bool,
detail: String,
},
Done,
}
@@ -87,7 +91,14 @@ pub fn start_restore(
break;
}
let (ok, detail) = restore_one(&t, &vnish_pass, &ssh_user, &ssh_pass);
if tx.send(RestoreMsg::Result { ip: t.ip, ok, detail }).is_err() {
if tx
.send(RestoreMsg::Result {
ip: t.ip,
ok,
detail,
})
.is_err()
{
return;
}
}
@@ -106,7 +117,12 @@ pub fn start_restore(
RestoreHandle { rx, cancel }
}
fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &str) -> (bool, String) {
fn restore_one(
t: &RestoreTarget,
vnish_pass: &str,
ssh_user: &str,
ssh_pass: &str,
) -> (bool, String) {
let fw = t.firmware.to_ascii_lowercase();
if fw.contains("vnish") || fw.contains("wildrose") || fw.contains("anthill") {
restore_vnish(&t.ip, vnish_pass)
@@ -115,7 +131,10 @@ fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &s
} else if fw.contains("braiins") || fw.contains("bos") {
restore_braiins(&t.ip, ssh_user, ssh_pass)
} else {
(false, format!("no restore-to-stock path for firmware '{}'", t.firmware))
(
false,
format!("no restore-to-stock path for firmware '{}'", t.firmware),
)
}
}
@@ -127,9 +146,17 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
let body = serde_json::json!({ "pw": pass }).to_string();
let unlock = match curl(
&[
"-s", "--connect-timeout", "5", "--max-time", "9",
"-X", "POST", "-H", "Content-Type: application/json",
"-d", "@-",
"-s",
"--connect-timeout",
"5",
"--max-time",
"9",
"-X",
"POST",
"-H",
"Content-Type: application/json",
"-d",
"@-",
&format!("http://{ip}/api/v1/unlock"),
],
Some(body.as_bytes()),
@@ -146,8 +173,15 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
};
match curl(
&[
"-s", "--connect-timeout", "5", "--max-time", "12",
"-X", "POST", "-H", &format!("Authorization: Bearer {token}"),
"-s",
"--connect-timeout",
"5",
"--max-time",
"12",
"-X",
"POST",
"-H",
&format!("Authorization: Bearer {token}"),
&format!("http://{ip}/api/v1/firmware/remove"),
],
None,
@@ -174,7 +208,10 @@ fn restore_luxos(ip: &str) -> (bool, String) {
.map(str::to_string)
});
let Some(session) = session.filter(|s| !s.is_empty()) else {
return (false, format!("no SessionID in logon response: {}", logon.trim()));
return (
false,
format!("no SessionID in logon response: {}", logon.trim()),
);
};
// serde-encode so the miner-supplied SessionID can't break or inject into the
// JSON-RPC command (round 18 #12).
@@ -206,22 +243,32 @@ fn restore_luxos(ip: &str) -> (bool, String) {
/// Braiins: SSH `uninstall.sh` (re-flashes the retained on-NAND stock backup).
fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
if pass.is_empty() {
return (false, "Braiins restore needs an SSH password (set the SSH login)".into());
return (
false,
"Braiins restore needs an SSH password (set the SSH login)".into(),
);
}
let target = format!("{user}@{ip}");
// sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it
// never shows up in the process list (round 18 #12). Host-key checking is
// deliberately disabled: these are LAN miners whose SSH host key changes on
// every reflash, so pinning it would break the very revert this performs.
// BatchMode stops any interactive prompt from hanging out the 60 s cap.
let mut cmd = Command::new("sshpass");
cmd.env("SSHPASS", pass);
cmd.arg("-e").arg("ssh");
// The password reaches ssh through the toolkit's own askpass helper (its
// environment, never argv, so it stays out of the process list; round 18
// #12), which works the same with Linux OpenSSH and Windows' ssh.exe. One
// password attempt and no terminal: a bad password fails fast instead of
// hanging out the 60 s cap. Host-key checking is deliberately disabled: these
// are LAN miners whose SSH host key changes on every reflash, so pinning it
// would break the very revert this performs.
let mut cmd = alkane_core::platform::quiet_command("ssh");
if let Err(e) = crate::askpass::ssh_with_password(&mut cmd, pass) {
return (false, e);
}
let known_hosts = format!("UserKnownHostsFile={}", alkane_core::platform::NULL_DEVICE);
cmd.args(crate::askpass::PASSWORD_AUTH_OPTIONS);
cmd.args([
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=8",
"-o",
"StrictHostKeyChecking=no",
"-o",
&known_hosts,
"-o",
"ConnectTimeout=8",
&target,
"uninstall.sh || /sbin/uninstall.sh",
]);
@@ -247,7 +294,12 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be
/// reported as a FAILURE, never a false success. A dropped connection or a
/// timeout after the command started is the expected signature of the reboot.
fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bool) -> (bool, String) {
fn classify_braiins(
stdout: &str,
stderr: &str,
code: Option<i32>,
timed_out: bool,
) -> (bool, String) {
let err = stderr.to_lowercase();
// ssh's own connection/auth failures (exit 255) never reach the remote command.
let conn_fail = [
@@ -264,7 +316,10 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
.any(|m| err.contains(m));
if conn_fail {
let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty());
return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error")));
return (
false,
format!("SSH failed: {}", why.unwrap_or("connection/auth error")),
);
}
let out = stdout.to_lowercase();
if out.contains("not found") || out.contains("no such") || err.contains("not found") {
@@ -273,14 +328,19 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
match code {
Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()),
None => (true, "SSH dropped (miner likely rebooting to stock)".into()),
_ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()),
_ if timed_out => (
true,
"SSH timed out (miner likely rebooting to stock)".into(),
),
Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())),
}
}
/// One luxminer :4028 request/response (line-framed, socket closes after reply).
fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?;
let addr: SocketAddr = format!("{ip}:4028")
.parse()
.map_err(|e| format!("bad addr: {e}"))?;
let t = Duration::from_secs(8);
let mut s = TcpStream::connect_timeout(&addr, t).map_err(|e| e.to_string())?;
s.set_read_timeout(Some(t)).ok();
@@ -300,7 +360,9 @@ fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
Err(_) => break,
}
}
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
Ok(String::from_utf8_lossy(&buf)
.trim_matches('\u{0}')
.to_string())
}
/// The captured result of a timed subprocess run.
@@ -316,7 +378,7 @@ struct CmdOutput {
/// timed out (a black-holed host); otherwise returns stdout even on a non-zero
/// exit (curl prints useful bodies/status on failures).
fn curl(args: &[&str], stdin_data: Option<&[u8]>) -> Result<String, String> {
let mut cmd = Command::new("curl");
let mut cmd = alkane_core::platform::quiet_command("curl");
cmd.args(args);
let out = run_with_timeout(cmd, Duration::from_secs(15), stdin_data)?;
if out.timed_out && out.stdout.is_empty() {
@@ -391,24 +453,45 @@ mod tests {
// The critical regression guard (round 18 #12): a wrong password or an
// unreachable miner writes to stderr, leaves stdout empty, and exits
// non-zero -- it must report failure, never "restored".
let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false);
let (ok, msg) =
classify_braiins("", "Permission denied, please try again.", Some(255), false);
assert!(!ok, "wrong password must not report success");
assert!(msg.to_lowercase().contains("ssh failed"), "{msg}");
let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false);
let (ok, _) = classify_braiins(
"",
"ssh: connect to host 10.0.0.9 port 22: Connection refused",
Some(255),
false,
);
assert!(!ok, "unreachable miner must not report success");
let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false);
let (ok, _) = classify_braiins(
"",
"ssh: Could not resolve hostname miner: Name or service not known",
Some(255),
false,
);
assert!(!ok, "unresolvable host must not report success");
// Genuine outcomes.
let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false);
assert!(ok, "clean exit 0 is success");
let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false);
let (ok, _) = classify_braiins(
"",
"Connection to 10.0.0.5 closed by remote host.",
None,
false,
);
assert!(ok, "connection dropped mid-command (reboot) is success");
let (ok, _) = classify_braiins("", "", None, true);
assert!(ok, "timeout after the command started (reboot) is success");
let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false);
let (ok, _) = classify_braiins(
"bash: uninstall.sh: command not found\n",
"",
Some(127),
false,
);
assert!(!ok, "missing uninstall.sh is a failure");
}
@@ -416,7 +499,10 @@ mod tests {
fn firmware_selects_the_right_flow() {
// The dispatcher only recognises the three revertible aftermarket
// families; anything else has no restore path.
let mk = |fw: &str| RestoreTarget { ip: "0.0.0.0".into(), firmware: fw.into() };
let mk = |fw: &str| RestoreTarget {
ip: "0.0.0.0".into(),
firmware: fw.into(),
};
// Unknown firmware is rejected cleanly (no network attempt in the branch).
let (ok, detail) = restore_one(&mk("Stock"), "", "", "");
assert!(!ok);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
Application manifest for alkane-toolkit.exe (embedded by windows/alkane-toolkit.rc).
- Common Controls v6: themed native controls (Windows 10/11 visual styles)
instead of the Windows 95 look.
- Per-monitor DPI awareness v2: crisp at any scale factor; wx rescales
windows when they move between monitors.
- supportedOS Windows 10/11 (the Rust toolchain's own minimum).
- activeCodePage UTF-8: the C runtime and any narrow-string Win32 call speak
the same UTF-8 the Rust side does.
- longPathAware: settings/export paths beyond MAX_PATH work when enabled.
- asInvoker: never asks for elevation.
-->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="Blueflare.AlkaneToolkit" version="1.0.0.0"
processorArchitecture="amd64"/>
<description>Alkane Toolkit</description>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls"
version="6.0.0.0" processorArchitecture="*"
publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
<activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
</windowsSettings>
</application>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

@@ -0,0 +1,42 @@
// Windows resources for alkane-toolkit.exe, compiled by crates/alkane-gui/build.rs
// with the windres named by `wx-config --rescomp`. ALKANE_VER_* come from the
// crate version (which CI stamps per release).
// wxMSW's own resources (stock cursors and bitmaps). Its built-in manifest is
// suppressed: the application manifest below replaces it.
#define wxUSE_NO_MANIFEST 1
#include "wx/msw/wx.rc"
// The first icon in the file is the one Explorer and the taskbar show.
aaaa ICON "alkane-toolkit.ico"
CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "alkane-toolkit.exe.manifest"
VS_VERSION_INFO VERSIONINFO
FILEVERSION ALKANE_VER_MAJOR, ALKANE_VER_MINOR, ALKANE_VER_PATCH, 0
PRODUCTVERSION ALKANE_VER_MAJOR, ALKANE_VER_MINOR, ALKANE_VER_PATCH, 0
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS 0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "CompanyName", "Blueflare"
VALUE "FileDescription", "Alkane Toolkit"
VALUE "FileVersion", ALKANE_VER_STR
VALUE "InternalName", "alkane-toolkit"
VALUE "LegalCopyright", "Copyright (c) 2026 Blueflare (MIT License)"
VALUE "OriginalFilename", "alkane-toolkit.exe"
VALUE "ProductName", "Alkane Toolkit"
VALUE "ProductVersion", ALKANE_VER_STR
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0409, 1200
END
END
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Regenerate alkane-toolkit.ico (the Windows executable/taskbar icon) from the
# in-repo microchip glyph: a white chip on a rounded amber tile, at the sizes
# Windows asks for (16-256 px). Needs rsvg-convert and ImageMagick; the .ico is
# committed, so a normal build never runs this.
set -e
cd "$(dirname "$0")"
GLYPH=../assets/icons/microchip-solid-full.svg
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' 0
sed 's/currentColor/#ffffff/g; s/<svg /<svg fill="#ffffff" /' "$GLYPH" > "$TMP/glyph.svg"
for s in 16 20 24 32 40 48 64 256; do
r=$((s * 22 / 100)); g=$((s * 64 / 100)); o=$(((s - g) / 2))
rsvg-convert -w "$g" -h "$g" "$TMP/glyph.svg" -o "$TMP/g$s.png"
convert -size "${s}x${s}" xc:none -fill '#d9822b' \
-draw "roundrectangle 0,0 $((s - 1)),$((s - 1)) $r,$r" \
"$TMP/g$s.png" -geometry "+$o+$o" -composite "PNG32:$TMP/i$s.png"
done
convert "$TMP"/i16.png "$TMP"/i20.png "$TMP"/i24.png "$TMP"/i32.png "$TMP"/i40.png \
"$TMP"/i48.png "$TMP"/i64.png "$TMP"/i256.png alkane-toolkit.ico
echo "wrote $(pwd)/alkane-toolkit.ico"
+6 -6
View File
@@ -1,10 +1,10 @@
# UI Spec — primary view
# Primary view
Source: operator description, 2026-09-15. Status: ACCEPTED (v1 scope).
## Header (above the table)
## Header
- **KPI block, top left — 6 KPIs:**
- **KPI block, top left: 6 KPIs:**
1. Total miners
2. Hashing
3. Slow
@@ -31,7 +31,7 @@ Source: operator description, 2026-09-15. Status: ACCEPTED (v1 scope).
4. Cooling (fan)
5. Firmware
6. Pool worker account name
7. …then the remaining statistics in registry order.
7. Remaining statistics in registry order.
## Data sources
@@ -45,10 +45,10 @@ Source: operator description, 2026-09-15. Status: ACCEPTED (v1 scope).
ships with the board registry; missing band = excluded from Slow, counted
in Hashing).
## Implementation notes
## Implementation
- wxWidgets: the view is a `wxDataViewListCtrl`/`wxDataViewCtrl` (virtual
list — thousands of rows without materializing cells), checkbox column +
list for thousands of rows without materializing cells), checkbox column +
IP column fixed via attribute/serializer, drag reorder via `wxReorderable`
column events, sort via column header click events mapped to the model.
- Filter panel: per-column distinct-value checklist with text search,
+1 -1
View File
@@ -1,4 +1,4 @@
# ADR 0001: Recipes as data, interpreted by one engine
# ADR 0001: Recipe engine
Status: ACCEPTED
Date: 2026-09-14
+15 -29
View File
@@ -1,41 +1,27 @@
# ADR 0002: GUI bindings — wxWidgets shell in C++ + Rust core, spike to revisit
# ADR 0002: GUI bindings
Status: RESOLVED 2026-09-15 - the operator chose Option B (pure Rust via
wx-rs) with vendoring (ADR-0003). wx-rs 0.2.0 was extended via the patch
queue: Linux/GTK3 wx-config build path plus the widget bridge (panel,
sizers, static text, button, text ctrl, checkbox, checklistbox, dialog,
data view list ctrl, timer). The app ships this way; no C++ shell.
Date: 2026-09-14
Resolved: 2026-09-15
## Context
The toolkit must present a native cross-platform GUI (wxWidgets chosen).
Rust bindings to wxWidgets checked on crates.io 2026-09-14:
- `wxRust` 0.0.1-alpha — unmaintained since 2022.
- `wx-rs` 0.2.0 (2023, self-contained) — ~6k downloads, no 1.0.
Betting the GUI on alpha bindings risks weeks of binding-gap debugging
(paste-heavy widgets, worker threads + event loops, GTK/WinCocoa quirks).
The toolkit needs a native wxWidgets GUI. At the time of evaluation,
`wxRust` 0.0.1-alpha had seen no maintenance since 2022, and `wx-rs`
0.2.0 lacked widgets needed for the Toolkit.
## Decision
Default: **thin C++17 wxWidgets shell (`gui/`) + Rust core exposed over a
small stable C ABI** (cdylib from `alkane-core`, header generated with
cbindgen). The shell holds frames, lists, the install wizard, and event
glue only — no business logic, no safety logic. All invariants, engines,
and tests live in Rust where they are testable headlessly.
The operator chose a Rust GUI through a vendored, patched `wx-rs` 0.2.0.
The patch queue adds the Linux/GTK3 build path and bindings for panels,
sizers, controls, dialogs, data views, timers, and event dispatch. The
application uses this bridge; it has no separate C++ shell.
Gate: M0 runs a time-boxed `wx-rs` spike (window + list/tree + wizard flow
+ worker-thread progress + cancel on Linux and Windows). If the spike is
solid, flip to pure Rust; either way the decision is recorded before M3.
The original proposal was a small C++17 wxWidgets shell calling a Rust
core through a C ABI. The `wx-rs` spike met the GUI need, so that proposal
was not adopted.
## Consequences
- The repo builds two things: a Rust workspace and a small C++ app linked
against the core cdylib. CMake in `gui/`.
- Core API surface stays small and event-oriented (discover, identify,
plan, execute, cancel, progress events, log tail) — good FFI hygiene and
a natural match for the CLI too (D4).
- If wx-rs wins the spike, the C ABI is kept as an integration boundary for
scripted/HIL use anyway.
- Keep business logic and safety checks in testable Rust code.
- Carry wx-rs changes as numbered patches under `thirdparty/wx-rs/patches`.
- Recheck the bridge on Linux, Windows, and macOS packaging changes.
+2 -2
View File
@@ -1,4 +1,4 @@
# ADR 0003: Vendoring policy — pristine upstream archives + patch queue
# ADR 0003: Vendoring
Status: ACCEPTED
Date: 2026-09-15
@@ -42,7 +42,7 @@ thirdparty/
Rules:
1. Never edit a vendored pristine tree in place — every local change is a
1. Never edit a vendored pristine tree in place. Every local change is a
patch in `patches/`, applied by the build in numeric order. This makes
an upstream update: replace pristine archive, `git apply` surviving
patches, rebase the rest.
+48
View File
@@ -0,0 +1,48 @@
# ADR 0004: Windows port
Date: 2026-11-02
## Context
The GUI is wxWidgets through the patched `wx-rs` bridge (ADR 0002), so most
of it is portable, but the patches and the app had only ever run on GTK. The
Windows build has to look and behave like a native Windows 10/11 application,
ship from the same CI as Linux, and stay maintainable for a team that develops
on Linux.
## Decision
- Build on Linux: cross-compile with mingw-w64 (posix threads) against the
vendored wxWidgets built as static wxMSW (`scripts/build-wx-windows.sh`).
The `wx-rs` build script now picks the platform from `CARGO_CFG_TARGET_*`
(a build script's `cfg!()` describes the host) and builds Windows/GNU through
`wx-config` exactly like GTK. The C++ runtime is linked statically; the
`.exe` imports only Windows system DLLs.
- Native look comes from wxMSW plus an application manifest
(`crates/alkane-gui/windows/`): Common Controls v6, per-monitor DPI
awareness v2, UTF-8 code page, Windows 10/11 compatibility, icon and
version resources. Light/dark follows the Windows app mode.
- Platform code is contained: OS differences in Rust live in
`alkane_core::platform` (config directory, owner-only secret files, null
device, console-less child processes); in C++ they are `#ifdef __WXMSW__` /
`__WXGTK__` sections of the bridge, with shared logic (icon hit-testing) in
plain functions both use.
- Sizes cross the Rust/C++ boundary in DIPs, converted per window with
`FromDIP`/`ToDIP`. That is the identity on GTK, so Linux output is unchanged.
- SSH password logins use `SSH_ASKPASS` with the toolkit's own executable as
the helper, on every platform, replacing `sshpass` (absent on Windows).
- CI tests the Windows build under Wine on the existing Linux runners (the
release gate), and again on real Windows 11 through a self-hosted VM runner
(advisory, never blocking).
- The `wx-rs` patch queue must reproduce the patched tree from the pristine
upstream crate; `scripts/wx_rs_patches.py check` enforces it in CI.
## Consequences
- One toolchain and one CI fleet for both platforms; no Windows build machine.
- Wine is a good but not perfect stand-in for Windows; the native VM job
covers the gap without making releases depend on the VM being up.
- Bridge changes need checking on both toolkits: GTK uses the native tree
view, wxMSW the generic data view, which differ in input routing, painting
and selection style (see docs/windows.md).
- macOS remains out of scope (no Mac to build or test on).
+120
View File
@@ -0,0 +1,120 @@
# Windows
The toolkit ships a Windows build alongside the Linux one in every release:
`alkane-toolkit-vX.Y.Z-windows-x86_64.zip`, holding one self-contained
`alkane-toolkit.exe` for Windows 10 and 11 (x86_64). There is no installer
and no runtime to install. Design decisions are in
[ADR 0004](adr/0004-windows-port.md).
## Using it
- Settings live in `%APPDATA%\alkane-toolkit` (Linux: `~/.config/alkane-toolkit`),
same file names and formats.
- SSH actions use the OpenSSH client built into Windows (`ssh.exe`); HTTP
actions use the built-in `curl.exe`. Both start without a console window.
- The window follows the Windows light/dark app setting. Set
`ALKANE_APPEARANCE=light` or `dark` to force one (any platform).
- Headless modes (`ALKANE_SELFTEST`, `ALKANE_ACCESS_PROBE`, `ALKANE_LOG_SCAN`)
print to the console they are started from.
- Offline demo: `set ALKANE_FAKE_SCAN=1 && alkane-toolkit.exe`.
## Building
The Windows build is cross-compiled on Linux with mingw-w64 (posix-threads
variant), exactly as CI does it:
```sh
sudo apt install g++-mingw-w64-x86-64-posix wine xvfb # once
scripts/build-wx-windows.sh # once: static wxMSW 3.3.3 in ~/.cache/wx-3.3.3-mingw
scripts/build-gui-windows.sh # release alkane-toolkit.exe
```
`scripts/windows-cross-env.sh` holds the toolchain environment (compilers,
linker, `WX_RS_WXCONFIG`, the Wine test runner). Source it to run cargo by hand:
```sh
. scripts/windows-cross-env.sh
cargo test --offline --target "$ALKANE_WIN_TARGET" --workspace --exclude wx-rs # runs under Wine
scripts/ui-selftest-windows.sh # headless UI self-test of the .exe under Wine
```
`alkane-toolkit.exe` must import only Windows system DLLs; `ci/windows-ci.sh
build` fails the build if a mingw runtime DLL slips in.
## CI
`ci/windows-ci.sh` is the one definition of every Windows step; the workflows
only call it.
| Workflow | Windows job | Gate |
|----------|-------------|------|
| `verify.yml` (PRs to main) | `verify-windows`: clippy, release build, unit tests and UI self-test under Wine | required |
| `release.yml` (main) | `windows`: the same, then packages the zip; `release` waits for it and attaches it | required |
| `next.yml` (next) | `windows`: build and package the `-rc` zip | required |
| `windows-native.yml` | runs main's cross-built unit tests and UI self-test on real Windows 11 | advisory |
The CI image (`ci/images/alkane-ci.Dockerfile`, digest pinned in
`ci/runner-image.txt`) adds mingw-w64, Wine with a ready prefix, the rustup
target and a prebuilt wxMSW prefix to the Linux image. Rebuild it with
`ci/images/build-image.sh TAG` from the workstation that holds the registry
credential; the script pins the new digest everywhere.
## Code signing
Release and `-rc` executables are Authenticode-signed with Azure Artifact
Signing (formerly Trusted Signing), so Windows and SmartScreen show
"Blueflare" as the verified publisher instead of "Unknown publisher".
| Piece | Where |
|-------|-------|
| Signing account | `blueflaresigning` (Basic), resource group `rg-blueflare-signing`, West US 2, endpoint `https://wus2.codesigning.azure.net` |
| CI identity | service principal `alkane-toolkit-ci-signer`, role "Artifact Signing Certificate Profile Signer" on the certificate profile only; Gitea secrets `AZURE_SIGNING_TENANT_ID`, `AZURE_SIGNING_CLIENT_ID`, `AZURE_SIGNING_CLIENT_SECRET` (secret expires 2027-11-03) |
| Switch | Gitea repository variable `AZURE_SIGNING_PROFILE` (certificate profile name); unset = builds stay unsigned |
| Signer | `ci/sign-windows.sh` (jsign from the CI image, RFC 3161 timestamp from `timestamp.acs.microsoft.com`) |
| Check | `windows-native.yml` requires `Get-AuthenticodeSignature` = Valid on real Windows once signing is on |
Signing is on since 2026-11-03 (identity validation approved, certificate
profile `alkane-toolkit`, PublicTrust). The zip's README.txt states whether its
executable is signed. To set it up again, e.g. for a new profile, after an
identity validation is approved (portal: signing account > Identity
validations):
```sh
scripts/enable-windows-signing.sh <identity-validation-id>
```
It creates the PublicTrust certificate profile, narrows the CI identity to it,
and sets `AZURE_SIGNING_PROFILE`. From then on a signing failure fails the
release. Rotate the CI secret before it expires with
`az ad sp credential reset --id <appId> --years 1` and update the Gitea secret.
Sign by hand (any machine with Java, `az login` and the Signer role):
```sh
AZURE_SIGNING_PROFILE=alkane-toolkit ALKANE_JSIGN_JAR=jsign.jar \
AZURE_SIGNING_TOKEN=$(az account get-access-token --resource https://codesigning.azure.net --query accessToken -o tsv) \
ci/sign-windows.sh alkane-toolkit.exe
```
## Native Windows runner
`windows-native.yml` runs on the self-hosted runner `win11-test-vm`
(label `alkane-windows`, host mode) inside the Windows 11 test VM
(a local test VM). It downloads the
`alkane-toolkit-windows-tests` artifact of the triggering main run, runs every
test executable and the UI self-test natively, and never blocks a release:
while the VM is off, the job waits for the runner.
In the VM, `gitea-runner` v3.5.0 lives in `C:\gitea-runner` and starts at boot
as the scheduled task `gitea-runner`, running as `LOCAL SERVICE` (log:
`C:\gitea-runner\runner.log`).
## Differences from Linux worth knowing
- wxMSW's `wxDataViewCtrl` is wx's generic implementation (GTK uses the native
`GtkTreeView`), so drag-select and per-cell tooltips are implemented in the
bridge for it.
- Selected rows use the Windows 10/11 list-view highlight: a light tint under
normal text, not a solid colour with white text.
- The app is per-monitor DPI aware: the bridge converts every size it gets
from Rust from DIPs to physical pixels for the window it applies to.
+1
View File
@@ -5,6 +5,7 @@
# scripts/build-wx-linux.sh to produce it).
set -e
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
trap 'bash "$REPO/scripts/clean-old-builds.sh" || true' 0
WX_PREFIX="${1:-$HOME/.cache/wx-3.3.3-linux}"
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
"$REPO/scripts/build-wx-linux.sh"
+22 -18
View File
@@ -1,22 +1,26 @@
#!/bin/sh
# Build the alkane-toolkit GUI for Windows (x86_64) from Linux, via mingw-w64.
# wx-rs upstream supports MSW (it downloads and builds wx 3.2.2.1 with MSVC
# via nmake, or links an msys2 mingw64 wx). Two supported routes:
# Build the alkane-toolkit GUI for Windows (x86_64) on Linux by cross-compiling
# with mingw-w64 against the vendored wxWidgets 3.3.3 (wxMSW), the same way CI
# builds the release .exe. The result is one self-contained executable: the C++
# runtime is linked statically and it imports only DLLs Windows itself ships.
#
# A) On Windows: install msys2/mingw64 wx + rust-gnu, run `cargo build
# --release -p alkane-gui` there (wx-rs build.rs handles msys2 paths).
# B) Cross from Linux: not automated yet - wxMSW needs the MSVC or msys2
# toolchain; tracked as follow-up. The Rust side cross-compiles fine;
# only the C++ bridge + wx need the Windows toolchain.
#
# This script documents route A and fails here if run on Linux.
# Usage: scripts/build-gui-windows.sh [cargo build args...]
# defaults to `--release`; e.g. `scripts/build-gui-windows.sh` or
# `scripts/build-gui-windows.sh --profile dev`.
# Needs: mingw-w64 (posix-threads variant), the rustup target
# x86_64-pc-windows-gnu, and the wxMSW prefix from build-wx-windows.sh
# (built on first use).
set -e
if [ "$(uname -s)" = "Linux" ]; then
echo "Route B (Linux cross to MSW) is not automated yet."
echo "Run scripts/build-gui-windows.sh on Windows (msys2 mingw64 + rust),"
echo "or use CI with a Windows runner."
exit 1
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$REPO"
. "$REPO/scripts/windows-cross-env.sh"
if [ ! -x "$WX_RS_WXCONFIG" ]; then
sh "$REPO/scripts/build-wx-windows.sh"
fi
cd "$(dirname -- "$0")/.."
cargo build --release -p alkane-gui
echo "binary: target/release/alkane-toolkit.exe"
rustup target list --installed 2>/dev/null | grep -qx "$ALKANE_WIN_TARGET" ||
rustup target add "$ALKANE_WIN_TARGET"
[ "$#" -gt 0 ] || set -- --release
cargo build --offline --target "$ALKANE_WIN_TARGET" -p alkane-gui "$@"
TDIR=$(cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \
| tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4)
echo "binary: ${TDIR:-$REPO/target}/$ALKANE_WIN_TARGET/<profile>/alkane-toolkit.exe"
+15
View File
@@ -6,6 +6,21 @@ REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3"
BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3"
PREFIX="$HOME/.cache/wx-3.3.3-linux"
cleanup_wx_build() {
python3 - "$BUILD" "$HOME/.cache/wxbuild" <<'PY'
from pathlib import Path
import shutil
import sys
build, parent = map(Path, sys.argv[1:])
if (build.name != "wxWidgets-3.3.3" or build.parent != parent
or build.is_symlink() or parent.is_symlink()):
raise SystemExit("refusing unsafe wxWidgets build cleanup path")
if build.is_dir():
shutil.rmtree(build)
PY
}
trap cleanup_wx_build 0
[ -d "$BUILD" ] || { mkdir -p "$HOME/.cache/wxbuild"; cp -r "$SRC" "$BUILD"; }
[ -d "$BUILD" ] || { echo "thirdparty wxWidgets tree missing"; exit 1; }
chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# Cross-build the vendored wxWidgets 3.3.3 for Windows (wxMSW, x86_64, static,
# monolithic) from Linux with mingw-w64. Mirrors build-wx-linux.sh: the repo
# tree stays pristine, the build lives in ~/.cache/wxbuild, and the result is a
# prefix whose bin/wx-config the wx-rs build script reads (WX_RS_WXCONFIG).
#
# Every third-party library wx needs is the copy bundled in the wx source tree
# ("builtin"), so the prefix needs nothing from the build host and the final
# .exe needs no DLLs beyond the ones Windows itself ships. TIFF and WebP are
# off: the app never loads either format.
#
# Needs: mingw-w64 (the posix-threads g++ variant), make.
set -e
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3"
HOST=x86_64-w64-mingw32
BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3-mingw"
PREFIX="${WX_WINDOWS_PREFIX:-$HOME/.cache/wx-3.3.3-mingw}"
# std::thread/std::mutex need the posix thread model; Debian's default
# x86_64-w64-mingw32-g++ alternative is the win32 model.
CC="${WX_WINDOWS_CC:-$HOST-gcc-posix}"
CXX="${WX_WINDOWS_CXX:-$HOST-g++-posix}"
command -v "$CXX" >/dev/null || { echo "$CXX not found (apt install mingw-w64)"; exit 1; }
cleanup_wx_build() {
python3 - "$BUILD" "$HOME/.cache/wxbuild" <<'PY'
from pathlib import Path
import shutil
import sys
build, parent = map(Path, sys.argv[1:])
if (build.name != "wxWidgets-3.3.3-mingw" or build.parent != parent
or build.is_symlink() or parent.is_symlink()):
raise SystemExit("refusing unsafe wxWidgets build cleanup path")
if build.is_dir():
shutil.rmtree(build)
PY
}
trap cleanup_wx_build 0
[ -d "$SRC" ] || { echo "thirdparty wxWidgets tree missing"; exit 1; }
[ -d "$BUILD" ] || { mkdir -p "$HOME/.cache/wxbuild"; cp -r "$SRC" "$BUILD"; }
chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true
mkdir -p "$BUILD/build-msw"
cd "$BUILD/build-msw"
# --enable-unicode is the 3.3 default. wxUSE_RC_MANIFEST/DPI awareness are
# handled by the application's own resource script (crates/alkane-gui/build.rs),
# not here, so the library stays policy-free.
sh ../configure --host="$HOST" --build="$(sh ../config.guess)" \
--prefix="$PREFIX" CC="$CC" CXX="$CXX" \
--disable-shared --enable-monolithic --with-msw \
--with-opengl=no --disable-stc --disable-tests --disable-webview \
--with-libpng=builtin --with-libjpeg=builtin --with-regex=builtin \
--with-zlib=builtin --with-expat=builtin \
--without-libtiff --without-libwebp --without-liblzma
make -j"${WX_BUILD_JOBS:-$(nproc)}"
make install
ls "$PREFIX"/lib/libwx_mswu-3.3-"$HOST".a >/dev/null
echo "installed: $PREFIX ($("$PREFIX/bin/wx-config" --version) $("$PREFIX/bin/wx-config" --selected-config))"
+9
View File
@@ -18,6 +18,15 @@
set -uo pipefail
TARGET="${CARGO_TARGET_DIR:-$HOME/.cache/alkane-tk-target}"
REPO="$(cd "$(dirname "$0")/.." && pwd)"
case "$(realpath -m "$TARGET")" in
"$HOME/.cache/alkane-tk-target"|"$REPO/target") ;;
*) echo "clean-old-builds: refusing unexpected target $TARGET" >&2; exit 1 ;;
esac
if [ -L "$TARGET" ]; then
echo "clean-old-builds: refusing symlink target $TARGET" >&2
exit 1
fi
if [ ! -d "$TARGET" ]; then
echo "clean-old-builds: no target dir at $TARGET (nothing to do)"
exit 0
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# Turn on Authenticode signing of the Windows build, once Microsoft has
# approved the publisher identity validation for the Artifact Signing account.
#
# scripts/enable-windows-signing.sh IDENTITY_VALIDATION_ID [PROFILE]
#
# IDENTITY_VALIDATION_ID is shown in the Azure portal: signing account
# "blueflaresigning" > Objects > Identity validations > (approved entry).
# The script
# 1. creates the PublicTrust certificate profile PROFILE (default
# alkane-toolkit) bound to that identity,
# 2. narrows the CI signer's role from the whole account to that profile,
# 3. sets the Gitea repository variable AZURE_SIGNING_PROFILE, which makes
# ci/sign-windows.sh sign every release and candidate from then on.
#
# Run on the workstation: it needs `az login` as an account owner and the
# Gitea admin token (~/.config/gitea/token), neither of which CI ever sees.
# Re-running is safe.
set -eu
IVID=${1:?usage: enable-windows-signing.sh IDENTITY_VALIDATION_ID [PROFILE]}
PROFILE=${2:-alkane-toolkit}
RG=rg-blueflare-signing
ACCOUNT=blueflaresigning
SIGNER=alkane-toolkit-ci-signer
REPO=blueflare/alkane-toolkit
TOKEN_FILE=${GITEA_TOKEN_FILE:-$HOME/.config/gitea/token}
if ! az trustedsigning certificate-profile show -g "$RG" --account-name "$ACCOUNT" \
-n "$PROFILE" --only-show-errors -o none 2>/dev/null; then
az trustedsigning certificate-profile create -g "$RG" --account-name "$ACCOUNT" \
-n "$PROFILE" --profile-type PublicTrust --identity-validation-id "$IVID" \
--only-show-errors -o none
fi
az trustedsigning certificate-profile show -g "$RG" --account-name "$ACCOUNT" -n "$PROFILE" \
--only-show-errors --query "{profile:name, state:provisioningState, status:status}" -o table
# Least privilege: the CI identity may sign with this profile and nothing else.
profile_id=$(az trustedsigning certificate-profile show -g "$RG" --account-name "$ACCOUNT" \
-n "$PROFILE" --only-show-errors --query id -o tsv)
account_id=${profile_id%/certificateProfiles/*}
sp=$(az ad sp list --display-name "$SIGNER" --query "[0].id" -o tsv)
role="Artifact Signing Certificate Profile Signer"
az role assignment create --assignee-object-id "$sp" --assignee-principal-type ServicePrincipal \
--role "$role" --scope "$profile_id" -o none
az role assignment delete --assignee "$sp" --role "$role" --scope "$account_id" 2>/dev/null || true
# Switch signing on for CI (repository variable, not a secret).
api=https://gitea.bluefla.re/api/v1/repos/$REPO/actions/variables/AZURE_SIGNING_PROFILE
body=$(printf '{"value":"%s"}' "$PROFILE")
auth() { printf 'header = "Authorization: token %s"\n' "$(cat "$TOKEN_FILE")"; }
code=$(auth | curl -sS --config - -X PUT -H 'Content-Type: application/json' -d "$body" \
-o /dev/null -w '%{http_code}' "$api")
[ "$code" = 204 ] || [ "$code" = 201 ] || {
code=$(auth | curl -sS --config - -X POST -H 'Content-Type: application/json' -d "$body" \
-o /dev/null -w '%{http_code}' "$api")
}
case "$code" in 201|204) echo "Gitea AZURE_SIGNING_PROFILE=$PROFILE: signing is on" ;;
*) echo "setting the Gitea variable failed (HTTP $code)" >&2; exit 1 ;; esac
+27 -17
View File
@@ -8,13 +8,13 @@
#
# Usage: scripts/ui-screenshot.sh [out.png] [--live] [binary]
set -u
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
REPO=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
WX_PREFIX="${WX_PREFIX:-$HOME/.cache/wx-3.3.3-linux}"
export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$WX_PREFIX/bin/wx-config}"
OUT="${1:-alkane-toolkit.png}"
LIVE=0; BIN=""
shift 2>/dev/null || true
[ "$#" -eq 0 ] || shift
for a in "$@"; do
case "$a" in
--live) LIVE=1 ;;
@@ -32,17 +32,31 @@ if [ -z "$BIN" ]; then
fi
[ -x "$BIN" ] || { echo "binary not found: $BIN" >&2; exit 3; }
DISP=":98"
FAKE_ENV="ALKANE_FAKE_SCAN=1"
[ "$LIVE" = "1" ] && FAKE_ENV=""
Xvfb "$DISP" -screen 0 1280x850x24 -nolisten tcp >/dev/null 2>&1 &
DISPLAY_FILE=$(mktemp)
XPID=""; APID=""; WARM=""
cleanup() {
[ -z "$APID" ] || kill "$APID" 2>/dev/null || true
[ -z "$WARM" ] || kill "$WARM" 2>/dev/null || true
[ -z "$XPID" ] || kill "$XPID" 2>/dev/null || true
rm -f "$DISPLAY_FILE"
}
trap cleanup EXIT
Xvfb -displayfd 3 -screen 0 1280x850x24 -nolisten tcp 3>"$DISPLAY_FILE" >/dev/null 2>&1 &
XPID=$!
sleep 1.2
for _ in {1..30}; do
[ -s "$DISPLAY_FILE" ] && break
kill -0 "$XPID" 2>/dev/null || { echo "Xvfb exited before startup" >&2; exit 3; }
sleep 0.1
done
[ -s "$DISPLAY_FILE" ] || { echo "Xvfb did not start" >&2; exit 3; }
DISP=":$(cat "$DISPLAY_FILE")"
# warm the font/GTK caches so the first window map is not stalled
DISPLAY="$DISP" xclock >/dev/null 2>&1 & WARM=$!; sleep 1.2; kill "$WARM" 2>/dev/null
# shellcheck disable=SC2086
DISPLAY="$DISP" GDK_BACKEND=x11 $FAKE_ENV "$BIN" >/dev/null 2>&1 &
if [ "$LIVE" = "1" ]; then
DISPLAY="$DISP" GDK_BACKEND=x11 "$BIN" >/dev/null 2>&1 &
else
DISPLAY="$DISP" GDK_BACKEND=x11 ALKANE_FAKE_SCAN=1 "$BIN" >/dev/null 2>&1 &
fi
APID=$!
WID=""; t=0
while [ "$t" -lt 25 ]; do
@@ -52,10 +66,6 @@ while [ "$t" -lt 25 ]; do
[ -n "$line" ] && { WID=$(echo "$line" | awk '{print $1}'); break; }
done
sleep 2 # let it paint and drain a scan tick
if [ -n "$WID" ]; then
DISPLAY="$DISP" import -window "$WID" "$OUT" && echo "wrote $OUT (window $WID, ${t}s)"
else
DISPLAY="$DISP" import -window root "$OUT"; echo "no app window; captured root -> $OUT" >&2
fi
kill "$APID" 2>/dev/null
kill "$XPID" 2>/dev/null
[ -n "$WID" ] || { echo "no app window mapped" >&2; exit 1; }
DISPLAY="$DISP" import -window "$WID" "$OUT" || exit 1
echo "wrote $OUT (window $WID, ${t}s)"
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# Headless UI workflow self-test of the WINDOWS build, under Wine on a private
# Xvfb display: the same ALKANE_SELFTEST check as scripts/ui-selftest.sh (bench
# fixtures rendered through the real wxMSW widgets, read back, and compared),
# run against alkane-toolkit.exe. CI runs this on every build; the native
# Windows smoke job (.gitea/workflows/windows-native.yml) repeats it on real
# Windows.
#
# Usage: scripts/ui-selftest-windows.sh [alkane-toolkit.exe]
# defaults to the cross-built release binary in the cargo target dir.
set -u
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
EXE="${1:-}"
if [ -z "$EXE" ]; then
sh "$REPO/scripts/build-gui-windows.sh" || exit 3
TDIR=$(cd "$REPO" && cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \
| tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4)
EXE="${TDIR:-$REPO/target}/x86_64-pc-windows-gnu/release/alkane-toolkit.exe"
fi
[ -f "$EXE" ] || { echo "executable not found: $EXE" >&2; exit 3; }
# xvfb-run picks a free display and cleans it up; Wine needs an X server for
# the window even though the self-test never shows it to anyone.
xvfb-run -a -s '-screen 0 1280x850x24' \
env ALKANE_SELFTEST=1 sh "$REPO/scripts/wine-run.sh" "$EXE"
RC=$?
echo "== ui-selftest-windows exit=$RC =="
exit "$RC"
+38
View File
@@ -0,0 +1,38 @@
# shellcheck shell=sh
# Toolchain environment for cross-building the toolkit for Windows
# (x86_64-pc-windows-gnu) on Linux. One definition, used by
# scripts/build-gui-windows.sh locally and by the CI Windows job:
#
# . scripts/windows-cross-env.sh # export into this shell
# sh scripts/windows-cross-env.sh --github-env # append to $GITHUB_ENV
#
# WX_WINDOWS_PREFIX selects the wxMSW prefix built by build-wx-windows.sh.
# `cargo test --target x86_64-pc-windows-gnu` runs the test .exe files through
# scripts/wine-run.sh, so the Windows build is unit-tested on every Linux host.
# The posix-threads mingw variants are required: libstdc++'s std::thread and
# the wx build both use them, and mixing in the win32-thread variant at link
# time fails on missing pthread symbols.
WX_WINDOWS_PREFIX="${WX_WINDOWS_PREFIX:-$HOME/.cache/wx-3.3.3-mingw}"
ALKANE_WIN_TARGET=x86_64-pc-windows-gnu
# Sourced scripts cannot rely on $0, so locate the checkout through git.
ALKANE_REPO="${ALKANE_REPO:-$(git rev-parse --show-toplevel)}"
_alkane_win_env() {
cat <<EOF
WX_WINDOWS_PREFIX=$WX_WINDOWS_PREFIX
WX_RS_WXCONFIG=$WX_WINDOWS_PREFIX/bin/wx-config
ALKANE_WIN_TARGET=$ALKANE_WIN_TARGET
CC_x86_64_pc_windows_gnu=x86_64-w64-mingw32-gcc-posix
CXX_x86_64_pc_windows_gnu=x86_64-w64-mingw32-g++-posix
AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc-posix
WINDRES=x86_64-w64-mingw32-windres
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=$ALKANE_REPO/scripts/wine-run.sh
EOF
}
if [ "${1:-}" = "--github-env" ]; then
_alkane_win_env >> "${GITHUB_ENV:?GITHUB_ENV is required}"
else
eval "$(_alkane_win_env | sed 's/^/export /')"
fi
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Cargo target runner for x86_64-pc-windows-gnu: run a Windows .exe under Wine.
# Set via CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER (scripts/windows-cross-env.sh).
# A private, reusable Wine prefix keeps runs isolated from any desktop Wine
# setup and avoids re-creating the prefix (~10 s) for every test binary.
set -e
export WINEPREFIX="${ALKANE_WINEPREFIX:-$HOME/.cache/alkane-wine}"
export WINEDEBUG="${WINEDEBUG:--all}"
# No Wine menu entries/file associations, no Gecko/Mono install prompts.
export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-winemenubuilder.exe=d;mscoree=d;mshtml=d}"
WINE="${WINE:-$(command -v wine64 || command -v wine)}"
if [ ! -f "$WINEPREFIX/system.reg" ]; then
mkdir -p "$WINEPREFIX"
# The registry (system.reg, the "prefix is ready" marker) is only written
# when the wine server shuts down, so finish the boot explicitly.
"$WINE" wineboot --init >/dev/null 2>&1 || true
"$WINE" wineboot --shutdown >/dev/null 2>&1 || true
wineserver -w 2>/dev/null || true
fi
exec "$WINE" "$@"
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Keep thirdparty/wx-rs/patches/ an exact recipe for the patched wx-rs tree.
The patched crate (thirdparty/wx-rs/wx-rs-0.2.0-patched) is what cargo builds;
the numbered patches are how a reviewer or an upstream bump reproduces it from
the pristine crates.io tarball (thirdparty/wx-rs/upstream/, digest pinned in
thirdparty/wx-rs/VERSION). The two drift apart whenever someone edits the tree
and forgets the patch, so:
wx_rs_patches.py check
Unpack the upstream crate, apply every patch in order (no fuzz), and
require the result to equal the patched tree byte for byte. Offline; CI
runs it on every bridge change.
wx_rs_patches.py capture NNNN-short-name "Subject line" [PATH ...]
Write the difference between (upstream + current queue) and the patched
tree as the next patch, optionally limited to PATHs, then re-check.
Workflow: edit the patched tree, build/test, capture, commit both.
"""
import argparse
import hashlib
import shutil
import subprocess
import sys
import tarfile
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
WXRS = ROOT / "thirdparty/wx-rs"
PATCHED = WXRS / "wx-rs-0.2.0-patched"
PATCHES = WXRS / "patches"
CRATE = WXRS / "upstream/wx-rs-0.2.0.crate"
# Build products and the wx source download cache are never part of the recipe.
IGNORED = {"target", "dist"}
def pinned_digest() -> str:
for line in (WXRS / "VERSION").read_text().splitlines():
if line.startswith("sha256:"):
return line.split()[1]
sys.exit("thirdparty/wx-rs/VERSION has no sha256 line")
def unpack_upstream(dest: Path) -> Path:
data = CRATE.read_bytes()
if hashlib.sha256(data).hexdigest() != pinned_digest():
sys.exit(f"{CRATE.relative_to(ROOT)} does not match the pinned sha256")
with tarfile.open(CRATE) as tar:
tar.extractall(dest, filter="data")
tree = dest / "wx-rs-0.2.0"
if not tree.is_dir():
sys.exit("upstream crate did not unpack to wx-rs-0.2.0/")
return tree
def patch_files() -> list:
return sorted(PATCHES.glob("[0-9][0-9][0-9][0-9]-*.patch"))
def apply_queue(tree: Path) -> None:
for patch in patch_files():
result = subprocess.run(
["patch", "-p1", "-s", "-F0", "--no-backup-if-mismatch", "-i", str(patch)],
cwd=tree, capture_output=True, text=True)
if result.returncode != 0:
sys.exit(f"{patch.name} does not apply cleanly:\n{result.stdout}{result.stderr}")
def copy_patched(dest: Path) -> Path:
tree = dest / "b"
shutil.copytree(PATCHED, tree, ignore=lambda d, names: [
n for n in names if Path(d) == PATCHED and n in IGNORED])
return tree
def unified_diff(work: Path, paths: list) -> str:
"""diff -ruN a b, run from `work` so headers read a/<path> and b/<path>."""
targets = [(f"a/{p}", f"b/{p}") for p in paths] if paths else [("a", "b")]
out = []
for left, right in targets:
result = subprocess.run(["diff", "-ruN", left, right], cwd=work,
capture_output=True, text=True)
if result.returncode > 1:
sys.exit(result.stderr)
out.append(result.stdout)
# Drop the mtimes diff appends to ---/+++ headers so a regenerated patch
# only changes when its content does.
return "".join(
line.split("\t", 1)[0] + "\n" if line.startswith(("--- ", "+++ ")) else line
for line in "".join(out).splitlines(keepends=True))
def prepare(work: Path) -> None:
unpack_upstream(work).rename(work / "a")
apply_queue(work / "a")
copy_patched(work)
def check() -> int:
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
prepare(work)
drift = unified_diff(work, [])
if drift:
print("wx-rs patch queue does not reproduce the patched tree;", file=sys.stderr)
print("capture the change with scripts/wx_rs_patches.py capture:", file=sys.stderr)
print(drift[:4000], file=sys.stderr)
return 1
print(f"wx-rs patch queue OK ({len(patch_files())} patches reproduce the tree)")
return 0
def capture(name: str, subject: str, paths: list) -> int:
existing = patch_files()
number = int(existing[-1].name[:4]) + 1 if existing else 1
if not name[:4].isdigit():
name = f"{number:04d}-{name}"
target = PATCHES / (name if name.endswith(".patch") else name + ".patch")
if target.exists():
sys.exit(f"{target.name} already exists")
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
prepare(work)
body = unified_diff(work, paths)
if not body:
sys.exit("nothing to capture: the queue already reproduces the tree")
target.write_text(f"Subject: [PATCH {target.name[:4]}] {subject}\n\n{body}")
print(f"wrote {target.relative_to(ROOT)}")
return check()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("check")
cap = sub.add_parser("capture")
cap.add_argument("name")
cap.add_argument("subject")
cap.add_argument("paths", nargs="*")
args = parser.parse_args()
if args.cmd == "check":
return check()
return capture(args.name, args.subject, args.paths)
if __name__ == "__main__":
sys.exit(main())
+4 -2
View File
@@ -4,5 +4,7 @@ source_url: https://static.crates.io/crates/wx-rs/wx-rs-0.2.0.crate
sha256: b70620dba2997db6640794ef43fa130d19b9a2ec1ab93925450a5b8334d99e33
state: patched tree is the used crate (path dep from crates/alkane-gui).
Upstream stubs non-Windows/macOS and has no widget surface; patches add
the Linux/GTK3 wx-config build path and the widget bridge (see patches/).
Update flow: unpack new upstream here, re-apply patches/, resolve, commit.
the wx-config build path (Linux/GTK3 and Windows/mingw wxMSW) and the
widget bridge (see patches/README.md). upstream/ holds the pristine crate.
Update flow: replace upstream/, re-apply patches/ (scripts/wx_rs_patches.py
check shows what no longer applies), resolve, capture, commit.
+33 -7
View File
@@ -1,3 +1,5 @@
Subject: [PATCH 0002] widget/event bridge, Rust side
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3,3 +3,7 @@
@@ -10,7 +12,7 @@
+pub use widgets::*;
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -0,0 +1,911 @@
@@ -0,0 +1,935 @@
+// 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).
@@ -20,6 +22,11 @@
+use std::ffi::CString;
+use std::os::raw::{c_char, c_int, c_long, c_void};
+
+/// Column alignment for `dvlc_append_text_col` / `dvlc_append_colored_col`.
+pub const ALIGN_LEFT: i32 = 0;
+pub const ALIGN_RIGHT: i32 = 1;
+pub const ALIGN_CENTER: i32 = 2;
+
+mod notsafe {
+ use std::os::raw::{c_char, c_int, c_long, c_void};
+
@@ -49,6 +56,7 @@
+ pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
+ pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
+ pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
+ pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
+ pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
+ pub fn wxbr_text_ctrl_write(win: *mut c_void, value: *const c_char);
@@ -68,8 +76,8 @@
+ pub fn wxbr_file_dialog(parent: *mut c_void, title: *const c_char, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_save_file_dialog(parent: *mut c_void, title: *const c_char, default_name: *const c_char, wildcard: *const c_char, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_dvlc(parent: *mut c_void) -> *mut c_void;
+ pub fn wxbr_dvlc_append_text_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int);
+ pub fn wxbr_dvlc_append_colored_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int) -> *mut c_void;
+ pub fn wxbr_dvlc_append_text_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int, align: c_int);
+ pub fn wxbr_dvlc_append_colored_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int, align: c_int) -> *mut c_void;
+ pub fn wxbr_dvlc_append_toggle_col(win: *mut c_void, width: c_int);
+ pub fn wxbr_dvlc_append_row(win: *mut c_void, nvals: c_int, vals: *const *const c_char);
+ pub fn wxbr_dvlc_delete_row(win: *mut c_void, row: usize);
@@ -81,6 +89,7 @@
+ pub fn wxbr_dvlc_get_cell(win: *mut c_void, row: usize, col: usize, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_dvlc_col_count(win: *mut c_void) -> c_int;
+ pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
+ pub fn wxbr_dvlc_autosize_col_capped(win: *mut c_void, pos: c_int, cap_px: c_int);
+ pub fn wxbr_dvlc_set_col_title(win: *mut c_void, col: c_int, title: *const c_char);
+ pub fn wxbr_dvlc_set_sort_indicator(win: *mut c_void, col: c_int, active: c_int, ascending: c_int);
+ pub fn wxbr_dvlc_col_at_pos(win: *mut c_void, pos: c_int) -> c_int;
@@ -450,6 +459,11 @@
+ Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
+ }
+
+ /// A single-line text control that masks its content (for password entry).
+ pub fn password_ctrl(parent: Widget) -> Widget {
+ Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
+ }
+
+ pub fn get_value(&self) -> String {
+ let mut buf = vec![0i8; 65536];
+ let n = unsafe { notsafe::wxbr_text_ctrl_get(self.0, buf.as_mut_ptr(), buf.len() as c_int) };
@@ -583,17 +597,23 @@
+ Widget(unsafe { notsafe::wxbr_dvlc(parent.0) })
+ }
+
+ pub fn dvlc_append_text_col(&self, title: &str, width: i32, reorderable: bool) {
+ /// Append a text column. `align` is the cell + header alignment:
+ /// [`ALIGN_LEFT`] (0), [`ALIGN_RIGHT`] (1) or [`ALIGN_CENTER`] (2).
+ pub fn dvlc_append_text_col(&self, title: &str, width: i32, reorderable: bool, align: i32) {
+ let c = CString::new(title).unwrap_or_default();
+ unsafe { notsafe::wxbr_dvlc_append_text_col(self.0, c.as_ptr(), width, reorderable as c_int) }
+ unsafe {
+ notsafe::wxbr_dvlc_append_text_col(self.0, c.as_ptr(), width, reorderable as c_int, align)
+ }
+ }
+
+ /// Like `dvlc_append_text_col`, but the column renders cell values through
+ /// the SegmentRenderer, so a value built with `model::encode_segments` is
+ /// drawn as coloured text runs (a plain string still renders normally).
+ pub fn dvlc_append_colored_col(&self, title: &str, width: i32, reorderable: bool) {
+ pub fn dvlc_append_colored_col(&self, title: &str, width: i32, reorderable: bool, align: i32) {
+ let c = CString::new(title).unwrap_or_default();
+ unsafe { notsafe::wxbr_dvlc_append_colored_col(self.0, c.as_ptr(), width, reorderable as c_int) };
+ unsafe {
+ notsafe::wxbr_dvlc_append_colored_col(self.0, c.as_ptr(), width, reorderable as c_int, align)
+ };
+ }
+
+ pub fn dvlc_append_toggle_col(&self, width: i32) {
@@ -660,6 +680,12 @@
+ unsafe { notsafe::wxbr_dvlc_autosize_col(self.0, pos as c_int) }
+ }
+
+ /// Size the column at display position `pos` to its content, then clamp to
+ /// `cap_px`: the width becomes min(cap, content-fit) (round 18 #10).
+ pub fn dvlc_autosize_col_capped(&self, pos: usize, cap_px: i32) {
+ unsafe { notsafe::wxbr_dvlc_autosize_col_capped(self.0, pos as c_int, cap_px) }
+ }
+
+ /// Model column index shown at display position `pos` (after drag reorder).
+ pub fn dvlc_col_at_pos(&self, pos: usize) -> Option<usize> {
+ let v = unsafe { notsafe::wxbr_dvlc_col_at_pos(self.0, pos as c_int) };
+115 -17
View File
@@ -1,6 +1,8 @@
Subject: [PATCH 0003] widget/event bridge, C++ side
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -0,0 +1,2053 @@
@@ -0,0 +1,2149 @@
+// 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).
@@ -338,15 +340,32 @@
+ if (h < 8) h = 8;
+ int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h;
+ if (w < 1) w = 1;
+ const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, w, h);
+ // The Font Awesome fan and brain glyphs fill their square box more than the
+ // other health icons (chip/bolt), so at the shared size they read as oversized.
+ // Draw them a bit smaller, centred in their full-size slot, so the slot advance
+ // and the per-icon tooltip hit-test (both keyed to the full width) are
+ // unchanged (round 17 R1; round 18 #1 brain).
+ int dw = w, dh = h;
+ double glyph_scale = (shape == SHAPE_FAN) ? 0.80 : (shape == SHAPE_BRAIN) ? 0.82 : 1.0;
+ if (glyph_scale < 1.0) {
+ dh = (int)(h * glyph_scale + 0.5);
+ if (dh < 8) dh = 8;
+ dw = (sv->vbh > 0) ? (int)((double)dh * sv->vbw / sv->vbh + 0.5) : dh;
+ if (dw < 1) dw = 1;
+ }
+ const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, dw, dh);
+ if (bmp.IsOk()) {
+ if (health) {
+ // Left-align and advance by less than the icon width so adjacent health
+ // icons sit close together (the Font Awesome glyphs carry inner margin,
+ // so a small bounding-box overlap does not visually collide).
+ dc->DrawBitmap(bmp, x, cy - h / 2, true);
+ int adv = w - 3;
+ return adv < 1 ? 1 : adv;
+ // UNIFORM fixed-width slot (round 19): every health icon (and the
+ // alignment gap) advances by the same amount -- the square (h - 3) -- so
+ // power/control/fan/board icons line up in fixed columns across rows
+ // regardless of each glyph's aspect ratio (a narrow bolt or a shrunk fan
+ // no longer shifts the icons after it). Each glyph is centred in its slot.
+ // This matches SHAPE_GAP's advance and the per-icon tooltip hit-test.
+ int adv = h - 3;
+ if (adv < 1) adv = 1;
+ dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
+ return adv;
+ }
+ int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
+ dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
@@ -441,7 +460,13 @@
+ wxRect bg = cell;
+ if (wxDataViewColumn* owner = const_cast<SegmentRenderer*>(this)->GetOwner()) {
+ int cw = owner->GetWidth();
+ if (cw > bg.width) bg.width = cw;
+ // Extend BOTH directions by the column width. For a right-aligned column
+ // (round 19 #21) wx anchors `cell` at the content's left edge (near the
+ // column's right side), so extending only rightward left the column's left
+ // portion unstriped; over-spanning both sides and letting the cell-DC clip
+ // trim it fills the whole cell regardless of alignment (round 19 review M1).
+ bg.x -= cw;
+ bg.width += 2 * cw;
+ }
+ bg.y -= 40;
+ bg.height += 80;
@@ -524,7 +549,10 @@
+ } else if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
+ int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh;
+ if (health) {
+ adv = ww - 3;
+ // UNIFORM fixed-width slot (round 19), matching DrawShape + the gap, so
+ // every health icon lines up in fixed columns across rows regardless of
+ // its glyph aspect. Width is measured square (hh - 3), not per-glyph.
+ adv = hh - 3;
+ if (adv < 1) adv = 1;
+ } else if (ww > adv) {
+ adv = ww;
@@ -765,6 +793,13 @@
+ wxDefaultPosition, wxSize(-1, -1), style);
+}
+
+// A single-line text control that masks its content (wxTE_PASSWORD), for secret
+// entry so a saved password is never rendered in the clear (round 18 #12).
+void* wxbr_text_ctrl_password(void* parent) {
+ return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
+ wxDefaultPosition, wxSize(-1, -1), wxTE_PASSWORD);
+}
+
+int wxbr_text_ctrl_get(void* win, char* buf, int cap) {
+ wxTextCtrl* t = (wxTextCtrl*)win;
+ wxString v = t->GetValue();
@@ -957,7 +992,10 @@
+ GdkRectangle crect;
+ gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
+ gtk_tree_path_free(path);
+ // Icon advance matches DrawShape's health-icon width (square icons: h - 3).
+ // Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
+ // (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
+ // earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
+ // the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
+ int h = crect.height - 1;
+ int cap = (int)(28 * g_table_zoom + 0.5);
+ if (cap < 8) cap = 8;
@@ -965,13 +1003,45 @@
+ if (h < 8) h = 8;
+ int adv = h - 3;
+ if (adv < 1) adv = 1;
+ int off = bx - crect.x;
+ int n = (int)iit->second.size();
+ // A right-aligned column (round 19 #21) draws the icon block flush to the
+ // cell's right edge, so measure the pointer from the block's left, not the
+ // cell's left.
+ int block_left = crect.x;
+ if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
+ int content_w = n * adv;
+ if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
+ }
+ int off = bx - block_left;
+ if (off < 0) off = 0;
+ int slot = off / adv;
+ if (slot < 0) slot = 0;
+ if (slot >= (int)iit->second.size()) slot = (int)iit->second.size() - 1;
+ if (slot >= n) slot = n - 1;
+ const wxString& tip = iit->second[(size_t)slot];
+ if (tip.IsEmpty()) return FALSE;
+ // Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
+ // Without a tip area GTK defaults it to the whole widget, so it never re-queries
+ // or moves the tooltip as the pointer crosses from one icon to the next -- the
+ // old tooltip just stays put with stale text. Setting a per-slot area makes GTK
+ // hide + re-show + reposition the tooltip for each icon.
+ //
+ // CRITICAL (round 19 #2, the reason the health tooltips never showed): the slot
+ // geometry above (block_left, crect) is in BIN-WINDOW coordinates (what
+ // gtk_tree_view_get_cell_area and get_path_at_pos use), but
+ // gtk_tooltip_set_tip_area expects WIDGET coordinates. Feeding it bin-window
+ // coords offsets the area upward by the header height, so it does not contain
+ // the pointer -- and GTK then suppresses the tooltip entirely (it only shows a
+ // tooltip whose tip area contains the cursor). The Errors column worked because
+ // it sets no tip area. Convert the slot rect back to widget coordinates.
+ gint area_wx = 0, area_wy = 0;
+ gtk_tree_view_convert_bin_window_to_widget_coords(
+ GTK_TREE_VIEW(tv), block_left + slot * adv, crect.y, &area_wx, &area_wy);
+ GdkRectangle area;
+ area.x = area_wx;
+ area.y = area_wy;
+ area.width = adv;
+ area.height = crect.height;
+ gtk_tooltip_set_tip_area(tooltip, &area);
+ gtk_tooltip_set_text(tooltip, tip.utf8_str());
+ return TRUE;
+ }
@@ -1097,14 +1167,23 @@
+ return (void*)dv;
+}
+
+void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable) {
+// Map the bridge alignment code (0 left, 1 right, 2 centre) to a wxAlignment.
+static wxAlignment dvlc_wx_align(int align) {
+ switch (align) {
+ case 1: return wxALIGN_RIGHT;
+ case 2: return wxALIGN_CENTER;
+ default: return wxALIGN_NOT;
+ }
+}
+
+void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable, int align) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ int flags = wxDATAVIEW_COL_RESIZABLE;
+ if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
+ unsigned col = dv->GetColumnCount(); // next model column index
+ dvlc_store(win)->AppendColumn("string");
+ dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
+ width, wxALIGN_NOT, flags);
+ width, dvlc_wx_align(align), flags);
+ // Record the 100% column width for the zoom (round 14 #3); the first column of
+ // a (re)built table resets the list.
+ if (col == 0) g_zoom_base_w.clear();
@@ -1115,15 +1194,17 @@
+// SegmentRenderer so its cell values can carry the '\x1f'/'\x1e' colour-run
+// encoding produced by alkane_gui::model::encode_segments. An ordinary string
+// with no encoding in it still renders fine (single default-coloured run).
+void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable) {
+void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable, int align) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ int flags = wxDATAVIEW_COL_RESIZABLE;
+ if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
+ unsigned col = dv->GetColumnCount(); // next model column index
+ dvlc_store(win)->AppendColumn("string");
+ SegmentRenderer* renderer = new SegmentRenderer();
+ wxAlignment al = dvlc_wx_align(align);
+ renderer->SetAlignment(al);
+ wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
+ width, wxALIGN_NOT, flags);
+ width, al, flags);
+ dv->AppendColumn(c);
+ // Record the 100% column width for the zoom (round 14 #3).
+ if (col == 0) g_zoom_base_w.clear();
@@ -1269,6 +1350,23 @@
+ if (c) c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
+}
+
+// Size a column to fit its content + header, then clamp to cap_px so the default
+// width is min(reasonable cap, content-fit) -- a short column shrinks to its
+// content, a long one is capped at the caller's sensible default (round 18 #10).
+// A small floor keeps a column from collapsing to nothing.
+void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ if (pos < 0 || (unsigned)pos >= dv->GetColumnCount()) return;
+ wxDataViewColumn* c = dv->GetColumn((unsigned)pos);
+ if (!c) return;
+ c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
+ int w = c->GetWidth();
+ const int floor_px = 24;
+ if (w < floor_px) w = floor_px;
+ if (cap_px > 0 && w > cap_px) w = cap_px;
+ c->SetWidth(w);
+}
+
+// Update a column's header text in place (creation index) without recreating
+// the control -- used to refresh the ASCII sort marker on a sort click.
+void wxbr_dvlc_set_col_title(void* win, int col, const char* title) {
@@ -1,39 +0,0 @@
Subject: [PATCH 0005] health tooltips: convert tip area to widget coordinates
Round 19 #2 (the real fix). The GtkTreeView "query-tooltip" handler for the Health
column set a per-icon tip area from gtk_tree_view_get_cell_area, whose rectangle is
in BIN-WINDOW coordinates, but gtk_tooltip_set_tip_area expects WIDGET coordinates.
The area was therefore offset upward by the column-header height, so it did not
contain the pointer -- and GTK suppresses a tooltip whose tip area excludes the
cursor. That is why the health icon tooltips never appeared, while the Errors column
(which sets no tip area) worked. Convert the slot rectangle back to widget
coordinates with gtk_tree_view_convert_bin_window_to_widget_coords before setting it.
diff --git a/cpp_src/widgets_bridge.cpp b/cpp_src/widgets_bridge.cpp
index ba9f1c04..6d09ccb7 100644
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -1019,9 +1019,21 @@ static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keybo
// or moves the tooltip as the pointer crosses from one icon to the next -- the
// old tooltip just stays put with stale text. Setting a per-slot area makes GTK
// hide + re-show + reposition the tooltip for each icon.
+ //
+ // CRITICAL (round 19 #2, the reason the health tooltips never showed): the slot
+ // geometry above (block_left, crect) is in BIN-WINDOW coordinates (what
+ // gtk_tree_view_get_cell_area and get_path_at_pos use), but
+ // gtk_tooltip_set_tip_area expects WIDGET coordinates. Feeding it bin-window
+ // coords offsets the area upward by the header height, so it does not contain
+ // the pointer -- and GTK then suppresses the tooltip entirely (it only shows a
+ // tooltip whose tip area contains the cursor). The Errors column worked because
+ // it sets no tip area. Convert the slot rect back to widget coordinates.
+ gint area_wx = 0, area_wy = 0;
+ gtk_tree_view_convert_bin_window_to_widget_coords(
+ GTK_TREE_VIEW(tv), block_left + slot * adv, crect.y, &area_wx, &area_wy);
GdkRectangle area;
- area.x = block_left + slot * adv;
- area.y = crect.y;
+ area.x = area_wx;
+ area.y = area_wy;
area.width = adv;
area.height = crect.height;
gtk_tooltip_set_tip_area(tooltip, &area);
+85
View File
@@ -0,0 +1,85 @@
Subject: [PATCH 0005] packaging: document the build-only reqwest; drop the case-duplicate readme.md
diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,6 +39,11 @@
[build-dependencies.embed-resource]
version = "1.3"
+# reqwest is only used by build.rs to download the wxWidgets source on
+# Windows/macOS; on Linux download_dist() returns before touching it, and it is
+# never linked into the runtime binary. Kept at the vendored 0.11 (the build tree
+# is fully vendored / offline); the h2 0.3 advisory it pulls is build-time only
+# and is documented as accepted in audit.toml (RUSTSEC-2026-0258).
[build-dependencies.reqwest]
version = "0.11"
features = ["blocking"]
diff -ruN a/readme.md b/readme.md
--- a/readme.md
+++ b/readme.md
@@ -1,64 +0,0 @@
-# wx-rs
-
-[![Crates.io](https://img.shields.io/crates/v/wx-rs)](https://crates.io/crates/wx-rs)
-[![Docs.rs](https://docs.rs/wx-rs/badge.svg)](https://docs.rs/wx-rs)
-
-*This is an alpha release. Don't expect much from me.*
-
-**Only builds on the MSVC toolchain right now**
-
-An extremely partial set of bindings to wxWidgets, for Rust. The intent is that you can import this and all the bits of wxWidgets provided are statically linked in. Implements [`HasRawWindowHandle`](https://crates.io/crates/raw-window-handle). Callbacks are used for rendering and event handling. Features:
-- Window initialization
-- Keyboard, mouse events
-- Clipboard support
-- Native menus
-- Cursor selection
-
-Some things that'd be great to have:
-- The build script has only been tested on MSVC. Previously I've gotten this to compile on OSX and Windows with the GNU toolchain. There's no reason why this can't work on Linux as well.
-- Icon support for Windows/Linux
-
-
-## Building
-The approach this crate takes is to download wxWidgets into the `./dist` directory, then build it. This means that you need to have a toolchain capable of compiling wxWidgets.
-
-Why are we doing this instead of using submodules? Because with submodules cargo would naturally check out files, but this isn't desirable since we want cargo to ignore these files when packaging (because wxWidgets is huge: The package, when you trim out all non-source files is still around 100MB).
-
-Why do we save/compile to `dist` rather than cargo's preferred `OUT_DIR`? Because with the latter, we'd have to recompile wxWidgets more frequently. Since it takes quite a while to do so, it's much nicer to only have to compile once and then have the artifact around forever.
-
-If you want to do a fresh install, just `rm -R ./dist`.
-
-# Building wxWidgets
-
-## Windows
-
-### Using the MSVC toolchain
-
-Make sure you're using ""x64 Native Tools Command Prompt for VS 2019"", and that cargo is in your path when compiling for the first time. After it's built, msys works fine to continue building things from the Rust side.
-- https://stackoverflow.com/questions/11065421/command-prompt-wont-change-directory-to-another-drive
-
-### Using the GNU toolchain on Windows
-This depends on nightly rust to build correctly
-
-#### Getting MSYS2
-https://www.msys2.org/
-
-```
-$ pacman -Syu
-$ pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-make mingw-w64-x86_64-libexpat mingw-w64-x86_64-zlib msys2-w32api-runtime pacman -S mingw-w64-x86_64-lld
-```
-
-#### Building
-This is a note of what needs to be integrated into the build script.
-
-In a MSYS2 MinGW64 terminal:
-
-```
-$ cd dist/wxWidgets
-$ mkdir msw64-release-build
-$ ../configure --with-opengl --disable-shared
-$ make -j20
-```
-
-### Using the OSX toolchain
-... why aren't I documented? :(
@@ -0,0 +1,180 @@
Subject: [PATCH 0006] build.rs: pick the platform from the target, not the build host; build Windows/GNU (mingw wxMSW) through wx-config like GTK
--- a/build.rs
+++ b/build.rs
@@ -12,22 +12,42 @@
const WX_SOURCE: &str =
"https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.2.1/wxWidgets-3.2.2.1.tar.bz2";
+// alkane-toolkit patch: decide the platform from the TARGET. A build script is
+// compiled for and runs on the build host, so `cfg!(windows)` etc. here describe
+// the host -- which made a Linux -> Windows cross build take the GTK path.
+// Cargo exposes the real target through CARGO_CFG_TARGET_* instead.
+fn target_os() -> String {
+ env::var("CARGO_CFG_TARGET_OS").unwrap_or_default()
+}
+
+fn target_env() -> String {
+ env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default()
+}
+
fn is_windows() -> bool {
- cfg!(windows)
+ target_os() == "windows"
}
fn is_msvc() -> bool {
- cfg!(target_env = "msvc")
+ is_windows() && target_env() == "msvc"
}
fn is_osx() -> bool {
- cfg!(target_os = "macos")
+ target_os() == "macos"
}
// alkane-toolkit patch: real wxGTK3 support on Linux via wx-config
// (upstream stubbed every non-Windows/macOS target).
fn is_linux() -> bool {
- cfg!(target_os = "linux")
+ target_os() == "linux"
+}
+
+// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
+// mingw-w64, natively or cross from Linux) both build against a wx prefix
+// described by its wx-config script, so they share one code path. Upstream's
+// MSVC/nmake and macOS download-and-build paths are left as they were.
+fn uses_wx_config() -> bool {
+ is_linux() || (is_windows() && !is_msvc())
}
fn is_stub() -> bool {
@@ -41,8 +61,8 @@
if is_stub() {
return Ok(());
}
- if is_linux() {
- return Ok(()); // libs are linked inside build_linux()
+ if uses_wx_config() {
+ return Ok(()); // libs are linked inside build_with_wx_config()
}
let wx_libs = get_libs(&wx_path)?;
@@ -89,7 +109,7 @@
fn download_dist() -> Result<PathBuf, Box<dyn Error>> {
let dist_path = Path::new("./dist/");
let wx_path = PathBuf::from(format!("./dist/{}", WX_PATH));
- if wx_path.exists() || is_stub() || is_linux() {
+ if wx_path.exists() || is_stub() || uses_wx_config() {
return Ok(wx_path);
}
println!("cargo:warning=wx-rs: Downloading source to './dist/");
@@ -120,8 +140,8 @@
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
- if is_linux() {
- return build_linux();
+ if uses_wx_config() {
+ return build_with_wx_config();
}
if is_windows() {
@@ -232,25 +252,27 @@
)?)
}
-fn build_linux() -> Result<(), Box<dyn Error>> {
- // alkane-toolkit patch: GTK3 build driven entirely by wx-config, so the
- // same code builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG
- // pointing at its prefix) or any system wxGTK3.
+fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
+ // alkane-toolkit patch: build driven entirely by wx-config, so the same code
+ // builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG pointing at its
+ // GTK or mingw prefix) or any system wx. wx-config is a POSIX shell script;
+ // cross builds run it on the Linux host, native mingw builds under MSYS2.
+ println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| String::from("wx-config"));
- let cxxflags = String::from_utf8(
- Command::new(&wxconfig).arg("--cxxflags").output()?.stdout,
- )?;
- let libs = String::from_utf8(Command::new(&wxconfig).arg("--libs").output()?.stdout)?;
- // The widget bridge uses GTK directly (zebra-striping CSS), so add GTK's own
- // include paths. Best-effort: if pkg-config or gtk3-dev is missing the flags
- // are simply empty and the GTK-only code stays disabled.
- let gtk_cflags = Command::new("pkg-config")
- .args(["--cflags", "gtk+-3.0"])
- .output()
- .ok()
- .filter(|o| o.status.success())
- .and_then(|o| String::from_utf8(o.stdout).ok())
- .unwrap_or_default();
+ let wx_config = |arg: &str| -> Result<String, Box<dyn Error>> {
+ let out = Command::new(&wxconfig).arg(arg).output().map_err(|e| {
+ format!("wx-rs: cannot run {wxconfig} {arg} (set WX_RS_WXCONFIG): {e}")
+ })?;
+ if !out.status.success() {
+ return Err(format!("wx-rs: {wxconfig} {arg} failed").into());
+ }
+ Ok(String::from_utf8(out.stdout)?)
+ };
+ let cxxflags = wx_config("--cxxflags")?;
+ let libs = wx_config("--libs")?;
+ if is_windows() && !cxxflags.contains("__WXMSW__") {
+ return Err(format!("wx-rs: {wxconfig} is not a wxMSW build").into());
+ }
let mut build = cc::Build::new();
build.cpp(true)
@@ -259,15 +281,37 @@
for f in cxxflags.split_whitespace() {
build.flag(f);
}
- for f in gtk_cflags.split_whitespace() {
- build.flag(f);
+ if is_linux() {
+ // The widget bridge uses GTK directly (native rubber-band selection,
+ // tooltips, themed colours), so add GTK's own include paths.
+ // Best-effort: if pkg-config or gtk3-dev is missing the flags are simply
+ // empty and the GTK-only code stays disabled.
+ let gtk_cflags = Command::new("pkg-config")
+ .args(["--cflags", "gtk+-3.0"])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+ for f in gtk_cflags.split_whitespace() {
+ build.flag(f);
+ }
+ }
+ if is_windows() {
+ // Ship one self-contained .exe: link the C++ runtime statically rather
+ // than depending on the toolchain's libstdc++-6.dll/libgcc_s_seh-1.dll/
+ // libwinpthread-1.dll, which no Windows machine has. `-bundle` hands the
+ // archives to the final link instead of copying them into this rlib.
+ build.cpp_link_stdlib(None);
+ println!("cargo:rustc-link-lib=static:-bundle=stdc++");
+ println!("cargo:rustc-link-lib=static:-bundle=winpthread");
}
build.compile("wxbridge");
for flag in libs.split_whitespace() {
- if flag.starts_with('/') && flag.ends_with(".a") {
+ if flag.ends_with(".a") && Path::new(flag).is_absolute() {
// static wx builds: wx-config emits the archive as a full path
- let file = flag.rsplit('/').next().unwrap_or(flag);
+ let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
let stem = file
.strip_prefix("lib")
.unwrap_or(file)
@@ -281,6 +325,9 @@
} else if flag == "-pthread" {
println!("cargo:rustc-link-arg=-pthread");
}
+ // `-mwindows` / `-Wl,--subsystem,windows` are deliberately dropped: the
+ // console-vs-GUI subsystem is the application's decision
+ // (`#![windows_subsystem]`), not the GUI library's.
}
Ok(())
}
+147
View File
@@ -0,0 +1,147 @@
Subject: [PATCH 0007] wxbridge: make the upstream frame usable on wxMSW (no input-swallowing overlay, appearance before the first window, work-area sizing, exe icon, UTF-8 menu fix)
--- a/cpp_src/wxbridge.cpp
+++ b/cpp_src/wxbridge.cpp
@@ -1,5 +1,7 @@
#include <wx/wx.h>
#include "wx/clipbrd.h"
+#include "wx/display.h"
+#include <algorithm>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64) || defined(WIN64) || defined(WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
@@ -34,6 +36,21 @@
void setDPIAware() {}
#endif
+#ifdef __WXMSW__
+#include <wx/msw/darkmode.h>
+// alkane-toolkit patch: wx's dark palette leaves wxSYS_COLOUR_3DLIGHT at its
+// light value, and the generic wxDataViewCtrl (the table on MSW) draws its row
+// and column rules in that colour -- bright grid lines across a dark table.
+// Give it a dark-grey rule colour; everything else stays wx's default palette.
+class DarkModeSettings : public wxDarkModeSettings {
+ public:
+ wxColour GetColour(wxSystemColour index) override {
+ if (index == wxSYS_COLOUR_3DLIGHT) return wxColour(0x3a, 0x3a, 0x3a);
+ return wxDarkModeSettings::GetColour(index);
+ }
+};
+#endif
+
enum cursor {
NO_CURSOR,
ARROW_CURSOR,
@@ -129,10 +146,19 @@
render = NULL;
handle_events = NULL;
// Needed to get App to catch key events on OSX
+ // alkane-toolkit patch: not on MSW. There this invisible child ends up above
+ // the application's own widgets in the sibling z-order, and a
+ // wxTRANSPARENT_WINDOW (WS_EX_TRANSPARENT) is transparent to painting only,
+ // not to hit-testing, so it silently swallowed every click and key press
+ // aimed at the real UI. On GTK later siblings stack above it, so it is kept.
+#ifdef __WXMSW__
+ inputWin = NULL;
+#else
inputWin = new wxWindow(this, wxID_ANY,
wxDefaultPosition,
wxSize(-1, -1),
wxBORDER_NONE | wxTRANSPARENT_WINDOW);
+#endif
InitCursors();
Show(true);
@@ -344,12 +370,43 @@
int fake_argc = 0;
char *fake_argv[1] = {NULL};
wxEntryStart(fake_argc, fake_argv);
+ // alkane-toolkit patch: light/dark appearance, decided before the first
+ // window exists because wxMSW cannot switch it afterwards (SetAppearance
+ // then returns CannotChange). System follows the desktop: the GTK theme's
+ // colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
+ // otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
+ {
+ wxString pref;
+ wxGetEnv("ALKANE_APPEARANCE", &pref);
+ pref.MakeLower();
+ wxApp::Appearance appearance = wxApp::Appearance::System;
+ if (pref == "dark") appearance = wxApp::Appearance::Dark;
+ else if (pref == "light") appearance = wxApp::Appearance::Light;
+#ifdef __WXMSW__
+ // Same as SetAppearance(), but with our dark palette tweak (below).
+ if (appearance != wxApp::Appearance::Light) {
+ wxTheApp->MSWEnableDarkMode(appearance == wxApp::Appearance::Dark
+ ? wxApp::DarkMode_Always
+ : wxApp::DarkMode_Auto,
+ new DarkModeSettings()); // wx takes ownership
+ }
+#else
+ wxTheApp->SetAppearance(appearance);
+#endif
+ }
wxTheApp->OnInit();
#ifdef __WINDOWS__
// Adjust the window according to the display scale factor
double scale = wxGetApp().frame->GetDPIScaleFactor();
wxGetApp().frame->SetSize(width * scale, height * scale);
+ // alkane-toolkit patch: title-bar/Alt-Tab icon from the executable's own
+ // icon resource. By wx convention the application icon group is named
+ // "aaaa" (first alphabetically, so Explorer shows it too); an executable
+ // without one keeps the default rather than showing a load-error dialog.
+ if (::FindResourceW(::GetModuleHandleW(NULL), L"aaaa", MAKEINTRESOURCEW(14) /* RT_GROUP_ICON */)) {
+ wxGetApp().frame->SetIcons(wxIconBundle(wxS("aaaa"), ::GetModuleHandleW(NULL)));
+ }
#else
// OSX
double scale = wxGetApp().frame->GetDPIScaleFactor();
@@ -358,6 +415,24 @@
wxGetApp().frame->Move(0.0, 20.0);
}
#endif
+ // alkane-toolkit patch: never open larger than the monitor's work area
+ // (the screen minus taskbar/panels). A 1280x800 request on a 1280x800 or
+ // 1366x768 laptop otherwise put the bottom of the window, with the status
+ // bar, behind the Windows taskbar.
+ {
+ wxFrame* frame = wxGetApp().frame;
+ int index = wxDisplay::GetFromWindow(frame);
+ wxRect work = wxDisplay(index == wxNOT_FOUND ? 0u : (unsigned)index).GetClientArea();
+ wxRect rect = frame->GetRect();
+ if (rect.width > work.width || rect.height > work.height) {
+ rect.SetSize(wxSize(std::min(rect.width, work.width), std::min(rect.height, work.height)));
+ frame->SetSize(rect.GetSize());
+ }
+ if (!work.Contains(frame->GetRect())) {
+ frame->Move(work.x + (work.width - rect.width) / 2,
+ work.y + (work.height - rect.height) / 2);
+ }
+ }
}
void set_render(void (*render)()) {
@@ -602,15 +677,21 @@
}
}
+ // alkane-toolkit patch: Rust hands UTF-8; upstream cast `help` to wxChar*,
+ // which is wchar_t* on MSW (garbage text), and fell off the end of a
+ // non-void function when `i` was out of range (undefined behaviour).
int insert_to_menu(wxMenu* menu, size_t i, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
- return menu->Insert(i, wxID_ANY, str, (help != NULL) ? (const wxChar *) help : wxEmptyString)->GetId();
+ return menu->Insert(i, wxID_ANY, wxString::FromUTF8(str),
+ help ? wxString::FromUTF8(help) : wxString())->GetId();
}
+ return -1;
}
void insert_submenu(wxMenu* menu, size_t i, wxMenu* subMenu, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
- menu->Insert(i, wxID_ANY, str, subMenu, (help != NULL) ? (const wxChar *) help : wxEmptyString);
+ menu->Insert(i, wxID_ANY, wxString::FromUTF8(str), subMenu,
+ help ? wxString::FromUTF8(help) : wxString());
}
}
+691
View File
@@ -0,0 +1,691 @@
Subject: [PATCH 0008] widget bridge: wxMSW support (generic data-view input and tooltips, DIP size boundary, anti-aliased shapes, themed selection colours)
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -36,7 +36,13 @@
#include <cstdio>
#include <cmath>
#include <map>
+#include <memory>
#include <vector>
+#ifdef __WXMSW__
+// Themed list-view colours, to draw selected rows the way the native renderer does.
+#include <wx/msw/uxtheme.h>
+#include <vssym32.h>
+#endif
#ifdef __WXGTK__
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
// enable and which cannot be done via wx mouse events on GTK (the native widget
@@ -48,8 +54,9 @@
static WxWidgetEventFn g_widget_event = nullptr;
#ifndef __WXGTK__
-// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
-// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
+// Anchor row per data-view control for the wx-mouse-event rubber-band selection
+// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
+// uses native GtkTreeView rubber-banding instead).
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
#endif
@@ -72,6 +79,26 @@
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
};
+// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
+// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
+// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
+// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
+// aware wxMSW works in physical pixels, where a 180 px column must become
+// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
+// like) pass through untouched.
+static wxWindow* DipWindow(wxWindow* win) {
+ if (win) return win;
+ return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
+}
+static int PxFromDip(wxWindow* win, int dip) {
+ wxWindow* w = DipWindow(win);
+ return (w && dip > 0) ? w->FromDIP(dip) : dip;
+}
+static int DipFromPx(wxWindow* win, int px) {
+ wxWindow* w = DipWindow(win);
+ return (w && px > 0) ? w->ToDIP(px) : px;
+}
+
// A list store that carries an optional per-row foreground colour plus an
// alternating-row (zebra) background, surfaced to the native control via
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
@@ -196,6 +223,20 @@
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
+// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
+// in DPI-independent logical pixels, so FromDIP() is the identity there and
+// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
+// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
+// size as the (already scaled) text beside it.
+static double DipFactor() {
+ return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
+}
+static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
+// Space one vector shape occupies, at the current display density.
+static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
+// Icon size factor: the table zoom (round 14 #3) times the display density.
+static double ShapeScale() { return g_table_zoom * DipFactor(); }
+
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
// the timer can invalidate exactly it.
@@ -313,7 +354,7 @@
// health icons are square, so the advance is (h - 3) just like a real one.
if (shape == SHAPE_GAP) {
int h = cell.height - 1;
- int cap = (int)(28 * g_table_zoom + 0.5);
+ int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -329,7 +370,7 @@
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int h = cell.height - (health ? 1 : 4);
- int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5);
+ int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -362,25 +403,37 @@
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
return adv;
}
- int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
+ int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
return slot;
}
}
- int cx = x + SHAPE_ADVANCE / 2;
+#ifdef __WXMSW__
+ // GDI does not anti-alias, so the dots and the padlock came out jagged next
+ // to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
+ // Cairo already does on GTK; the context inherits the DC's origin, scale and
+ // clip (the same approach wx's own generic markup renderer takes).
+ std::unique_ptr<wxGCDC> smooth;
+ if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
+ smooth.reset(new wxGCDC(gc));
+ dc = smooth.get();
+ }
+#endif
+ const int adv = ShapeAdvance();
+ int cx = x + adv / 2;
if (shape == SHAPE_LIGHT_BEACON) {
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
- int r = 3;
+ int r = Dip(3);
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(green));
dc->DrawCircle(cx, cy - (r + 1), r);
dc->SetBrush(wxBrush(red));
dc->DrawCircle(cx, cy + (r + 1), r);
- return SHAPE_ADVANCE;
+ return adv;
}
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
wxColour fill = colour;
@@ -391,21 +444,21 @@
}
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(fill));
- dc->DrawCircle(cx, cy, 4);
- return SHAPE_ADVANCE;
+ dc->DrawCircle(cx, cy, Dip(4));
+ return adv;
}
// Padlock: a filled body with a staple shackle above. The colour carries the
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
bool open = (shape == SHAPE_UNLOCK);
- int bw = 9, bh = 7;
+ int bw = Dip(9), bh = Dip(7);
int bx = cx - bw / 2;
int by = cy - bh / 2 + 1;
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(colour));
- dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5);
+ dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
dc->SetBrush(*wxTRANSPARENT_BRUSH);
- dc->SetPen(wxPen(colour, 2));
- int sr = 3;
+ dc->SetPen(wxPen(colour, Dip(2)));
+ int sr = Dip(3);
int legTop = by - sr - 1;
int lx = cx - sr, rx = cx + sr;
dc->DrawLine(lx, by, lx, legTop); // left leg
@@ -414,11 +467,45 @@
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
else
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
- return SHAPE_ADVANCE;
+ return adv;
}
} // namespace
+// True when selected rows keep their own background under a light, translucent
+// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
+// rather than a solid highlight colour.
+static bool SelectionIsTranslucent(wxWindow* win) {
+#ifdef __WXMSW__
+ if (win && wxUxThemeIsActive()) {
+ wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
+ return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
+ }
+#else
+ (void)win;
+#endif
+ return false;
+}
+
+// Text colour for a selected row, matching the platform's native data-view text
+// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
+// selection: a light translucent highlight under the normal dark text, taken
+// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
+// styles off / high contrast -- the selection is a solid highlight, so the text
+// switches to the system highlight-text colour.
+static wxColour SelectedTextColour(wxWindow* win) {
+#ifdef __WXMSW__
+ if (SelectionIsTranslucent(win)) {
+ wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
+ wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
+ if (c.IsOk()) return c;
+ }
+#else
+ (void)win;
+#endif
+ return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
+}
+
class SegmentRenderer : public wxDataViewCustomRenderer {
public:
SegmentRenderer()
@@ -467,7 +554,9 @@
bg.height += 80;
dc->DrawRectangle(bg);
}
- wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
+ wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
+ wxColour highlight =
+ SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
// firmware family, etc. -- must dim exactly like the native columns when the
// top-level window is backdropped. wxGTK dims a native cell's text via the
@@ -503,7 +592,7 @@
if (IsShapeSentinel(seg.text, shape)) {
// Background the shape sits on, so the pulsing locate dot fades toward it.
wxColour cellbg;
- if (selected) {
+ if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
@@ -530,11 +619,11 @@
if (IsShapeSentinel(seg.text, shape)) {
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
- int adv = SHAPE_ADVANCE;
+ int adv = ShapeAdvance();
// Health icons measure bigger and pack tighter, and report a taller
// content height so the row grows to fit them (round 14 #1). Sizes scale
// with the table zoom (round 14 #3).
- int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5);
+ int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
if (hh < 8) hh = 8;
// The alignment gap is one health-icon-width slot that draws nothing
// (round 15 #5); health icons are square, so its advance is hh - 3.
@@ -646,7 +735,7 @@
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
- ((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, border);
+ ((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
}
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
@@ -658,11 +747,12 @@
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
- ((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f, border);
+ ((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
+ PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
}
void wxbr_sizer_add_spacer(void* sizer, int px) {
- ((wxSizer*)sizer)->AddSpacer(px);
+ ((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
}
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
@@ -694,9 +784,11 @@
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
void wxbr_bind_size(void* win) {
- ((wxWindow*)win)->Bind(wxEVT_SIZE, [](wxSizeEvent& e) {
- if (g_widget_event) g_widget_event(WxEV_SIZE, (long)e.GetSize().GetWidth(),
- (long)e.GetSize().GetHeight());
+ wxWindow* w = (wxWindow*)win;
+ w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
+ if (g_widget_event)
+ g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
+ (long)DipFromPx(w, e.GetSize().GetHeight()));
e.Skip();
});
}
@@ -704,7 +796,8 @@
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
void wxbr_set_min_size(void* win, int w, int h) {
- ((wxWindow*)win)->SetMinSize(wxSize(w, h));
+ wxWindow* window = (wxWindow*)win;
+ window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
}
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
@@ -902,7 +995,8 @@
void* wxbr_dialog(void* parent, const char* title) {
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(title), wxDefaultPosition,
- wxSize(360, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
+ DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
+ wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
}
int wxbr_dialog_show_modal(void* win) {
@@ -957,6 +1051,96 @@
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
}
+// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
+// the GTK and generic tooltip paths so both pick the same icon. The slot advance
+// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
+// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
+// column (round 19 #21) draws the icon block flush to the cell's right edge, so
+// slots are measured from the block's left, not the cell's left.
+struct IconSlots {
+ int left; // x of the first slot, in the same coordinates as the cell
+ int adv; // width of one slot
+};
+
+static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
+ bool right_aligned) {
+ int h = cell_h - 1;
+ int cap = (int)(28 * ShapeScale() + 0.5);
+ if (cap < 8) cap = 8;
+ if (h > cap) h = cap;
+ if (h < 8) h = 8;
+ int adv = h - 3;
+ if (adv < 1) adv = 1;
+ int left = cell_x;
+ if (right_aligned) {
+ int content_w = n * adv;
+ if (content_w < cell_w) left = cell_x + (cell_w - content_w);
+ }
+ return IconSlots{left, adv};
+}
+
+static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
+ int off = x - slots.left;
+ if (off < 0) off = 0;
+ int slot = off / slots.adv;
+ if (slot >= n) slot = n - 1;
+ return slot < 0 ? 0 : slot;
+}
+
+#ifndef __WXGTK__
+// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
+// The control draws its rows in an inner main window, which is where mouse
+// events arrive, so the tooltip lives on that window. Windows only re-shows a
+// tooltip when its text is re-set, so the handler tracks the (row, column,
+// icon slot) under the pointer and replaces the tooltip only when it changes;
+// moving from one Health icon to the next therefore pops the right text.
+struct DvTipKey {
+ int row = -1;
+ unsigned col = (unsigned)-1;
+ int slot = -1;
+ bool operator==(const DvTipKey& o) const {
+ return row == o.row && col == o.col && slot == o.slot;
+ }
+};
+static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
+
+// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
+// in src/generic/datavgen.cpp); custom renderers draw inside it.
+static const int GENERIC_CELL_PADDING = 3;
+
+static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
+ const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
+ wxDataViewItem item;
+ wxDataViewColumn* col = nullptr;
+ dv->HitTest(p, item, col);
+ DvTipKey key;
+ wxString tip;
+ if (item.IsOk() && col) {
+ AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
+ key.row = (int)store->GetRow(item);
+ key.col = col->GetModelColumn();
+ auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
+ if (iit != store->icon_tip.end() && !iit->second.empty()) {
+ wxRect r = dv->GetItemRect(item, col);
+ int pad = dv->FromDIP(GENERIC_CELL_PADDING);
+ int n = (int)iit->second.size();
+ IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
+ col->GetAlignment() == wxALIGN_RIGHT);
+ key.slot = HealthIconSlotAt(slots, p.x, n);
+ tip = iit->second[(size_t)key.slot];
+ } else {
+ auto it = store->cell_tip.find({(unsigned)key.row, key.col});
+ if (it != store->cell_tip.end()) tip = it->second;
+ }
+ }
+ DvTipKey& last = g_tip_key[dv];
+ if (last == key) return;
+ last = key;
+ area->UnsetToolTip();
+ if (!tip.IsEmpty()) area->SetToolTip(tip);
+}
+#endif
+
#ifdef __WXGTK__
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
// (row, model column) under the pointer (used by the Errors column). wx does
@@ -987,31 +1171,12 @@
GdkRectangle crect;
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
gtk_tree_path_free(path);
- // Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
- // (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
- // earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
- // the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
- int h = crect.height - 1;
- int cap = (int)(28 * g_table_zoom + 0.5);
- if (cap < 8) cap = 8;
- if (h > cap) h = cap;
- if (h < 8) h = 8;
- int adv = h - 3;
- if (adv < 1) adv = 1;
int n = (int)iit->second.size();
- // A right-aligned column (round 19 #21) draws the icon block flush to the
- // cell's right edge, so measure the pointer from the block's left, not the
- // cell's left.
- int block_left = crect.x;
- if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
- int content_w = n * adv;
- if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
- }
- int off = bx - block_left;
- if (off < 0) off = 0;
- int slot = off / adv;
- if (slot < 0) slot = 0;
- if (slot >= n) slot = n - 1;
+ IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
+ wxcol->GetAlignment() == wxALIGN_RIGHT);
+ int slot = HealthIconSlotAt(slots, bx, n);
+ int adv = slots.adv;
+ int block_left = slots.left;
const wxString& tip = iit->second[(size_t)slot];
if (tip.IsEmpty()) return FALSE;
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
@@ -1103,49 +1268,61 @@
}
}
#else
- // Non-GTK fallback: track a drag anchor and extend the selection to the row
- // under the cursor. LEFT_DOWN records the anchor (and lets the native handler
- // select it); dragging with the button down selects the inclusive range.
- dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
- if (!dv) { e.Skip(); return; }
- // Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
- if (e.ControlDown() || e.ShiftDown()) { g_drag_anchor.erase(dv); e.Skip(); return; }
- wxDataViewItem item;
- wxDataViewColumn* col = nullptr;
- dv->HitTest(e.GetPosition(), item, col);
- if (item.IsOk()) {
- g_drag_anchor[dv] =
- (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
- } else {
+ // Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
+ // anchor and extend the selection to the row under the cursor. The generic
+ // control draws and receives mouse input in an inner "main window", not in
+ // the wxDataViewCtrl itself (mouse events do not propagate to parents), so
+ // the handlers bind there; HitTest wants control coordinates.
+ {
+ wxWindow* area = dv->GetMainWindow();
+ auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
+ wxDataViewItem item;
+ wxDataViewColumn* col = nullptr;
+ dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
+ if (!item.IsOk()) return false;
+ row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
+ return true;
+ };
+ area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
+ // Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
+ int row = -1;
+ if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
+ g_drag_anchor[dv] = row;
+ } else {
+ g_drag_anchor.erase(dv);
+ }
+ e.Skip(); // let the control select the anchor row
+ });
+ area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
+ e.Skip();
+ dvlc_update_tooltip(dv, area, e.GetPosition());
+ auto it = g_drag_anchor.find(dv);
+ int cur = -1;
+ if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
+ return;
+ int lo = it->second < cur ? it->second : cur;
+ int hi = it->second < cur ? cur : it->second;
+ wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
+ wxDataViewItemArray sel;
+ for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
+ dv->SetSelections(sel);
+ // Selecting programmatically does not emit SELECTION_CHANGED, so notify.
+ if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
+ });
+ area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
g_drag_anchor.erase(dv);
- }
- e.Skip(); // let the native handler select the anchor row
- });
- dv->Bind(wxEVT_MOTION, [](wxMouseEvent& e) {
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
- if (!dv || !e.LeftIsDown()) { e.Skip(); return; }
- auto it = g_drag_anchor.find(dv);
- if (it == g_drag_anchor.end()) { e.Skip(); return; }
- wxDataViewItem item;
- wxDataViewColumn* col = nullptr;
- dv->HitTest(e.GetPosition(), item, col);
- if (!item.IsOk()) { e.Skip(); return; }
- wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
- int cur = (int)model->GetRow(item);
- int lo = it->second < cur ? it->second : cur;
- int hi = it->second < cur ? cur : it->second;
- dv->UnselectAll();
- for (int r = lo; r <= hi; ++r) dv->Select(model->GetItem((unsigned)r));
- // Selecting programmatically does not emit SELECTION_CHANGED, so notify.
- if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
- e.Skip();
- });
- dv->Bind(wxEVT_LEFT_UP, [](wxMouseEvent& e) {
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
- if (dv) g_drag_anchor.erase(dv);
- e.Skip();
- });
+ e.Skip();
+ });
+ area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
+ g_tip_key.erase(dv);
+ e.Skip();
+ });
+ dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
+ g_drag_anchor.erase(dv);
+ g_tip_key.erase(dv);
+ e.Skip();
+ });
+ }
#endif
// Row activation (double-click / Enter): report the row + column so the app
// can, e.g., open the miner's IP in a browser.
@@ -1177,6 +1354,7 @@
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
+ width = PxFromDip(dv, width);
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
width, dvlc_wx_align(align), flags);
// Record the 100% column width for the zoom (round 14 #3); the first column of
@@ -1196,6 +1374,7 @@
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
SegmentRenderer* renderer = new SegmentRenderer();
+ width = PxFromDip(dv, width);
wxAlignment al = dvlc_wx_align(align);
renderer->SetAlignment(al);
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
@@ -1211,7 +1390,7 @@
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned col = dv->GetColumnCount();
dvlc_store(win)->AppendColumn("bool");
- dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
+ dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
wxALIGN_CENTRE, 0);
}
@@ -1356,7 +1535,8 @@
if (!c) return;
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
int w = c->GetWidth();
- const int floor_px = 24;
+ cap_px = PxFromDip(dv, cap_px);
+ const int floor_px = PxFromDip(dv, 24);
if (w < floor_px) w = floor_px;
if (cap_px > 0 && w > cap_px) w = cap_px;
c->SetWidth(w);
@@ -1483,7 +1663,7 @@
void* wxbr_gauge(void* parent, int range) {
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
- wxDefaultPosition, wxSize(-1, 6),
+ wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
wxGA_HORIZONTAL | wxGA_SMOOTH);
return (void*)g;
}
@@ -1510,11 +1690,10 @@
// ---- appearance / dark mode -------------------------------------------------
-void wxbr_set_appearance_system() {
-#if wxCHECK_VERSION(3, 3, 0)
- if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System);
-#endif
-}
+// init_app() now sets the appearance before the frame exists (the only point
+// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
+// kept for API compatibility and does nothing further.
+void wxbr_set_appearance_system() {}
int wxbr_is_dark() {
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
@@ -1658,7 +1837,8 @@
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
- wxSize(-1, 240), wxLC_REPORT | wxLC_NO_HEADER);
+ wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
+ wxLC_REPORT | wxLC_NO_HEADER);
lc->EnableCheckBoxes(true);
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
@@ -1874,7 +2054,9 @@
// 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;
+ // The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
+ const int sz = PxFromDip((wxWindow*)parent, 20);
+ const double scale = sz / 20.0;
wxImage img(sz, sz);
img.InitAlpha();
unsigned char* a = img.GetAlpha();
@@ -1885,6 +2067,7 @@
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
if (gc) {
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
+ gc->Scale(scale, scale);
wxColour col(r, g, b);
gc->SetBrush(wxBrush(col));
gc->SetPen(wxPen(col, 1.0));
@@ -1915,9 +2098,10 @@
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
+ // A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
+ // rasterised for the window's actual display scale.
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
- wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
- return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
+ return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
@@ -1990,7 +2174,7 @@
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
wxRect r;
if (sb->GetFieldRect(fld, r)) {
- int ew = 52;
+ int ew = PxFromDip(sb, 52);
int eh = g_zoom_entry->GetBestSize().GetHeight();
if (eh > r.height - 2) eh = r.height - 2;
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
@@ -2039,7 +2223,7 @@
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
- int widths[2] = { -1, 340 };
+ int widths[2] = { -1, PxFromDip(frame, 340) };
sb->SetFieldsCount(2);
sb->SetStatusWidths(2, widths);
if (!g_status_indicator) {
@@ -2072,12 +2256,12 @@
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
- int widths[3] = { -1, 240, 190 };
+ int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
sb->SetFieldsCount(3);
sb->SetStatusWidths(3, widths);
// A native slider needs more vertical room than a default status bar gives, so
// grow the bar to fit it (round 14 #3).
- sb->SetMinHeight(30);
+ sb->SetMinHeight(PxFromDip(frame, 30));
if (!g_zoom_slider) {
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
g_zoom_slider->SetToolTip(wxT("Table zoom"));
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -260,7 +260,8 @@
unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 }
}
-/// Ask wx to follow the system light/dark appearance (no-op before 3.3).
+/// Kept for API compatibility: `init_app` already follows the system light/dark
+/// appearance (or `ALKANE_APPEARANCE=light|dark`), before any window exists.
pub fn set_appearance_system() {
unsafe { notsafe::wxbr_set_appearance_system() }
}
+33
View File
@@ -0,0 +1,33 @@
# wx-rs patch queue
`../wx-rs-0.2.0-patched/` is the tree cargo builds. These patches, applied in
order to the pristine crate in `../upstream/` (digest pinned in `../VERSION`),
must reproduce it byte for byte; CI checks this with
`scripts/wx_rs_patches.py check`.
To change the bridge: edit the patched tree, build and test, then record the
change as the next patch and commit both:
```sh
python3 scripts/wx_rs_patches.py capture short-name "One-line subject" [PATH ...]
```
`capture` limits the patch to the given paths (default: everything that
differs) and re-runs the check. `0002` and `0003` create the widget bridge
files outright, so they carry those files as of the queue's re-baselining;
later changes go in new patches.
| Patch | What |
|-------|------|
| 0001 | Linux/GTK3 build through `wx-config` |
| 0002 | Widget/event bridge, Rust side (`src/widgets.rs`) |
| 0003 | Widget/event bridge, C++ side (`cpp_src/widgets_bridge.cpp`) |
| 0004 | Upstream fixes for wx 3.3 (uninitialised callbacks) |
| 0005 | Packaging: build-only `reqwest` note; drop the case-duplicate `readme.md` |
| 0006 | Build: platform from the target, not the host; Windows/GNU via `wx-config` |
| 0007 | `wxbridge.cpp` on wxMSW: no input-swallowing overlay, appearance before the first window, work-area sizing, executable icon, UTF-8 menu fix |
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
History: the round 19 health-tooltip fix (GTK tip area converted from
bin-window to widget coordinates) used to be a separate patch on top of an
older 0003; it is part of 0003 since the re-baselining.
Binary file not shown.
+78 -31
View File
@@ -12,22 +12,42 @@ const WX_PATH: &str = "wxWidgets-3.2.2.1";
const WX_SOURCE: &str =
"https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.2.1/wxWidgets-3.2.2.1.tar.bz2";
// alkane-toolkit patch: decide the platform from the TARGET. A build script is
// compiled for and runs on the build host, so `cfg!(windows)` etc. here describe
// the host -- which made a Linux -> Windows cross build take the GTK path.
// Cargo exposes the real target through CARGO_CFG_TARGET_* instead.
fn target_os() -> String {
env::var("CARGO_CFG_TARGET_OS").unwrap_or_default()
}
fn target_env() -> String {
env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default()
}
fn is_windows() -> bool {
cfg!(windows)
target_os() == "windows"
}
fn is_msvc() -> bool {
cfg!(target_env = "msvc")
is_windows() && target_env() == "msvc"
}
fn is_osx() -> bool {
cfg!(target_os = "macos")
target_os() == "macos"
}
// alkane-toolkit patch: real wxGTK3 support on Linux via wx-config
// (upstream stubbed every non-Windows/macOS target).
fn is_linux() -> bool {
cfg!(target_os = "linux")
target_os() == "linux"
}
// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
// mingw-w64, natively or cross from Linux) both build against a wx prefix
// described by its wx-config script, so they share one code path. Upstream's
// MSVC/nmake and macOS download-and-build paths are left as they were.
fn uses_wx_config() -> bool {
is_linux() || (is_windows() && !is_msvc())
}
fn is_stub() -> bool {
@@ -41,8 +61,8 @@ fn main() -> Result<(), Box<dyn Error>> {
if is_stub() {
return Ok(());
}
if is_linux() {
return Ok(()); // libs are linked inside build_linux()
if uses_wx_config() {
return Ok(()); // libs are linked inside build_with_wx_config()
}
let wx_libs = get_libs(&wx_path)?;
@@ -89,7 +109,7 @@ fn main() -> Result<(), Box<dyn Error>> {
fn download_dist() -> Result<PathBuf, Box<dyn Error>> {
let dist_path = Path::new("./dist/");
let wx_path = PathBuf::from(format!("./dist/{}", WX_PATH));
if wx_path.exists() || is_stub() || is_linux() {
if wx_path.exists() || is_stub() || uses_wx_config() {
return Ok(wx_path);
}
println!("cargo:warning=wx-rs: Downloading source to './dist/");
@@ -120,8 +140,8 @@ fn build_bridge_lib(wx_path: &Path) -> Result<(), Box<dyn Error>> {
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
if is_linux() {
return build_linux();
if uses_wx_config() {
return build_with_wx_config();
}
if is_windows() {
@@ -232,25 +252,27 @@ fn osx_libs(wx_path: &Path) -> Result<String, Box<dyn Error>> {
)?)
}
fn build_linux() -> Result<(), Box<dyn Error>> {
// alkane-toolkit patch: GTK3 build driven entirely by wx-config, so the
// same code builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG
// pointing at its prefix) or any system wxGTK3.
fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
// alkane-toolkit patch: build driven entirely by wx-config, so the same code
// builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG pointing at its
// GTK or mingw prefix) or any system wx. wx-config is a POSIX shell script;
// cross builds run it on the Linux host, native mingw builds under MSYS2.
println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| String::from("wx-config"));
let cxxflags = String::from_utf8(
Command::new(&wxconfig).arg("--cxxflags").output()?.stdout,
)?;
let libs = String::from_utf8(Command::new(&wxconfig).arg("--libs").output()?.stdout)?;
// The widget bridge uses GTK directly (zebra-striping CSS), so add GTK's own
// include paths. Best-effort: if pkg-config or gtk3-dev is missing the flags
// are simply empty and the GTK-only code stays disabled.
let gtk_cflags = Command::new("pkg-config")
.args(["--cflags", "gtk+-3.0"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
let wx_config = |arg: &str| -> Result<String, Box<dyn Error>> {
let out = Command::new(&wxconfig).arg(arg).output().map_err(|e| {
format!("wx-rs: cannot run {wxconfig} {arg} (set WX_RS_WXCONFIG): {e}")
})?;
if !out.status.success() {
return Err(format!("wx-rs: {wxconfig} {arg} failed").into());
}
Ok(String::from_utf8(out.stdout)?)
};
let cxxflags = wx_config("--cxxflags")?;
let libs = wx_config("--libs")?;
if is_windows() && !cxxflags.contains("__WXMSW__") {
return Err(format!("wx-rs: {wxconfig} is not a wxMSW build").into());
}
let mut build = cc::Build::new();
build.cpp(true)
@@ -259,15 +281,37 @@ fn build_linux() -> Result<(), Box<dyn Error>> {
for f in cxxflags.split_whitespace() {
build.flag(f);
}
for f in gtk_cflags.split_whitespace() {
build.flag(f);
if is_linux() {
// The widget bridge uses GTK directly (native rubber-band selection,
// tooltips, themed colours), so add GTK's own include paths.
// Best-effort: if pkg-config or gtk3-dev is missing the flags are simply
// empty and the GTK-only code stays disabled.
let gtk_cflags = Command::new("pkg-config")
.args(["--cflags", "gtk+-3.0"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
for f in gtk_cflags.split_whitespace() {
build.flag(f);
}
}
if is_windows() {
// Ship one self-contained .exe: link the C++ runtime statically rather
// than depending on the toolchain's libstdc++-6.dll/libgcc_s_seh-1.dll/
// libwinpthread-1.dll, which no Windows machine has. `-bundle` hands the
// archives to the final link instead of copying them into this rlib.
build.cpp_link_stdlib(None);
println!("cargo:rustc-link-lib=static:-bundle=stdc++");
println!("cargo:rustc-link-lib=static:-bundle=winpthread");
}
build.compile("wxbridge");
for flag in libs.split_whitespace() {
if flag.starts_with('/') && flag.ends_with(".a") {
if flag.ends_with(".a") && Path::new(flag).is_absolute() {
// static wx builds: wx-config emits the archive as a full path
let file = flag.rsplit('/').next().unwrap_or(flag);
let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
let stem = file
.strip_prefix("lib")
.unwrap_or(file)
@@ -281,6 +325,9 @@ fn build_linux() -> Result<(), Box<dyn Error>> {
} else if flag == "-pthread" {
println!("cargo:rustc-link-arg=-pthread");
}
// `-mwindows` / `-Wl,--subsystem,windows` are deliberately dropped: the
// console-vs-GUI subsystem is the application's decision
// (`#![windows_subsystem]`), not the GUI library's.
}
Ok(())
}
+293 -109
View File
@@ -36,7 +36,13 @@
#include <cstdio>
#include <cmath>
#include <map>
#include <memory>
#include <vector>
#ifdef __WXMSW__
// Themed list-view colours, to draw selected rows the way the native renderer does.
#include <wx/msw/uxtheme.h>
#include <vssym32.h>
#endif
#ifdef __WXGTK__
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
// enable and which cannot be done via wx mouse events on GTK (the native widget
@@ -48,8 +54,9 @@ typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
static WxWidgetEventFn g_widget_event = nullptr;
#ifndef __WXGTK__
// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
// Anchor row per data-view control for the wx-mouse-event rubber-band selection
// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
// uses native GtkTreeView rubber-banding instead).
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
#endif
@@ -72,6 +79,26 @@ enum WxWidgetEventKind {
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
};
// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
// aware wxMSW works in physical pixels, where a 180 px column must become
// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
// like) pass through untouched.
static wxWindow* DipWindow(wxWindow* win) {
if (win) return win;
return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
}
static int PxFromDip(wxWindow* win, int dip) {
wxWindow* w = DipWindow(win);
return (w && dip > 0) ? w->FromDIP(dip) : dip;
}
static int DipFromPx(wxWindow* win, int px) {
wxWindow* w = DipWindow(win);
return (w && px > 0) ? w->ToDIP(px) : px;
}
// A list store that carries an optional per-row foreground colour plus an
// alternating-row (zebra) background, surfaced to the native control via
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
@@ -196,6 +223,20 @@ static wxVector<int> g_zoom_base_w; // column widths at 100% (per co
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
// in DPI-independent logical pixels, so FromDIP() is the identity there and
// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
// size as the (already scaled) text beside it.
static double DipFactor() {
return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
}
static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
// Space one vector shape occupies, at the current display density.
static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
// Icon size factor: the table zoom (round 14 #3) times the display density.
static double ShapeScale() { return g_table_zoom * DipFactor(); }
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
// the timer can invalidate exactly it.
@@ -313,7 +354,7 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
// health icons are square, so the advance is (h - 3) just like a real one.
if (shape == SHAPE_GAP) {
int h = cell.height - 1;
int cap = (int)(28 * g_table_zoom + 0.5);
int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -329,7 +370,7 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int h = cell.height - (health ? 1 : 4);
int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5);
int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -362,25 +403,37 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
return adv;
}
int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
return slot;
}
}
int cx = x + SHAPE_ADVANCE / 2;
#ifdef __WXMSW__
// GDI does not anti-alias, so the dots and the padlock came out jagged next
// to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
// Cairo already does on GTK; the context inherits the DC's origin, scale and
// clip (the same approach wx's own generic markup renderer takes).
std::unique_ptr<wxGCDC> smooth;
if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
smooth.reset(new wxGCDC(gc));
dc = smooth.get();
}
#endif
const int adv = ShapeAdvance();
int cx = x + adv / 2;
if (shape == SHAPE_LIGHT_BEACON) {
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
int r = 3;
int r = Dip(3);
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(green));
dc->DrawCircle(cx, cy - (r + 1), r);
dc->SetBrush(wxBrush(red));
dc->DrawCircle(cx, cy + (r + 1), r);
return SHAPE_ADVANCE;
return adv;
}
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
wxColour fill = colour;
@@ -391,21 +444,21 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
}
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(fill));
dc->DrawCircle(cx, cy, 4);
return SHAPE_ADVANCE;
dc->DrawCircle(cx, cy, Dip(4));
return adv;
}
// Padlock: a filled body with a staple shackle above. The colour carries the
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
bool open = (shape == SHAPE_UNLOCK);
int bw = 9, bh = 7;
int bw = Dip(9), bh = Dip(7);
int bx = cx - bw / 2;
int by = cy - bh / 2 + 1;
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(colour));
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5);
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
dc->SetBrush(*wxTRANSPARENT_BRUSH);
dc->SetPen(wxPen(colour, 2));
int sr = 3;
dc->SetPen(wxPen(colour, Dip(2)));
int sr = Dip(3);
int legTop = by - sr - 1;
int lx = cx - sr, rx = cx + sr;
dc->DrawLine(lx, by, lx, legTop); // left leg
@@ -414,11 +467,45 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
else
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
return SHAPE_ADVANCE;
return adv;
}
} // namespace
// True when selected rows keep their own background under a light, translucent
// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
// rather than a solid highlight colour.
static bool SelectionIsTranslucent(wxWindow* win) {
#ifdef __WXMSW__
if (win && wxUxThemeIsActive()) {
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
}
#else
(void)win;
#endif
return false;
}
// Text colour for a selected row, matching the platform's native data-view text
// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
// selection: a light translucent highlight under the normal dark text, taken
// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
// styles off / high contrast -- the selection is a solid highlight, so the text
// switches to the system highlight-text colour.
static wxColour SelectedTextColour(wxWindow* win) {
#ifdef __WXMSW__
if (SelectionIsTranslucent(win)) {
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
if (c.IsOk()) return c;
}
#else
(void)win;
#endif
return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
}
class SegmentRenderer : public wxDataViewCustomRenderer {
public:
SegmentRenderer()
@@ -467,7 +554,9 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
bg.height += 80;
dc->DrawRectangle(bg);
}
wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
wxColour highlight =
SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
// firmware family, etc. -- must dim exactly like the native columns when the
// top-level window is backdropped. wxGTK dims a native cell's text via the
@@ -503,7 +592,7 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
if (IsShapeSentinel(seg.text, shape)) {
// Background the shape sits on, so the pulsing locate dot fades toward it.
wxColour cellbg;
if (selected) {
if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
@@ -530,11 +619,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
if (IsShapeSentinel(seg.text, shape)) {
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int adv = SHAPE_ADVANCE;
int adv = ShapeAdvance();
// Health icons measure bigger and pack tighter, and report a taller
// content height so the row grows to fit them (round 14 #1). Sizes scale
// with the table zoom (round 14 #3).
int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5);
int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
if (hh < 8) hh = 8;
// The alignment gap is one health-icon-width slot that draws nothing
// (round 15 #5); health icons are square, so its advance is hh - 3.
@@ -646,7 +735,7 @@ void wxbr_sizer_add(void* sizer, void* win, int proportion, int flags, int borde
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, border);
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
}
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
@@ -658,11 +747,12 @@ void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f, border);
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
}
void wxbr_sizer_add_spacer(void* sizer, int px) {
((wxSizer*)sizer)->AddSpacer(px);
((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
}
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
@@ -694,9 +784,11 @@ void wxbr_sizer_show(void* sizer, void* win, int show) {
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
void wxbr_bind_size(void* win) {
((wxWindow*)win)->Bind(wxEVT_SIZE, [](wxSizeEvent& e) {
if (g_widget_event) g_widget_event(WxEV_SIZE, (long)e.GetSize().GetWidth(),
(long)e.GetSize().GetHeight());
wxWindow* w = (wxWindow*)win;
w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
if (g_widget_event)
g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
(long)DipFromPx(w, e.GetSize().GetHeight()));
e.Skip();
});
}
@@ -704,7 +796,8 @@ void wxbr_bind_size(void* win) {
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
void wxbr_set_min_size(void* win, int w, int h) {
((wxWindow*)win)->SetMinSize(wxSize(w, h));
wxWindow* window = (wxWindow*)win;
window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
}
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
@@ -902,7 +995,8 @@ int wxbr_clb_string(void* win, int i, char* buf, int cap) {
void* wxbr_dialog(void* parent, const char* title) {
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(title), wxDefaultPosition,
wxSize(360, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
}
int wxbr_dialog_show_modal(void* win) {
@@ -957,6 +1051,96 @@ static AttrListStore* dvlc_store(void* win) {
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
}
// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
// the GTK and generic tooltip paths so both pick the same icon. The slot advance
// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
// column (round 19 #21) draws the icon block flush to the cell's right edge, so
// slots are measured from the block's left, not the cell's left.
struct IconSlots {
int left; // x of the first slot, in the same coordinates as the cell
int adv; // width of one slot
};
static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
bool right_aligned) {
int h = cell_h - 1;
int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int adv = h - 3;
if (adv < 1) adv = 1;
int left = cell_x;
if (right_aligned) {
int content_w = n * adv;
if (content_w < cell_w) left = cell_x + (cell_w - content_w);
}
return IconSlots{left, adv};
}
static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
int off = x - slots.left;
if (off < 0) off = 0;
int slot = off / slots.adv;
if (slot >= n) slot = n - 1;
return slot < 0 ? 0 : slot;
}
#ifndef __WXGTK__
// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
// The control draws its rows in an inner main window, which is where mouse
// events arrive, so the tooltip lives on that window. Windows only re-shows a
// tooltip when its text is re-set, so the handler tracks the (row, column,
// icon slot) under the pointer and replaces the tooltip only when it changes;
// moving from one Health icon to the next therefore pops the right text.
struct DvTipKey {
int row = -1;
unsigned col = (unsigned)-1;
int slot = -1;
bool operator==(const DvTipKey& o) const {
return row == o.row && col == o.col && slot == o.slot;
}
};
static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
// in src/generic/datavgen.cpp); custom renderers draw inside it.
static const int GENERIC_CELL_PADDING = 3;
static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(p, item, col);
DvTipKey key;
wxString tip;
if (item.IsOk() && col) {
AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
key.row = (int)store->GetRow(item);
key.col = col->GetModelColumn();
auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
if (iit != store->icon_tip.end() && !iit->second.empty()) {
wxRect r = dv->GetItemRect(item, col);
int pad = dv->FromDIP(GENERIC_CELL_PADDING);
int n = (int)iit->second.size();
IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
col->GetAlignment() == wxALIGN_RIGHT);
key.slot = HealthIconSlotAt(slots, p.x, n);
tip = iit->second[(size_t)key.slot];
} else {
auto it = store->cell_tip.find({(unsigned)key.row, key.col});
if (it != store->cell_tip.end()) tip = it->second;
}
}
DvTipKey& last = g_tip_key[dv];
if (last == key) return;
last = key;
area->UnsetToolTip();
if (!tip.IsEmpty()) area->SetToolTip(tip);
}
#endif
#ifdef __WXGTK__
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
// (row, model column) under the pointer (used by the Errors column). wx does
@@ -987,31 +1171,12 @@ static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keybo
GdkRectangle crect;
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
gtk_tree_path_free(path);
// Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
// (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
// earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
// the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
int h = crect.height - 1;
int cap = (int)(28 * g_table_zoom + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int adv = h - 3;
if (adv < 1) adv = 1;
int n = (int)iit->second.size();
// A right-aligned column (round 19 #21) draws the icon block flush to the
// cell's right edge, so measure the pointer from the block's left, not the
// cell's left.
int block_left = crect.x;
if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
int content_w = n * adv;
if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
}
int off = bx - block_left;
if (off < 0) off = 0;
int slot = off / adv;
if (slot < 0) slot = 0;
if (slot >= n) slot = n - 1;
IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
wxcol->GetAlignment() == wxALIGN_RIGHT);
int slot = HealthIconSlotAt(slots, bx, n);
int adv = slots.adv;
int block_left = slots.left;
const wxString& tip = iit->second[(size_t)slot];
if (tip.IsEmpty()) return FALSE;
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
@@ -1103,49 +1268,61 @@ void* wxbr_dvlc(void* parent) {
}
}
#else
// Non-GTK fallback: track a drag anchor and extend the selection to the row
// under the cursor. LEFT_DOWN records the anchor (and lets the native handler
// select it); dragging with the button down selects the inclusive range.
dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv) { e.Skip(); return; }
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
if (e.ControlDown() || e.ShiftDown()) { g_drag_anchor.erase(dv); e.Skip(); return; }
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(e.GetPosition(), item, col);
if (item.IsOk()) {
g_drag_anchor[dv] =
(int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
} else {
// Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
// anchor and extend the selection to the row under the cursor. The generic
// control draws and receives mouse input in an inner "main window", not in
// the wxDataViewCtrl itself (mouse events do not propagate to parents), so
// the handlers bind there; HitTest wants control coordinates.
{
wxWindow* area = dv->GetMainWindow();
auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
if (!item.IsOk()) return false;
row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
return true;
};
area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
int row = -1;
if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
g_drag_anchor[dv] = row;
} else {
g_drag_anchor.erase(dv);
}
e.Skip(); // let the control select the anchor row
});
area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
e.Skip();
dvlc_update_tooltip(dv, area, e.GetPosition());
auto it = g_drag_anchor.find(dv);
int cur = -1;
if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
return;
int lo = it->second < cur ? it->second : cur;
int hi = it->second < cur ? cur : it->second;
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
wxDataViewItemArray sel;
for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
dv->SetSelections(sel);
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
});
area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
g_drag_anchor.erase(dv);
}
e.Skip(); // let the native handler select the anchor row
});
dv->Bind(wxEVT_MOTION, [](wxMouseEvent& e) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv || !e.LeftIsDown()) { e.Skip(); return; }
auto it = g_drag_anchor.find(dv);
if (it == g_drag_anchor.end()) { e.Skip(); return; }
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(e.GetPosition(), item, col);
if (!item.IsOk()) { e.Skip(); return; }
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
int cur = (int)model->GetRow(item);
int lo = it->second < cur ? it->second : cur;
int hi = it->second < cur ? cur : it->second;
dv->UnselectAll();
for (int r = lo; r <= hi; ++r) dv->Select(model->GetItem((unsigned)r));
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
e.Skip();
});
dv->Bind(wxEVT_LEFT_UP, [](wxMouseEvent& e) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (dv) g_drag_anchor.erase(dv);
e.Skip();
});
e.Skip();
});
area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
g_tip_key.erase(dv);
e.Skip();
});
dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
g_drag_anchor.erase(dv);
g_tip_key.erase(dv);
e.Skip();
});
}
#endif
// Row activation (double-click / Enter): report the row + column so the app
// can, e.g., open the miner's IP in a browser.
@@ -1177,6 +1354,7 @@ void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reor
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
width = PxFromDip(dv, width);
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
width, dvlc_wx_align(align), flags);
// Record the 100% column width for the zoom (round 14 #3); the first column of
@@ -1196,6 +1374,7 @@ void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
SegmentRenderer* renderer = new SegmentRenderer();
width = PxFromDip(dv, width);
wxAlignment al = dvlc_wx_align(align);
renderer->SetAlignment(al);
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
@@ -1211,7 +1390,7 @@ void wxbr_dvlc_append_toggle_col(void* win, int width) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned col = dv->GetColumnCount();
dvlc_store(win)->AppendColumn("bool");
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
wxALIGN_CENTRE, 0);
}
@@ -1356,7 +1535,8 @@ void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
if (!c) return;
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
int w = c->GetWidth();
const int floor_px = 24;
cap_px = PxFromDip(dv, cap_px);
const int floor_px = PxFromDip(dv, 24);
if (w < floor_px) w = floor_px;
if (cap_px > 0 && w > cap_px) w = cap_px;
c->SetWidth(w);
@@ -1483,7 +1663,7 @@ void* wxbr_timer(int id, int ms) {
void* wxbr_gauge(void* parent, int range) {
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
wxDefaultPosition, wxSize(-1, 6),
wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
wxGA_HORIZONTAL | wxGA_SMOOTH);
return (void*)g;
}
@@ -1510,11 +1690,10 @@ int wxbr_launch_browser(const char* url) {
// ---- appearance / dark mode -------------------------------------------------
void wxbr_set_appearance_system() {
#if wxCHECK_VERSION(3, 3, 0)
if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System);
#endif
}
// init_app() now sets the appearance before the frame exists (the only point
// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
// kept for API compatibility and does nothing further.
void wxbr_set_appearance_system() {}
int wxbr_is_dark() {
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
@@ -1658,7 +1837,8 @@ static void ReorderMoveTo(wxListCtrl* lc, const wxPoint& pos) {
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, 240), wxLC_REPORT | wxLC_NO_HEADER);
wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
wxLC_REPORT | wxLC_NO_HEADER);
lc->EnableCheckBoxes(true);
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
@@ -1874,7 +2054,9 @@ void wxbr_choice_set_selection(void* win, int i) {
// 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;
// The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
const int sz = PxFromDip((wxWindow*)parent, 20);
const double scale = sz / 20.0;
wxImage img(sz, sz);
img.InitAlpha();
unsigned char* a = img.GetAlpha();
@@ -1885,6 +2067,7 @@ void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
if (gc) {
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
gc->Scale(scale, scale);
wxColour col(r, g, b);
gc->SetBrush(wxBrush(col));
gc->SetPen(wxPen(col, 1.0));
@@ -1915,9 +2098,10 @@ void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
// A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
// rasterised for the window's actual display scale.
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
@@ -1990,7 +2174,7 @@ static void reposition_status_indicator() {
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
wxRect r;
if (sb->GetFieldRect(fld, r)) {
int ew = 52;
int ew = PxFromDip(sb, 52);
int eh = g_zoom_entry->GetBestSize().GetHeight();
if (eh > r.height - 2) eh = r.height - 2;
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
@@ -2039,7 +2223,7 @@ void wxbr_status_indicator_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[2] = { -1, 340 };
int widths[2] = { -1, PxFromDip(frame, 340) };
sb->SetFieldsCount(2);
sb->SetStatusWidths(2, widths);
if (!g_status_indicator) {
@@ -2072,12 +2256,12 @@ void wxbr_status_zoom_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[3] = { -1, 240, 190 };
int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
sb->SetFieldsCount(3);
sb->SetStatusWidths(3, widths);
// A native slider needs more vertical room than a default status bar gives, so
// grow the bar to fit it (round 14 #3).
sb->SetMinHeight(30);
sb->SetMinHeight(PxFromDip(frame, 30));
if (!g_zoom_slider) {
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
g_zoom_slider->SetToolTip(wxT("Table zoom"));
+83 -2
View File
@@ -1,5 +1,7 @@
#include <wx/wx.h>
#include "wx/clipbrd.h"
#include "wx/display.h"
#include <algorithm>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64) || defined(WIN64) || defined(WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
@@ -34,6 +36,21 @@ void setDPIAware() {
void setDPIAware() {}
#endif
#ifdef __WXMSW__
#include <wx/msw/darkmode.h>
// alkane-toolkit patch: wx's dark palette leaves wxSYS_COLOUR_3DLIGHT at its
// light value, and the generic wxDataViewCtrl (the table on MSW) draws its row
// and column rules in that colour -- bright grid lines across a dark table.
// Give it a dark-grey rule colour; everything else stays wx's default palette.
class DarkModeSettings : public wxDarkModeSettings {
public:
wxColour GetColour(wxSystemColour index) override {
if (index == wxSYS_COLOUR_3DLIGHT) return wxColour(0x3a, 0x3a, 0x3a);
return wxDarkModeSettings::GetColour(index);
}
};
#endif
enum cursor {
NO_CURSOR,
ARROW_CURSOR,
@@ -129,10 +146,19 @@ MyFrame::MyFrame(const wxString& title, const wxSize& size)
render = NULL;
handle_events = NULL;
// Needed to get App to catch key events on OSX
// alkane-toolkit patch: not on MSW. There this invisible child ends up above
// the application's own widgets in the sibling z-order, and a
// wxTRANSPARENT_WINDOW (WS_EX_TRANSPARENT) is transparent to painting only,
// not to hit-testing, so it silently swallowed every click and key press
// aimed at the real UI. On GTK later siblings stack above it, so it is kept.
#ifdef __WXMSW__
inputWin = NULL;
#else
inputWin = new wxWindow(this, wxID_ANY,
wxDefaultPosition,
wxSize(-1, -1),
wxBORDER_NONE | wxTRANSPARENT_WINDOW);
#endif
InitCursors();
Show(true);
@@ -344,12 +370,43 @@ extern "C" {
int fake_argc = 0;
char *fake_argv[1] = {NULL};
wxEntryStart(fake_argc, fake_argv);
// alkane-toolkit patch: light/dark appearance, decided before the first
// window exists because wxMSW cannot switch it afterwards (SetAppearance
// then returns CannotChange). System follows the desktop: the GTK theme's
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
{
wxString pref;
wxGetEnv("ALKANE_APPEARANCE", &pref);
pref.MakeLower();
wxApp::Appearance appearance = wxApp::Appearance::System;
if (pref == "dark") appearance = wxApp::Appearance::Dark;
else if (pref == "light") appearance = wxApp::Appearance::Light;
#ifdef __WXMSW__
// Same as SetAppearance(), but with our dark palette tweak (below).
if (appearance != wxApp::Appearance::Light) {
wxTheApp->MSWEnableDarkMode(appearance == wxApp::Appearance::Dark
? wxApp::DarkMode_Always
: wxApp::DarkMode_Auto,
new DarkModeSettings()); // wx takes ownership
}
#else
wxTheApp->SetAppearance(appearance);
#endif
}
wxTheApp->OnInit();
#ifdef __WINDOWS__
// Adjust the window according to the display scale factor
double scale = wxGetApp().frame->GetDPIScaleFactor();
wxGetApp().frame->SetSize(width * scale, height * scale);
// alkane-toolkit patch: title-bar/Alt-Tab icon from the executable's own
// icon resource. By wx convention the application icon group is named
// "aaaa" (first alphabetically, so Explorer shows it too); an executable
// without one keeps the default rather than showing a load-error dialog.
if (::FindResourceW(::GetModuleHandleW(NULL), L"aaaa", MAKEINTRESOURCEW(14) /* RT_GROUP_ICON */)) {
wxGetApp().frame->SetIcons(wxIconBundle(wxS("aaaa"), ::GetModuleHandleW(NULL)));
}
#else
// OSX
double scale = wxGetApp().frame->GetDPIScaleFactor();
@@ -358,6 +415,24 @@ extern "C" {
wxGetApp().frame->Move(0.0, 20.0);
}
#endif
// alkane-toolkit patch: never open larger than the monitor's work area
// (the screen minus taskbar/panels). A 1280x800 request on a 1280x800 or
// 1366x768 laptop otherwise put the bottom of the window, with the status
// bar, behind the Windows taskbar.
{
wxFrame* frame = wxGetApp().frame;
int index = wxDisplay::GetFromWindow(frame);
wxRect work = wxDisplay(index == wxNOT_FOUND ? 0u : (unsigned)index).GetClientArea();
wxRect rect = frame->GetRect();
if (rect.width > work.width || rect.height > work.height) {
rect.SetSize(wxSize(std::min(rect.width, work.width), std::min(rect.height, work.height)));
frame->SetSize(rect.GetSize());
}
if (!work.Contains(frame->GetRect())) {
frame->Move(work.x + (work.width - rect.width) / 2,
work.y + (work.height - rect.height) / 2);
}
}
}
void set_render(void (*render)()) {
@@ -602,15 +677,21 @@ extern "C" {
}
}
// alkane-toolkit patch: Rust hands UTF-8; upstream cast `help` to wxChar*,
// which is wchar_t* on MSW (garbage text), and fell off the end of a
// non-void function when `i` was out of range (undefined behaviour).
int insert_to_menu(wxMenu* menu, size_t i, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
return menu->Insert(i, wxID_ANY, str, (help != NULL) ? (const wxChar *) help : wxEmptyString)->GetId();
return menu->Insert(i, wxID_ANY, wxString::FromUTF8(str),
help ? wxString::FromUTF8(help) : wxString())->GetId();
}
return -1;
}
void insert_submenu(wxMenu* menu, size_t i, wxMenu* subMenu, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
menu->Insert(i, wxID_ANY, str, subMenu, (help != NULL) ? (const wxChar *) help : wxEmptyString);
menu->Insert(i, wxID_ANY, wxString::FromUTF8(str), subMenu,
help ? wxString::FromUTF8(help) : wxString());
}
}
+2 -1
View File
@@ -260,7 +260,8 @@ pub fn launch_browser(url: &str) -> bool {
unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 }
}
/// Ask wx to follow the system light/dark appearance (no-op before 3.3).
/// Kept for API compatibility: `init_app` already follows the system light/dark
/// appearance (or `ALKANE_APPEARANCE=light|dark`), before any window exists.
pub fn set_appearance_system() {
unsafe { notsafe::wxbr_set_appearance_system() }
}
+4
View File
@@ -3,3 +3,7 @@ version: 3.3.3
source_url: https://github.com/wxWidgets/wxWidgets/releases/download/v3.3.3/wxWidgets-3.3.3.tar.bz2
sha256: 81b09d6dd9f1ed9301f8c55a968a488d0491f264dc2bab19a7e407ac67009482
note: pristine dist tarball (includes 3rdparty submodules). Builds happen out-of-tree via scripts/build-wx-linux.sh - the repo tree is never built in place.
update: the tarball carries its own nested .gitignore files, so stage a new
tree with `git add -f` and check `diff -rq` against the unpacked tarball;
a plain `git add` silently drops generated files (pnglibconf.h, PCRE2's
configure, libtiff build/) that the mingw cross build needs.
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
</Project>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+279
View File
@@ -0,0 +1,279 @@
#! /bin/sh
# Wrapper for Microsoft lib.exe
me=ar-lib
scriptversion=2024-06-19.01; # UTC
# Copyright (C) 2010-2024 Free Software Foundation, Inc.
# Written by Peter Rosin <peda@lysator.liu.se>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
# func_error message
func_error ()
{
echo "$me: $1" 1>&2
exit 1
}
file_conv=
# func_file_conv build_file
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN* | MSYS*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv in
mingw)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin | msys)
file=`cygpath -m "$file" || echo "$file"`
;;
wine)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_at_file at_file operation archive
# Iterate over all members in AT_FILE performing OPERATION on ARCHIVE
# for each of them.
# When interpreting the content of the @FILE, do NOT use func_file_conv,
# since the user would need to supply preconverted file names to
# binutils ar, at least for MinGW.
func_at_file ()
{
operation=$2
archive=$3
at_file_contents=`cat "$1"`
eval set x "$at_file_contents"
shift
for member
do
$AR -NOLOGO $operation:"$member" "$archive" || exit $?
done
}
case $1 in
'')
func_error "no command. Try '$0 --help' for more information."
;;
-h | --h*)
cat <<EOF
Usage: $me [--help] [--version] PROGRAM ACTION ARCHIVE [MEMBER...]
Members may be specified in a file named with @FILE.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
EOF
exit $?
;;
-v | --v*)
echo "$me (GNU Automake) $scriptversion"
exit $?
;;
esac
if test $# -lt 3; then
func_error "you must specify a program, an action and an archive"
fi
AR=$1
shift
while :
do
if test $# -lt 2; then
func_error "you must specify a program, an action and an archive"
fi
case $1 in
-lib | -LIB \
| -ltcg | -LTCG \
| -machine* | -MACHINE* \
| -subsystem* | -SUBSYSTEM* \
| -verbose | -VERBOSE \
| -wx* | -WX* )
AR="$AR $1"
shift
;;
-nologo | -NOLOGO)
# We always invoke AR with -nologo, so don't need to add it again.
shift
;;
*)
action=$1
shift
break
;;
esac
done
orig_archive=$1
shift
func_file_conv "$orig_archive"
archive=$file
# strip leading dash in $action
action=${action#-}
delete=
extract=
list=
quick=
replace=
index=
create=
while test -n "$action"
do
case $action in
d*) delete=yes ;;
x*) extract=yes ;;
t*) list=yes ;;
q*) quick=yes ;;
r*) replace=yes ;;
s*) index=yes ;;
S*) ;; # the index is always updated implicitly
c*) create=yes ;;
u*) ;; # TODO: don't ignore the update modifier
v*) ;; # TODO: don't ignore the verbose modifier
*)
func_error "unknown action specified"
;;
esac
action=${action#?}
done
case $delete$extract$list$quick$replace,$index in
yes,* | ,yes)
;;
yesyes*)
func_error "more than one action specified"
;;
*)
func_error "no action specified"
;;
esac
if test -n "$delete"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
for member
do
case $1 in
@*)
func_at_file "${1#@}" -REMOVE "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -REMOVE:"$file" "$archive" || exit $?
;;
esac
done
elif test -n "$extract"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
if test $# -gt 0; then
for member
do
case $1 in
@*)
func_at_file "${1#@}" -EXTRACT "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -EXTRACT:"$file" "$archive" || exit $?
;;
esac
done
else
$AR -NOLOGO -LIST "$archive" | tr -d '\r' | sed -e 's/\\/\\\\/g' \
| while read member
do
$AR -NOLOGO -EXTRACT:"$member" "$archive" || exit $?
done
fi
elif test -n "$quick$replace"; then
if test ! -f "$orig_archive"; then
if test -z "$create"; then
echo "$me: creating $orig_archive"
fi
orig_archive=
else
orig_archive=$archive
fi
for member
do
case $1 in
@*)
func_file_conv "${1#@}"
set x "$@" "@$file"
;;
*)
func_file_conv "$1"
set x "$@" "$file"
;;
esac
shift
shift
done
if test -n "$orig_archive"; then
$AR -NOLOGO -OUT:"$archive" "$orig_archive" "$@" || exit $?
else
$AR -NOLOGO -OUT:"$archive" "$@" || exit $?
fi
elif test -n "$list"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
$AR -NOLOGO -LIST "$archive" || exit $?
fi
+351
View File
@@ -0,0 +1,351 @@
#! /bin/sh
# Wrapper for compilers which do not understand '-c -o'.
scriptversion=2024-06-19.01; # UTC
# Copyright (C) 1999-2024 Free Software Foundation, Inc.
# Written by Tom Tromey <tromey@cygnus.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
nl='
'
# We need space, tab and new line, in precisely that order. Quoting is
# there to prevent tools from complaining about whitespace usage.
IFS=" "" $nl"
file_conv=
# func_file_conv build_file lazy
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts. If the determined conversion
# type is listed in (the comma separated) LAZY, no conversion will
# take place.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN* | MSYS*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv/,$2, in
*,$file_conv,*)
;;
mingw/*)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin/* | msys/*)
file=`cygpath -m "$file" || echo "$file"`
;;
wine/*)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_cl_dashL linkdir
# Make cl look for libraries in LINKDIR
func_cl_dashL ()
{
func_file_conv "$1"
if test -z "$lib_path"; then
lib_path=$file
else
lib_path="$lib_path;$file"
fi
linker_opts="$linker_opts -LIBPATH:$file"
}
# func_cl_dashl library
# Do a library search-path lookup for cl
func_cl_dashl ()
{
lib=$1
found=no
save_IFS=$IFS
IFS=';'
for dir in $lib_path $LIB
do
IFS=$save_IFS
if $shared && test -f "$dir/$lib.dll.lib"; then
found=yes
lib=$dir/$lib.dll.lib
break
fi
if test -f "$dir/$lib.lib"; then
found=yes
lib=$dir/$lib.lib
break
fi
if test -f "$dir/lib$lib.a"; then
found=yes
lib=$dir/lib$lib.a
break
fi
done
IFS=$save_IFS
if test "$found" != yes; then
lib=$lib.lib
fi
}
# func_cl_wrapper cl arg...
# Adjust compile command to suit cl
func_cl_wrapper ()
{
# Assume a capable shell
lib_path=
shared=:
linker_opts=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
eat=1
case $2 in
*.o | *.lo | *.[oO][bB][jJ])
func_file_conv "$2"
set x "$@" -Fo"$file"
shift
;;
*)
func_file_conv "$2"
set x "$@" -Fe"$file"
shift
;;
esac
;;
-I)
eat=1
func_file_conv "$2" mingw
set x "$@" -I"$file"
shift
;;
-I*)
func_file_conv "${1#-I}" mingw
set x "$@" -I"$file"
shift
;;
-l)
eat=1
func_cl_dashl "$2"
set x "$@" "$lib"
shift
;;
-l*)
func_cl_dashl "${1#-l}"
set x "$@" "$lib"
shift
;;
-L)
eat=1
func_cl_dashL "$2"
;;
-L*)
func_cl_dashL "${1#-L}"
;;
-static)
shared=false
;;
-Wl,*)
arg=${1#-Wl,}
save_ifs="$IFS"; IFS=','
for flag in $arg; do
IFS="$save_ifs"
linker_opts="$linker_opts $flag"
done
IFS="$save_ifs"
;;
-Xlinker)
eat=1
linker_opts="$linker_opts $2"
;;
-*)
set x "$@" "$1"
shift
;;
*.cc | *.CC | *.cxx | *.CXX | *.[cC]++)
func_file_conv "$1"
set x "$@" -Tp"$file"
shift
;;
*.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO])
func_file_conv "$1" mingw
set x "$@" "$file"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -n "$linker_opts"; then
linker_opts="-link$linker_opts"
fi
exec "$@" $linker_opts
exit 1
}
eat=
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: compile [--help] [--version] PROGRAM [ARGS]
Wrapper for compilers which do not understand '-c -o'.
Remove '-o dest.o' from ARGS, run PROGRAM with the remaining
arguments, and rename the output as expected.
If you are trying to build a whole package this is not the
right script to run: please start by reading the file 'INSTALL'.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
EOF
exit $?
;;
-v | --v*)
echo "compile (GNU Automake) $scriptversion"
exit $?
;;
cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \
clang-cl | *[/\\]clang-cl | clang-cl.exe | *[/\\]clang-cl.exe | \
icl | *[/\\]icl | icl.exe | *[/\\]icl.exe )
func_cl_wrapper "$@" # Doesn't return...
;;
esac
ofile=
cfile=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
# So we strip '-o arg' only if arg is an object.
eat=1
case $2 in
*.o | *.obj)
ofile=$2
;;
*)
set x "$@" -o "$2"
shift
;;
esac
;;
*.c)
cfile=$1
set x "$@" "$1"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -z "$ofile" || test -z "$cfile"; then
# If no '-o' option was seen then we might have been invoked from a
# pattern rule where we don't need one. That is ok -- this is a
# normal compilation that the losing compiler can handle. If no
# '.c' file was seen then we are probably linking. That is also
# ok.
exec "$@"
fi
# Name of file we expect compiler to create.
cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
# Create the lock directory.
# Note: use '[/\\:.-]' here to ensure that we don't use the same name
# that we are using for the .o file. Also, base the name on the expected
# object file name, since that is what matters with a parallel build.
lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
while true; do
if mkdir "$lockdir" >/dev/null 2>&1; then
break
fi
sleep 1
done
# FIXME: race condition here if user kills between mkdir and trap.
trap "rmdir '$lockdir'; exit 1" 1 2 15
# Run the compile.
"$@"
ret=$?
if test -f "$cofile"; then
test "$cofile" = "$ofile" || mv "$cofile" "$ofile"
elif test -f "${cofile}bj"; then
test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile"
fi
rmdir "$lockdir"
exit $ret
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More