Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1b7a3dbc0 | ||
|
|
8275f893dd | ||
|
|
36f12d6d4e | ||
|
|
a4d82bf45b | ||
|
|
d925414bc8 | ||
|
|
9f9fe18926 | ||
|
|
d8d044f439 | ||
|
|
517bee9b9e | ||
|
|
10d7fd6d95 | ||
|
|
9b440a46e3 | ||
|
|
c3b0dc6c8a | ||
|
|
bfda29a845 | ||
|
|
2c58cbac48 | ||
|
|
174b162dfd | ||
|
|
cbf0f70cf6 | ||
|
|
332a3f7419 | ||
|
|
3931b6348f | ||
|
|
69b1b6e6fb | ||
|
|
a732f01ac9 | ||
|
|
6da34a55e8 | ||
|
|
be5edfc2bf | ||
|
|
569ef9dcd8 | ||
|
|
b1313fd059 | ||
|
|
9ad8b56c1f | ||
|
|
28f8f9ce80 | ||
|
|
d35cedd056 | ||
|
|
a825299ebc | ||
|
|
a17f108050 | ||
|
|
3faa35ea70 | ||
|
|
16490dd3b9 | ||
|
|
e6ae9d9d50 | ||
|
|
fc1ed3e4e5 | ||
|
|
d7a914258e | ||
|
|
2108f47eea | ||
|
|
d4a1db7243 | ||
|
|
18acc31a28 | ||
|
|
d780fe007a | ||
|
|
f18bad36f3 | ||
|
|
d7ae81dce9 | ||
|
|
10c93a3246 | ||
|
|
50ff6c60ce | ||
|
|
cfe1f5be3b |
@@ -1,33 +0,0 @@
|
||||
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-pages
|
||||
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
|
||||
@@ -7,9 +7,9 @@ on:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-fast
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
|
||||
@@ -12,10 +12,83 @@ 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:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
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
|
||||
@@ -65,11 +138,23 @@ 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: |
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
name: pages
|
||||
|
||||
# The project site, https://blueflare.gitea.bluefla.re/alkane-toolkit/ :
|
||||
# overview, user manual (docs/manual), code-quality dashboard (from the
|
||||
# quality record main CI publishes with the badges) and benchmark history.
|
||||
# Rebuilt after every main build-test-release run and published to this
|
||||
# repository's gh-pages branch.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [build-test-release]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install page tools
|
||||
run: bash ci/ensure-build-deps.sh pages
|
||||
- name: Render measured benchmark history
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/bench_history.py render
|
||||
- name: Fetch measured quality record
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/fetch-quality.py quality.json
|
||||
- name: Build site
|
||||
run: |
|
||||
python3 ci/build-pages.py --out site --quality quality.json \
|
||||
--bench bench-site/index.html --sha "$GITHUB_SHA"
|
||||
- name: Publish site
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/publish-pages.py site
|
||||
- name: Clean generated site
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -1,7 +1,8 @@
|
||||
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]
|
||||
@@ -15,10 +16,119 @@ permissions:
|
||||
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:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
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
|
||||
@@ -35,6 +145,15 @@ jobs:
|
||||
- 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"
|
||||
@@ -152,8 +271,10 @@ jobs:
|
||||
set -euo pipefail
|
||||
rustup component add llvm-tools-preview >/dev/null 2>&1 || true
|
||||
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
|
||||
PCT=$(bash ci/coverage.sh --summary-only \
|
||||
| awk '/^TOTAL/{gsub(/%/,"",$10); print $10}')
|
||||
# Keep the whole table: gen-badges turns it into the per-crate and
|
||||
# per-file breakdown on the Pages quality dashboard.
|
||||
bash ci/coverage.sh --summary-only | tee coverage-summary.txt
|
||||
PCT=$(awk '/^TOTAL/{gsub(/%/,"",$10); print $10}' coverage-summary.txt)
|
||||
[ -n "$PCT" ] || { echo "coverage report produced no TOTAL line" >&2; exit 1; }
|
||||
echo "pct=${PCT}" >> "$GITHUB_OUTPUT"
|
||||
echo "line coverage (tests + self-test): ${PCT}%"
|
||||
@@ -181,7 +302,8 @@ jobs:
|
||||
python3 ci/gen-badges.py --tests "$PASS" \
|
||||
--coverage "${{ steps.cov.outputs.pct }}" \
|
||||
--bench-coverage "${{ steps.benchcov.outputs.pct }}" \
|
||||
--bench-delta "$BENCH_DELTA" --clippy clean
|
||||
--bench-delta "$BENCH_DELTA" --clippy clean \
|
||||
--coverage-summary coverage-summary.txt
|
||||
|
||||
- name: Publish measured badges
|
||||
env:
|
||||
@@ -218,11 +340,30 @@ 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'
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
check:
|
||||
runs-on: alkane-fast
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
env:
|
||||
CARGO_BUILD_JOBS: 2
|
||||
steps:
|
||||
|
||||
+115
-6
@@ -13,7 +13,9 @@ jobs:
|
||||
verify:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
outputs:
|
||||
surface: ${{ steps.surface.outputs.surface }}
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
@@ -28,6 +30,9 @@ jobs:
|
||||
- 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"
|
||||
@@ -37,23 +42,56 @@ jobs:
|
||||
run: |
|
||||
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
|
||||
git diff --check "$base" HEAD
|
||||
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; then
|
||||
# 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: 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 != 'documentation'
|
||||
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 != 'documentation'
|
||||
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
|
||||
run: bash ci/configure-rust-cache.sh
|
||||
|
||||
- name: Compute wxWidgets cache key
|
||||
@@ -138,7 +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 != 'documentation'
|
||||
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
|
||||
@@ -147,7 +185,7 @@ jobs:
|
||||
echo "cargo-audit not installed on this runner; skipping"
|
||||
fi
|
||||
- name: Rust compiler cache statistics
|
||||
if: always() && steps.surface.outputs.surface != 'documentation'
|
||||
if: always() && (steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full')
|
||||
run: |
|
||||
if [ -n "${SCCACHE_DIR:-}" ]; then
|
||||
sccache --show-stats
|
||||
@@ -155,3 +193,74 @@ jobs:
|
||||
- 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
|
||||
|
||||
@@ -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 }
|
||||
@@ -2,3 +2,8 @@
|
||||
**/target
|
||||
.claude/
|
||||
__pycache__/
|
||||
# Internal working notes live outside this public repository.
|
||||
/AGENTS.md
|
||||
/HANDOFF.md
|
||||
/CLAUDE.md
|
||||
code-review-report*.md
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Blueflare
|
||||
Copyright (c) 2026 BlueFlare Energy Solutions Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
# Alkane Toolkit
|
||||
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/#coverage)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/#coverage)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](LICENSE)
|
||||
|
||||
The badges link to the [project site](https://blueflare.gitea.bluefla.re/alkane-toolkit/): the [manual](https://blueflare.gitea.bluefla.re/alkane-toolkit/manual/),
|
||||
the [code-quality dashboard](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) (how the grade is set, coverage by
|
||||
crate and file) and the [benchmark history](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/).
|
||||
|
||||
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
|
||||
a patched [wx-rs bridge](thirdparty/wx-rs). Firmware installation is under
|
||||
development.
|
||||
a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled
|
||||
while that path is reworked.
|
||||
|
||||
## Run locally
|
||||
|
||||
@@ -23,18 +27,23 @@ ALKANE_FAKE_SCAN=1 ~/.cache/alkane-tk-target/release/alkane-toolkit
|
||||
```
|
||||
|
||||
The first command builds wxWidgets 3.3.3 once. Linux needs GTK 3. Fake scan
|
||||
uses offline fixtures and does not contact hardware. For Windows and macOS,
|
||||
use the matching `scripts/build-gui-*.sh` script.
|
||||
uses offline fixtures and does not contact hardware.
|
||||
|
||||
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.
|
||||
|
||||
## Current scope
|
||||
|
||||
- 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.
|
||||
|
||||
Discovery is read-only. The installer and operator actions remain in the
|
||||
[implementation plan](docs/IMPLEMENTATION-PLAN.md) and
|
||||
[firmware matrix](docs/aftermarket-parity-roadmap.md).
|
||||
Discovery is read-only. Control and restore actions change miners. Check the
|
||||
selected devices before applying them.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -46,8 +55,8 @@ WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config" \
|
||||
|
||||
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/).
|
||||
code, not installation support. See the
|
||||
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/).
|
||||
|
||||
## Firmware safety
|
||||
|
||||
|
||||
+70
-9
@@ -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,12 +163,14 @@ 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")
|
||||
|
||||
|
||||
@@ -136,10 +186,16 @@ 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
|
||||
if args.action == "render":
|
||||
if not index["entries"]:
|
||||
@@ -148,8 +204,13 @@ def main() -> None:
|
||||
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()}
|
||||
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"
|
||||
|
||||
Executable
+293
@@ -0,0 +1,293 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Build the Alkane Toolkit Pages site (served from this repo's gh-pages).
|
||||
|
||||
build-pages.py --out site [--manual docs/manual] [--quality quality.json]
|
||||
[--bench bench-site/index.html] [--sha SHA]
|
||||
|
||||
Pages:
|
||||
/ overview and downloads
|
||||
/manual/ the user manual, one page per docs/manual/NN-name.md chapter
|
||||
/quality/ code-quality dashboard from the measured quality.json that main
|
||||
CI publishes next to the badges (ci/gen-badges.py)
|
||||
/bench/ the measured benchmark history (ci/bench_history.py render)
|
||||
|
||||
Every value taken from CI data is HTML-escaped; the manual is Markdown written
|
||||
in this repository.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import markdown
|
||||
|
||||
REPO = "https://gitea.bluefla.re/blueflare/alkane-toolkit"
|
||||
RELEASES = REPO + "/releases"
|
||||
SECTIONS = (("", "Overview"), ("manual/", "Manual"), ("quality/", "Code quality"),
|
||||
("bench/", "Benchmarks"))
|
||||
|
||||
CSS = """
|
||||
:root { --bg:#ffffff; --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --card:#f6f8fa;
|
||||
--accent:#d9822b; --link:#0969da; --good:#1a7f37; --warn:#9a6700; --bad:#cf222e; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --fg:#e6edf3; --muted:#9198a1;
|
||||
--line:#30363d; --card:#151b23; --link:#4493f8; --good:#3fb950; --warn:#d29922; --bad:#f85149; } }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--fg);
|
||||
font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,sans-serif; }
|
||||
a { color:var(--link); text-decoration:none; } a:hover { text-decoration:underline; }
|
||||
header { border-bottom:1px solid var(--line); }
|
||||
header .bar, main { max-width:1040px; margin:0 auto; padding:0 16px; }
|
||||
header .bar { display:flex; align-items:center; gap:24px; height:56px; flex-wrap:wrap; }
|
||||
header .brand { font-weight:700; color:var(--fg); display:flex; gap:8px; align-items:center; }
|
||||
header .brand i { width:20px; height:20px; border-radius:5px; background:var(--accent); display:inline-block; }
|
||||
header nav { display:flex; gap:18px; flex-wrap:wrap; }
|
||||
header nav a { color:var(--muted); } header nav a.on { color:var(--fg); font-weight:600; }
|
||||
main { padding:28px 16px 64px; }
|
||||
h1 { font-size:1.9rem; margin:.2em 0 .4em; } h2 { margin-top:1.8em; border-bottom:1px solid var(--line); padding-bottom:.25em; }
|
||||
code { background:var(--card); border:1px solid var(--line); border-radius:5px; padding:.1em .35em; font-size:.92em; }
|
||||
pre { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:12px; overflow:auto; }
|
||||
pre code { border:0; padding:0; }
|
||||
table { border-collapse:collapse; width:100%; margin:1em 0; display:block; overflow-x:auto; }
|
||||
th, td { border:1px solid var(--line); padding:6px 10px; text-align:left; vertical-align:top; }
|
||||
th { background:var(--card); }
|
||||
td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:12px; margin:1.2em 0; }
|
||||
.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px; }
|
||||
.card b { display:block; font-size:1.6rem; } .card span { color:var(--muted); font-size:.9rem; }
|
||||
.good { color:var(--good); } .warn { color:var(--warn); } .bad { color:var(--bad); }
|
||||
.bar-cell { min-width:120px; } .meter { height:8px; background:var(--line); border-radius:4px; overflow:hidden; }
|
||||
.meter i { display:block; height:100%; }
|
||||
.layout { display:grid; grid-template-columns:220px 1fr; gap:32px; }
|
||||
.layout aside ol { padding-left:1.2em; margin:0; } .layout aside li { margin:.3em 0; }
|
||||
.layout aside a.on { font-weight:600; color:var(--fg); }
|
||||
@media (max-width:760px) { .layout { grid-template-columns:1fr; } }
|
||||
.buttons a { display:inline-block; margin:4px 8px 4px 0; padding:8px 14px; border-radius:8px;
|
||||
border:1px solid var(--line); background:var(--card); color:var(--fg); }
|
||||
.buttons a.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
|
||||
footer { color:var(--muted); font-size:.85rem; margin-top:48px; }
|
||||
"""
|
||||
|
||||
|
||||
def page(title: str, body: str, depth: int, current: str, sha: str) -> str:
|
||||
up = "../" * depth
|
||||
nav = "".join(
|
||||
f'<a href="{up}{path}"{" class=on" if path == current else ""}>{label}</a>'
|
||||
for path, label in SECTIONS)
|
||||
built = f"Built from {html.escape(sha[:10])}. " if sha else ""
|
||||
return f"""<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{html.escape(title)} - Alkane Toolkit</title>
|
||||
<link rel="stylesheet" href="{up}style.css"></head>
|
||||
<body><header><div class="bar"><a class="brand" href="{up}"><i></i>Alkane Toolkit</a>
|
||||
<nav>{nav}<a href="{RELEASES}">Downloads</a><a href="{REPO}">Source</a></nav></div></header>
|
||||
<main>{body}
|
||||
<footer>{built}Alkane Toolkit is MIT licensed.</footer></main></body></html>
|
||||
"""
|
||||
|
||||
|
||||
def write(out: Path, rel: str, text: str) -> None:
|
||||
path = out / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
# ---- manual -----------------------------------------------------------------
|
||||
|
||||
def chapters(manual: Path) -> list[tuple[str, str, str]]:
|
||||
"""(slug, title, markdown) for docs/manual/NN-slug.md, in file-name order."""
|
||||
out = []
|
||||
for path in sorted(manual.glob("[0-9][0-9]-*.md")):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
m = re.search(r"^# (.+)$", text, re.M)
|
||||
title = m.group(1).strip() if m else path.stem
|
||||
out.append((path.stem[3:], title, text))
|
||||
return out
|
||||
|
||||
|
||||
def build_manual(out: Path, manual: Path, sha: str) -> None:
|
||||
items = chapters(manual)
|
||||
if not items:
|
||||
raise SystemExit(f"no manual chapters in {manual}")
|
||||
|
||||
def toc(current: str) -> str:
|
||||
links = "".join(
|
||||
f'<li><a href="{slug}.html"{" class=on" if slug == current else ""}>'
|
||||
f"{html.escape(title)}</a></li>" for slug, title, _ in items)
|
||||
return f"<aside><ol>{links}</ol></aside>"
|
||||
|
||||
for slug, title, text in items:
|
||||
# Chapters link to each other as NN-name.md in the repo; on the site
|
||||
# they are name.html.
|
||||
text = re.sub(r"\]\((?:\./)?[0-9][0-9]-([a-z0-9-]+)\.md(#[^)]*)?\)", r"](\1.html\2)", text)
|
||||
body_html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"])
|
||||
write(out, f"manual/{slug}.html",
|
||||
page(title, f'<div class="layout">{toc(slug)}<article>{body_html}</article></div>',
|
||||
1, "manual/", sha))
|
||||
first = items[0][0]
|
||||
listing = "".join(f'<li><a href="{s}.html">{html.escape(t)}</a></li>' for s, t, _ in items)
|
||||
write(out, "manual/index.html",
|
||||
page("Manual", f"<h1>Manual</h1><p>Start with "
|
||||
f'<a href="{first}.html">{html.escape(items[0][1])}</a>.</p><ol>{listing}</ol>',
|
||||
1, "manual/", sha))
|
||||
|
||||
|
||||
# ---- quality dashboard ---------------------------------------------------------
|
||||
|
||||
def pct_class(pct: float | None) -> str:
|
||||
if pct is None:
|
||||
return ""
|
||||
return "good" if pct >= 80 else "warn" if pct >= 40 else "bad"
|
||||
|
||||
|
||||
def meter(pct: float) -> str:
|
||||
colour = {"good": "var(--good)", "warn": "var(--warn)", "bad": "var(--bad)"}[pct_class(pct)]
|
||||
return f'<div class="meter"><i style="width:{max(0.0, min(pct, 100.0)):.1f}%;background:{colour}"></i></div>'
|
||||
|
||||
|
||||
def build_quality(out: Path, quality: dict | None, sha: str) -> None:
|
||||
e = html.escape
|
||||
if not quality:
|
||||
write(out, "quality/index.html", page(
|
||||
"Code quality", "<h1>Code quality</h1><p>No measurement has been published yet; "
|
||||
"the next main build will fill this page.</p>", 1, "quality/", sha))
|
||||
return
|
||||
grade = str(quality.get("grade", "pending"))
|
||||
cov = quality.get("coverage_pct")
|
||||
bench_cov = quality.get("bench_coverage_pct")
|
||||
delta = quality.get("bench_delta_pct")
|
||||
|
||||
def card(value: str, label: str, cls: str = "") -> str:
|
||||
return f'<div class="card"><b class="{cls}">{value}</b><span>{label}</span></div>'
|
||||
|
||||
cards = "".join([
|
||||
card(e(grade), "Quality grade", {"A": "good", "B": "good", "C": "warn"}.get(grade, "bad")),
|
||||
card(e(str(quality.get("tests_passed", "-"))), "Tests passing", "good"),
|
||||
card(f"{cov:.1f}%" if cov is not None else "-", "Line coverage", pct_class(cov)),
|
||||
card(f"{bench_cov:.1f}%" if bench_cov is not None else "-", "Benchmark coverage", pct_class(bench_cov)),
|
||||
card(e(str(quality.get("clippy") or "-")), "Clippy (warnings are errors)",
|
||||
"good" if quality.get("clippy") == "clean" else "bad"),
|
||||
card(e(str(quality.get("rustfmt") or "-")), "rustfmt", "good" if quality.get("rustfmt") == "clean" else ""),
|
||||
card(f"{quality.get('loc', 0):,}", "Lines of Rust"),
|
||||
card(e(str(quality.get("dependencies", "-"))), "Crates in Cargo.lock"),
|
||||
card((f"{'+' if delta > 0 else ''}{delta:.1f}%" if delta is not None else "-"),
|
||||
"Benchmarks vs previous" + (" (same inputs)" if quality.get("bench_same_inputs") else ""),
|
||||
"" if delta is None else "good" if delta >= 2 else "" if delta > -2 else "warn"),
|
||||
])
|
||||
bands = ", ".join(f"{e(str(letter))} at {floor:.0f}% or more"
|
||||
for floor, letter in quality.get("grade_bands", []))
|
||||
grade_rule = (f"<p>The grade is F if Clippy or rustfmt fails on main. Otherwise it is the "
|
||||
f"line-coverage band: {bands}, and F below that. The coverage badge uses the "
|
||||
f"same bands for its colour, so the two never disagree.</p>")
|
||||
|
||||
crates = quality.get("coverage_by_crate", {})
|
||||
loc = quality.get("loc_by_crate", {})
|
||||
rows = []
|
||||
for name in sorted(set(crates) | set(loc)):
|
||||
c = crates.get(name)
|
||||
if c and c["lines"]:
|
||||
pct = 100.0 * (c["lines"] - c["missed"]) / c["lines"]
|
||||
cov_cells = (f'<td class="num {pct_class(pct)}">{pct:.1f}%</td>'
|
||||
f'<td class="bar-cell">{meter(pct)}</td>'
|
||||
f'<td class="num">{c["lines"] - c["missed"]:,} / {c["lines"]:,}</td>')
|
||||
else:
|
||||
cov_cells = '<td class="num">-</td><td></td><td class="num">-</td>'
|
||||
rows.append(f"<tr><td>{e(name)}</td>{cov_cells}<td class='num'>{loc.get(name, 0):,}</td></tr>")
|
||||
crate_table = ("<table><tr><th>Crate</th><th class=num>Line coverage</th><th></th>"
|
||||
"<th class=num>Covered lines</th><th class=num>Lines of Rust</th></tr>"
|
||||
+ "".join(rows) + "</table>")
|
||||
|
||||
files = sorted(quality.get("coverage_by_file", []),
|
||||
key=lambda r: (r["lines"] - r["missed"]) / r["lines"] if r["lines"] else 1)
|
||||
file_rows = "".join(
|
||||
f"<tr><td><code>{e(r['file'])}</code></td>"
|
||||
f"<td class='num {pct_class(100.0 * (r['lines'] - r['missed']) / r['lines'])}'>"
|
||||
f"{100.0 * (r['lines'] - r['missed']) / r['lines']:.1f}%</td>"
|
||||
f"<td class='num'>{r['missed']:,}</td><td class='num'>{r['lines']:,}</td></tr>"
|
||||
for r in files if r["lines"])
|
||||
file_table = ("<table><tr><th>File (least covered first)</th><th class=num>Coverage</th>"
|
||||
"<th class=num>Uncovered lines</th><th class=num>Lines</th></tr>"
|
||||
+ file_rows + "</table>") if file_rows else ""
|
||||
|
||||
measured = str(quality.get("sha", ""))[:10]
|
||||
of_build = f" (this page: <code>{e(measured)}</code>)" if measured else ""
|
||||
body = f"""<h1>Code quality</h1>
|
||||
<p>Measured by main CI on every build{of_build}:
|
||||
unit tests, line coverage (unit tests plus the headless UI self-test), Clippy with
|
||||
warnings as errors, and rustfmt. Windows builds run the same tests under Wine and
|
||||
on real Windows 11.</p>
|
||||
<div class="cards">{cards}</div>
|
||||
<h2 id="grade">How the grade is set</h2>{grade_rule}
|
||||
<h2 id="coverage">Coverage by crate</h2>{crate_table}
|
||||
<h2 id="files">Coverage by file</h2>{file_table}
|
||||
<p>The dependency count is every package in <code>Cargo.lock</code>, direct and
|
||||
transitive. Lines of Rust count every <code>.rs</code> line under <code>crates/</code>,
|
||||
tests included.</p>"""
|
||||
write(out, "quality/index.html", page("Code quality", body, 1, "quality/", sha))
|
||||
|
||||
|
||||
# ---- benchmarks + overview -------------------------------------------------------
|
||||
|
||||
def build_bench(out: Path, bench: Path | None, sha: str) -> None:
|
||||
if bench is None or not bench.is_file():
|
||||
write(out, "bench/index.html", page(
|
||||
"Benchmarks", "<h1>Benchmarks</h1><p>No benchmark history yet.</p>", 1, "bench/", sha))
|
||||
return
|
||||
rendered = bench.read_text(encoding="utf-8")
|
||||
# The history renderer emits a complete document; keep its body (and its
|
||||
# own styles) under the site's header.
|
||||
styles = "".join(re.findall(r"<style[^>]*>.*?</style>", rendered, re.S | re.I))
|
||||
m = re.search(r"<body[^>]*>(.*)</body>", rendered, re.S | re.I)
|
||||
inner = m.group(1) if m else rendered
|
||||
text = page("Benchmarks", inner, 1, "bench/", sha)
|
||||
write(out, "bench/index.html", text.replace("</head>", styles + "</head>", 1))
|
||||
|
||||
|
||||
def build_index(out: Path, quality: dict | None, sha: str) -> None:
|
||||
grade = html.escape(str((quality or {}).get("grade", "pending")))
|
||||
body = f"""<h1>Alkane Toolkit</h1>
|
||||
<p>Desktop discovery and monitoring for ASIC miners on your network: find every
|
||||
miner in your IP ranges, see hashrate, power, temperatures, fans and hashboard
|
||||
health at a glance, and run the controls each firmware supports.</p>
|
||||
<div class="buttons"><a class="primary" href="{RELEASES}">Download for Windows or Linux</a>
|
||||
<a href="manual/">Read the manual</a><a href="quality/">Code quality: {grade}</a>
|
||||
<a href="bench/">Benchmarks</a></div>
|
||||
<h2>Platforms</h2>
|
||||
<ul><li><b>Windows 10 and 11</b> (x86_64): one signed, self-contained <code>alkane-toolkit.exe</code>.</li>
|
||||
<li><b>Linux</b> (x86_64, GTK 3): one binary.</li></ul>
|
||||
<p>Every release is built, tested and signed by CI from the public source.</p>"""
|
||||
write(out, "index.html", page("Overview", body, 0, "", sha))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--manual", default="docs/manual")
|
||||
ap.add_argument("--quality", default=None)
|
||||
ap.add_argument("--bench", default=None)
|
||||
ap.add_argument("--sha", default="")
|
||||
args = ap.parse_args()
|
||||
out = Path(args.out)
|
||||
if out.exists():
|
||||
shutil.rmtree(out)
|
||||
out.mkdir(parents=True)
|
||||
quality = None
|
||||
if args.quality and Path(args.quality).is_file():
|
||||
quality = json.loads(Path(args.quality).read_text())
|
||||
if not isinstance(quality, dict) or quality.get("schema") != 1:
|
||||
raise SystemExit("unsupported quality.json")
|
||||
(out / "style.css").write_text(CSS.strip() + "\n", encoding="utf-8")
|
||||
build_index(out, quality, args.sha)
|
||||
build_manual(out, Path(args.manual), args.sha)
|
||||
build_quality(out, quality, args.sha)
|
||||
build_bench(out, Path(args.bench) if args.bench else None, args.sha)
|
||||
print(f"built {sum(1 for _ in out.rglob('*.html'))} pages in {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -22,24 +22,31 @@ def main() -> int:
|
||||
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(),
|
||||
(ROOT / ".gitea/workflows/pages.yml").read_text(),
|
||||
Loader=yaml.BaseLoader,
|
||||
)
|
||||
if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"]
|
||||
or pages["jobs"]["publish"].get("runs-on") != "alkane-pages"):
|
||||
print("Benchmark Pages must follow main CI on the Pages runner", file=sys.stderr)
|
||||
or pages["jobs"]["publish"].get("runs-on") != "alkane-verify"):
|
||||
print("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 any("ci/publish-bench-pages.py" in step.get("run", "")
|
||||
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-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
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
#!/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
|
||||
|
||||
prefix="${WX_PREFIX:?WX_PREFIX is required}"
|
||||
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/lib/libwx_gtk3u-3.3.a" ] &&
|
||||
[ -s "$prefix/$library" ] &&
|
||||
[ "$(cat "$prefix/.alkane-source-sha256" 2>/dev/null || true)" = "$expected" ]; then
|
||||
available=true
|
||||
fi
|
||||
|
||||
+13
-2
@@ -9,8 +9,9 @@ import sys
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
|
||||
FILES = ("bench-current.txt",)
|
||||
DIRECTORIES = ("target", "dist", "coverage", "bench-site", "site")
|
||||
FILES = ("bench-current.txt", "coverage-summary.txt", "quality.json")
|
||||
BADGE_FILES = ("bench-baseline.json", "bench-context.json", "quality.json")
|
||||
|
||||
|
||||
def cleanup() -> None:
|
||||
@@ -32,6 +33,16 @@ def cleanup() -> None:
|
||||
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__":
|
||||
|
||||
@@ -36,13 +36,17 @@ 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
|
||||
*) : ;; # docs, README, thirdparty/wxwidgets tree: no bump
|
||||
esac
|
||||
done <<< "$changed"
|
||||
|
||||
|
||||
@@ -3,13 +3,19 @@
|
||||
# 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}"
|
||||
mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows|pages}"
|
||||
case "$mode" in
|
||||
base) packages=(libssl-dev pkg-config ca-certificates) ;;
|
||||
ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;;
|
||||
ssh) packages=(openssh-client) ;;
|
||||
pages) packages=(python3-markdown) ;;
|
||||
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
|
||||
|
||||
|
||||
+21
-6
@@ -1,9 +1,24 @@
|
||||
#!/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
|
||||
|
||||
prefix="${WX_PREFIX:?WX_PREFIX is required}"
|
||||
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
|
||||
@@ -15,13 +30,13 @@ expected="$(awk '$1 == "sha256:" {print $2}' thirdparty/wxwidgets/VERSION)"
|
||||
}
|
||||
marker="$prefix/.alkane-source-sha256"
|
||||
if [ -e "$marker" ] && [ "$(cat "$marker")" != "$expected" ]; then
|
||||
python3 - "$prefix" <<'PY'
|
||||
python3 - "$prefix" "$allowed" <<'PY'
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
prefix = Path(sys.argv[1])
|
||||
allowed = Path('/root/.cache/wx-3.3.3-linux')
|
||||
allowed = Path(sys.argv[2])
|
||||
if prefix != allowed or prefix.is_symlink():
|
||||
raise SystemExit('refusing unsafe wxWidgets prefix reset')
|
||||
if prefix.is_dir():
|
||||
@@ -30,13 +45,13 @@ PY
|
||||
fi
|
||||
built=false
|
||||
if [ ! -x "$prefix/bin/wx-config" ] ||
|
||||
[ ! -s "$prefix/lib/libwx_gtk3u-3.3.a" ]; then
|
||||
bash scripts/build-wx-linux.sh
|
||||
[ ! -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/lib/libwx_gtk3u-3.3.a" ]
|
||||
[ -s "$prefix/$library" ]
|
||||
printf '%s\n' "$expected" > "$marker"
|
||||
if [ -n "${GITHUB_OUTPUT:-}" ]; then
|
||||
printf 'built=%s\n' "$built" >> "$GITHUB_OUTPUT"
|
||||
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Download the measured quality record (badges/quality.json on ci-badges).
|
||||
|
||||
fetch-quality.py OUT.json
|
||||
|
||||
Writes nothing (and exits 0) when main CI has not published one yet, so the
|
||||
Pages build shows a "not measured yet" dashboard instead of failing.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def main() -> None:
|
||||
out = Path(sys.argv[1])
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
url = f"{api}/repos/{repo}/contents/badges/quality.json?ref=ci-badges"
|
||||
request = Request(url, headers={"Authorization": f"token {os.environ['GITEA_TOKEN']}"})
|
||||
try:
|
||||
with urlopen(request, timeout=20) as response:
|
||||
content = base64.b64decode(json.load(response)["content"])
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
print("No quality record published yet")
|
||||
return
|
||||
raise
|
||||
if not isinstance(json.loads(content), dict):
|
||||
sys.exit("invalid quality record")
|
||||
out.write_bytes(content)
|
||||
print(f"Fetched quality record ({len(content)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+125
-14
@@ -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"/>
|
||||
@@ -131,10 +135,72 @@ def cov_color(pct: float) -> str:
|
||||
return "red"
|
||||
|
||||
|
||||
def quality_grade(clippy: str | None) -> str:
|
||||
if clippy is None:
|
||||
# Code-quality grade (shown on the badge and explained on the Pages quality
|
||||
# dashboard). Lint failures fail the grade outright; otherwise the grade is the
|
||||
# measured line-coverage band, using the same bands as the coverage badge
|
||||
# colour, so the two badges can never disagree.
|
||||
GRADE_BANDS = ((80.0, "A"), (60.0, "B"), (40.0, "C"), (20.0, "D"))
|
||||
GRADE_COLORS = {"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
||||
"D": "orange", "F": "red", "pending": "lightgrey"}
|
||||
|
||||
|
||||
def quality_grade(clippy: str | None, coverage: float | None = None) -> str:
|
||||
if clippy is None or (clippy == "clean" and coverage is None):
|
||||
return "pending"
|
||||
return "A" if clippy == "clean" else "F"
|
||||
if clippy != "clean":
|
||||
return "F"
|
||||
for floor, grade in GRADE_BANDS:
|
||||
if coverage >= floor:
|
||||
return grade
|
||||
return "F"
|
||||
|
||||
|
||||
def coverage_by_file(summary_path: str | None, root: str) -> list[dict]:
|
||||
"""Per-file line coverage from a `cargo llvm-cov --summary-only` table.
|
||||
|
||||
Columns: Filename, Regions, Missed Regions, Cover, Functions, Missed
|
||||
Functions, Executed, Lines, Missed Lines, Cover, ...
|
||||
"""
|
||||
if not summary_path:
|
||||
return []
|
||||
rows = []
|
||||
root_abs = os.path.abspath(root).rstrip("/") + "/"
|
||||
for line in Path(summary_path).read_text(errors="replace").splitlines():
|
||||
cols = line.split()
|
||||
if len(cols) < 10 or cols[0] in ("Filename", "TOTAL") or not cols[0].endswith(".rs"):
|
||||
continue
|
||||
try:
|
||||
lines, missed = int(cols[7]), int(cols[8])
|
||||
except ValueError:
|
||||
continue
|
||||
name = cols[0][len(root_abs):] if cols[0].startswith(root_abs) else cols[0]
|
||||
# llvm-cov drops the prefix every file shares, so when only workspace
|
||||
# crates are measured "crates/alkane-gui/src/x.rs" is printed as
|
||||
# "alkane-gui/src/x.rs". Put the prefix back.
|
||||
first = Path(name).parts[0] if Path(name).parts else ""
|
||||
if not name.startswith("crates/") and (Path(root) / "crates" / first).is_dir():
|
||||
name = f"crates/{name}"
|
||||
rows.append({"file": name, "lines": lines, "missed": missed})
|
||||
return rows
|
||||
|
||||
|
||||
def crate_of(path: str) -> str:
|
||||
parts = Path(path).parts
|
||||
if "crates" in parts and parts.index("crates") + 1 < len(parts):
|
||||
return parts[parts.index("crates") + 1]
|
||||
if "wx-rs-0.2.0-patched" in parts:
|
||||
return "wx-rs (bridge)"
|
||||
return "other"
|
||||
|
||||
|
||||
def loc_by_crate(root: str) -> dict[str, int]:
|
||||
out: dict[str, int] = {}
|
||||
crates = Path(root) / "crates"
|
||||
for path in sorted(crates.glob("*/**/*.rs")):
|
||||
crate = path.relative_to(crates).parts[0]
|
||||
with open(path, encoding="utf-8", errors="ignore") as fh:
|
||||
out[crate] = out.get(crate, 0) + sum(1 for _ in fh)
|
||||
return out
|
||||
|
||||
|
||||
def human(n: int) -> str:
|
||||
@@ -165,6 +231,9 @@ def main() -> int:
|
||||
# percentage string, or "NEW" when there is no baseline.
|
||||
ap.add_argument("--bench-delta", default=None)
|
||||
ap.add_argument("--clippy", choices=("clean", "failed"))
|
||||
# The full `cargo llvm-cov --summary-only` table, for the per-crate and
|
||||
# per-file breakdown in quality.json (the Pages quality dashboard).
|
||||
ap.add_argument("--coverage-summary", default=None)
|
||||
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):
|
||||
@@ -172,10 +241,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)
|
||||
@@ -185,10 +254,9 @@ 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)
|
||||
write("quality", "code quality", grade,
|
||||
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
||||
"D": "orange", "F": "red", "pending": "lightgrey"}[grade])
|
||||
grade = quality_grade(args.clippy, args.coverage)
|
||||
write("quality", "code quality", grade, GRADE_COLORS[grade],
|
||||
f"code quality: {grade} (Clippy, rustfmt and line coverage)")
|
||||
if args.tests is not None:
|
||||
write("tests", "tests", f"{args.tests} passing", "brightgreen")
|
||||
if args.coverage is not None:
|
||||
@@ -196,6 +264,14 @@ 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")
|
||||
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
|
||||
@@ -206,12 +282,47 @@ def main() -> int:
|
||||
delta = None
|
||||
if delta is not None:
|
||||
# Positive = faster than the previous release.
|
||||
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
|
||||
write("bench", "bench", msg, bench_color(delta))
|
||||
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:
|
||||
write("bench", "bench", args.bench, "blue")
|
||||
|
||||
# Everything above, plus the per-crate breakdowns, for the Pages quality
|
||||
# dashboard (ci/build-pages.py).
|
||||
files = coverage_by_file(args.coverage_summary, args.root)
|
||||
crates: dict[str, dict] = {}
|
||||
for row in files:
|
||||
c = crates.setdefault(crate_of(row["file"]), {"lines": 0, "missed": 0})
|
||||
c["lines"] += row["lines"]
|
||||
c["missed"] += row["missed"]
|
||||
quality = {
|
||||
"schema": 1,
|
||||
"sha": os.environ.get("GITHUB_SHA", ""),
|
||||
"grade": grade,
|
||||
"grade_bands": [[floor, letter] for floor, letter in GRADE_BANDS],
|
||||
"clippy": args.clippy,
|
||||
"rustfmt": "clean" if args.clippy is not None else None,
|
||||
"tests_passed": args.tests,
|
||||
"coverage_pct": args.coverage,
|
||||
"bench_coverage_pct": args.bench_coverage,
|
||||
"bench_delta_pct": delta,
|
||||
"bench_same_inputs": same_inputs,
|
||||
"loc": loc,
|
||||
"loc_by_crate": loc_by_crate(args.root),
|
||||
"dependencies": deps,
|
||||
"license": lic,
|
||||
"coverage_by_crate": crates,
|
||||
"coverage_by_file": files,
|
||||
}
|
||||
path = os.path.join(args.root, args.out, "quality.json")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(quality, fh, indent=1, sort_keys=True)
|
||||
print(f"wrote {path}")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
Executable
+39
@@ -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"
|
||||
@@ -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 Energy Solutions Inc. (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()
|
||||
+14
-2
@@ -22,6 +22,15 @@ def documentation_only(paths: list[str]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
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()
|
||||
@@ -95,12 +104,15 @@ def main() -> None:
|
||||
try:
|
||||
paths = changed_paths()
|
||||
docs = documentation_only(paths)
|
||||
packages = headless_packages(paths) if not docs else []
|
||||
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 "headless" if packages else "full"
|
||||
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)
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
#!/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()
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish measured toolkit badges to the private Gitea badge branch."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
@@ -22,7 +23,14 @@ def main() -> None:
|
||||
raise ValueError(f"invalid {name} SVG")
|
||||
publish_file(api, repo, f"badges/{name}.svg", data, token,
|
||||
f"Update measured {name} badge")
|
||||
print(f"Published {len(NAMES)} measured badge SVGs")
|
||||
# The full measurement record behind the badges, read by the Pages
|
||||
# quality dashboard (ci/build-pages.py).
|
||||
data = (ROOT / "badges" / "quality.json").read_bytes()
|
||||
if not isinstance(json.loads(data), dict):
|
||||
raise ValueError("invalid quality.json")
|
||||
publish_file(api, repo, "badges/quality.json", data, token,
|
||||
"Update measured quality record", max_bytes=262_144)
|
||||
print(f"Published {len(NAMES)} measured badge SVGs and quality.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish the built Pages site to this repository's gh-pages branch.
|
||||
|
||||
publish-pages.py SITE_DIR
|
||||
|
||||
Served at https://blueflare.gitea.bluefla.re/alkane-toolkit/ by the Pages
|
||||
server, which serves the gh-pages branch of public repositories. Each publish
|
||||
is one orphan commit (force-pushed), so the branch never accumulates history.
|
||||
Only main may publish, and a run for a superseded main commit skips.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
BRANCH = "gh-pages"
|
||||
MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
|
||||
def current_main_sha(api: str, repo: str, token: str) -> str:
|
||||
request = Request(f"{api}/repos/{repo}/branches/main",
|
||||
headers={"Authorization": f"token {token}"})
|
||||
with urlopen(request, timeout=20) as response:
|
||||
return json.load(response)["commit"]["id"]
|
||||
|
||||
|
||||
def git(*args: str, cwd: Path, env: dict | None = None) -> None:
|
||||
subprocess.run(("git", *args), cwd=cwd, env=env, check=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit(__doc__)
|
||||
site = Path(sys.argv[1])
|
||||
if not (site / "index.html").is_file():
|
||||
sys.exit(f"{site} has no index.html")
|
||||
size = sum(p.stat().st_size for p in site.rglob("*") if p.is_file())
|
||||
if size > MAX_BYTES:
|
||||
sys.exit(f"site is {size} bytes, over the {MAX_BYTES} byte limit")
|
||||
for path in site.rglob("*"):
|
||||
if path.is_file() and path.suffix not in {".html", ".css", ".svg", ".png", ".json"}:
|
||||
sys.exit(f"unexpected file type on the site: {path}")
|
||||
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
sha = os.environ["GITHUB_SHA"]
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
if os.environ.get("GITHUB_REF") != "refs/heads/main":
|
||||
sys.exit("Pages publication requires main")
|
||||
if current_main_sha(api, repo, token) != sha:
|
||||
print("Skipping Pages for a superseded main commit")
|
||||
return
|
||||
|
||||
server = api.removesuffix("/api/v1")
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
|
||||
work = Path(directory)
|
||||
shutil.copytree(site, work, dirs_exist_ok=True)
|
||||
env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
|
||||
git("init", "-q", "-b", BRANCH, cwd=work)
|
||||
git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re",
|
||||
"add", "-A", cwd=work)
|
||||
git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re",
|
||||
"commit", "-q", "-m", f"Publish site for {sha[:10]} [skip ci]", cwd=work)
|
||||
# The token is read from the environment by the credential helper at
|
||||
# push time; it never appears on a command line or in the remote URL.
|
||||
helper = '!f() { echo username=alkane-ci; echo "password=$GITEA_TOKEN"; }; f'
|
||||
git("-c", f"credential.helper={helper}", "push", "-q", "--force",
|
||||
f"{server}/{repo}.git", f"HEAD:refs/heads/{BRANCH}", cwd=work, env=env)
|
||||
print(f"Published Pages for {sha[:10]} to {BRANCH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1
-1
@@ -1 +1 @@
|
||||
gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||
gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
|
||||
Executable
+88
@@ -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
|
||||
@@ -5,6 +5,7 @@
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@@ -50,6 +51,47 @@ class BenchBadgeTests(unittest.TestCase):
|
||||
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
|
||||
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
|
||||
|
||||
def test_quality_grade_follows_lint_and_coverage(self):
|
||||
# A lint failure fails the grade; otherwise it is the coverage band,
|
||||
# with the same floors as the coverage badge colour.
|
||||
self.assertEqual(gen_badges.quality_grade("failed", 95.0), "F")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 85.0), "A")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 65.6), "B")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 48.0), "C")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 25.0), "D")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 5.0), "F")
|
||||
self.assertEqual(gen_badges.quality_grade("clean"), "pending")
|
||||
self.assertEqual(gen_badges.quality_grade(None, 90.0), "pending")
|
||||
for pct in (85.0, 65.6, 48.0, 25.0):
|
||||
grade = gen_badges.quality_grade("clean", pct)
|
||||
self.assertEqual(gen_badges.GRADE_COLORS[grade], gen_badges.cov_color(pct))
|
||||
|
||||
def test_coverage_table_is_split_by_crate(self):
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-cov-") as directory:
|
||||
summary = Path(directory) / "summary.txt"
|
||||
summary.write_text(
|
||||
"Filename Regions Missed Regions Cover Functions Missed Functions "
|
||||
"Executed Lines Missed Lines Cover\n"
|
||||
"crates/alkane-gui/src/ui.rs 10 5 50.00% 4 2 50.00% 100 60 40.00%\n"
|
||||
"crates/alkane-core/src/platform.rs 4 0 100.00% 2 0 100.00% 50 5 90.00%\n"
|
||||
"TOTAL 14 5 64.29% 6 2 66.67% 150 65 56.67%\n")
|
||||
rows = gen_badges.coverage_by_file(str(summary), directory)
|
||||
self.assertEqual([r["file"] for r in rows],
|
||||
["crates/alkane-gui/src/ui.rs", "crates/alkane-core/src/platform.rs"])
|
||||
self.assertEqual(rows[0]["missed"], 60)
|
||||
self.assertEqual(gen_badges.crate_of(rows[1]["file"]), "alkane-core")
|
||||
|
||||
def test_coverage_table_restores_the_stripped_crates_prefix(self):
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-cov-") as directory:
|
||||
(Path(directory) / "crates" / "alkane-cli").mkdir(parents=True)
|
||||
summary = Path(directory) / "summary.txt"
|
||||
summary.write_text(
|
||||
"alkane-cli/src/main.rs 4 4 0.00% 1 1 0.00% 23 23 0.00%\n")
|
||||
rows = gen_badges.coverage_by_file(str(summary), directory)
|
||||
self.assertEqual(rows[0], {"file": "crates/alkane-cli/src/main.rs",
|
||||
"lines": 23, "missed": 23})
|
||||
self.assertEqual(gen_badges.crate_of(rows[0]["file"]), "alkane-cli")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -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("<script>", page)
|
||||
self.assertNotIn("<script>", page)
|
||||
self.assertIn("10.000", page)
|
||||
self.assertIn("same inputs", page)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -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
|
||||
|
||||
+107
-1
@@ -4,13 +4,16 @@
|
||||
|
||||
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)
|
||||
@@ -24,8 +27,111 @@ def git(directory: Path, *args: str) -> str:
|
||||
).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
|
||||
@@ -105,7 +211,7 @@ def main() -> None:
|
||||
pr_surface.ROOT = saved_root
|
||||
os.environ.clear()
|
||||
os.environ.update(saved_env)
|
||||
print("Toolkit PR change surface: documentation, headless, and fallback PASS")
|
||||
print("Toolkit PR change surface: documentation, workflow, headless, and fallback PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -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
|
||||
+16
-1
@@ -1,8 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-License-Identifier: MIT
|
||||
# Key the native wxWidgets prefix to its tracked source and build toolchain.
|
||||
# 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
|
||||
|
||||
@@ -81,7 +81,7 @@ impl SshTarget {
|
||||
}
|
||||
|
||||
fn command(&self, probe: Probe) -> Command {
|
||||
let mut command = Command::new("ssh");
|
||||
let mut command = alkane_core::platform::quiet_command("ssh");
|
||||
command
|
||||
.arg("-F")
|
||||
.arg("none")
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
// alkane-core
|
||||
|
||||
pub mod platform;
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
|
||||
@@ -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<()> {
|
||||
@@ -80,13 +69,26 @@ pub fn load_ssh_credentials() -> Option<(String, String)> {
|
||||
load_creds_file(SSH_CREDENTIALS_FILE)
|
||||
}
|
||||
|
||||
/// Save the SSH username/password (0600). Retained for a future SSH-login dialog
|
||||
/// now that the SSH PIC probe that used to save it has been removed (round 14 #5).
|
||||
#[allow(dead_code)]
|
||||
/// Save the SSH username/password (0600), from the Credentials dialog.
|
||||
pub fn save_ssh_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
||||
save_creds_file(SSH_CREDENTIALS_FILE, user, pass)
|
||||
}
|
||||
|
||||
/// Remove the saved SSH login, if any. Not an error if none was saved.
|
||||
pub fn clear_ssh_credentials() -> std::io::Result<()> {
|
||||
clear_creds_file(SSH_CREDENTIALS_FILE)
|
||||
}
|
||||
|
||||
/// The SSH username to use: the saved one, or `root` (the control-board login
|
||||
/// on every firmware the restore flow drives over SSH) when none was entered.
|
||||
pub fn ssh_user_or_default(user: &str) -> String {
|
||||
if user.trim().is_empty() {
|
||||
"root".to_string()
|
||||
} else {
|
||||
user.trim().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the saved web/API credentials, if any. Not an error if none were saved.
|
||||
pub fn clear_credentials() -> std::io::Result<()> {
|
||||
match clear_creds_file(CREDENTIALS_FILE) {
|
||||
@@ -164,20 +166,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 +191,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 +214,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 +264,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()).
|
||||
@@ -262,38 +285,74 @@ mod tests {
|
||||
assert_eq!(load_credentials(), None, "cleared -> None");
|
||||
clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error
|
||||
|
||||
// SSH login: separate file, same 0600 rule, clear is idempotent.
|
||||
assert_eq!(load_ssh_credentials(), None, "no SSH file -> None");
|
||||
save_ssh_credentials("root", "ssh-pass").unwrap();
|
||||
assert_owner_only(
|
||||
&config_path(SSH_CREDENTIALS_FILE),
|
||||
"SSH creds file must be 0600",
|
||||
);
|
||||
assert_eq!(
|
||||
load_ssh_credentials(),
|
||||
Some(("root".to_string(), "ssh-pass".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
load_credentials(),
|
||||
None,
|
||||
"SSH save leaves the web login alone"
|
||||
);
|
||||
clear_ssh_credentials().unwrap();
|
||||
assert_eq!(load_ssh_credentials(), None, "cleared -> None");
|
||||
clear_ssh_credentials().unwrap();
|
||||
assert_eq!(ssh_user_or_default(""), "root");
|
||||
assert_eq!(ssh_user_or_default(" admin "), "admin");
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Bench-fleet fixtures: the expected hardware output of the 9 boards on
|
||||
//! 10.255.1.0/24 (see ../../../HANDOFF.md section 7 and the parent project's
|
||||
//! [removed]). These are the reference values the workflow tests compare
|
||||
//! Fixture fleet: the expected hardware output of nine representative miners
|
||||
//! (one per control-board family / firmware). These are the reference values
|
||||
//! the workflow tests compare
|
||||
//! the application's actual output against, and the rows the offline
|
||||
//! `ALKANE_FAKE_SCAN` demo mode renders. Only miners that respond become rows,
|
||||
//! so there is no synthetic "offline" fixture.
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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..])
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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() {}
|
||||
|
||||
+684
-175
File diff suppressed because it is too large
Load Diff
@@ -234,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.
|
||||
@@ -365,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).
|
||||
@@ -431,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"), "");
|
||||
}
|
||||
|
||||
@@ -455,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()))
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 (Credentials > SSH)".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);
|
||||
|
||||
+811
-463
File diff suppressed because it is too large
Load Diff
+1031
-295
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 Energy Solutions Inc."
|
||||
VALUE "FileDescription", "Alkane Toolkit"
|
||||
VALUE "FileVersion", ALKANE_VER_STR
|
||||
VALUE "InternalName", "alkane-toolkit"
|
||||
VALUE "LegalCopyright", "Copyright (c) 2026 BlueFlare Energy Solutions Inc. (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
|
||||
Executable
+21
@@ -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"
|
||||
@@ -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).
|
||||
@@ -0,0 +1,55 @@
|
||||
# Getting started
|
||||
|
||||
Alkane Toolkit finds the ASIC miners on your network and shows them in one
|
||||
table: model, firmware, hashrate, power, temperatures, fans and the health of
|
||||
every hashboard. From the same table you can run the controls each miner's
|
||||
firmware supports, such as pausing, restarting or changing pools.
|
||||
|
||||
## Download
|
||||
|
||||
Get the latest release from the
|
||||
[downloads page](https://gitea.bluefla.re/blueflare/alkane-toolkit/releases).
|
||||
|
||||
| Platform | File | Notes |
|
||||
|---|---|---|
|
||||
| Windows 10 and 11 (x86_64) | `alkane-toolkit-vX.Y.Z-windows-x86_64.zip` | One signed `alkane-toolkit.exe`; nothing to install |
|
||||
| Linux (x86_64) | `alkane-toolkit-vX.Y.Z-linux-x86_64.tar.gz` | One binary; needs GTK 3 (`sudo apt install libgtk-3-0`) |
|
||||
|
||||
### Windows
|
||||
|
||||
1. Download the zip, right-click it, choose **Properties**, tick **Unblock** if
|
||||
it is shown, then extract it.
|
||||
2. Run `alkane-toolkit.exe`. Windows shows *BlueFlare Energy Solutions Inc.* as
|
||||
the verified publisher. To check the signature yourself, right-click the exe,
|
||||
choose **Properties** and open **Digital Signatures**.
|
||||
|
||||
### Linux
|
||||
|
||||
```sh
|
||||
tar xzf alkane-toolkit-vX.Y.Z-linux-x86_64.tar.gz
|
||||
./alkane-toolkit-vX.Y.Z-linux-x86_64/alkane-toolkit
|
||||
```
|
||||
|
||||
## First run
|
||||
|
||||
The toolkit starts a scan as soon as it opens. Set your own ranges first with
|
||||
**Scan ranges** (see [Scanning](02-scanning.md)); until you do, it scans
|
||||
192.168.1.0/24, the usual router subnet.
|
||||
|
||||
To look around without touching any miner, start it in demo mode. It shows a
|
||||
built-in sample fleet and simulates every action:
|
||||
|
||||
| Platform | Command |
|
||||
|---|---|
|
||||
| Windows (Command Prompt) | `set ALKANE_FAKE_SCAN=1 && alkane-toolkit.exe` |
|
||||
| Linux | `ALKANE_FAKE_SCAN=1 ./alkane-toolkit` |
|
||||
|
||||
## Where settings are kept
|
||||
|
||||
| Platform | Folder |
|
||||
|---|---|
|
||||
| Windows | `%APPDATA%\alkane-toolkit` |
|
||||
| Linux | `~/.config/alkane-toolkit` |
|
||||
|
||||
See [Settings and credentials](06-settings.md) for the files in that folder.
|
||||
Deleting the folder resets the toolkit to its defaults.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Scanning
|
||||
|
||||
Discovery is read-only: a scan asks each address what it is and records what
|
||||
it reports. It never changes a miner.
|
||||
|
||||
## Scan ranges
|
||||
|
||||
Click **Scan ranges** to edit the addresses to scan. Put one entry per line;
|
||||
blank lines and lines starting with `#` are ignored.
|
||||
|
||||
| Form | Example | Scans |
|
||||
|---|---|---|
|
||||
| Single address | `192.168.1.50` | that address |
|
||||
| CIDR block | `192.168.1.0/24` | the whole block |
|
||||
| Full range | `192.168.1.10-192.168.2.40` | every address between the two, inclusive |
|
||||
| Short range | `192.168.1.10-90` | `.10` to `.90` within the same /24 |
|
||||
| Per-octet ranges | `10.1-4.0-1.1-255` | every combination (10.1.0.1 ... 10.4.1.255) |
|
||||
|
||||
Commas or spaces between several entries on one line are not accepted; use one
|
||||
line each. Duplicates are removed automatically. One line, and all lines
|
||||
together, may cover at most 1,000,000 addresses.
|
||||
|
||||
**Apply** saves the ranges and starts a scan. A mistake keeps the dialog open
|
||||
and the status bar explains it, for example `invalid range: bad octet range`.
|
||||
|
||||
The same dialog has three numbers:
|
||||
|
||||
| Field | Meaning | Default |
|
||||
|---|---|---|
|
||||
| Rescan (s) | seconds between automatic rescans; `0` turns auto-rescan off | 300 |
|
||||
| Timeout (s) | how long to wait for one miner (scans, refreshes, actions and log fetches) | 10 |
|
||||
| Concurrency | how many addresses are probed at once (8 to 256); higher is faster but slow miners may report fewer values | 128 |
|
||||
|
||||
When the ranges change, miners outside the new ranges leave the table at the
|
||||
next scan.
|
||||
|
||||
## Running, pausing and stopping
|
||||
|
||||
The three buttons next to **Scan ranges** control scanning:
|
||||
|
||||
- **Play** (green) turns auto-rescan on and starts a scan now if none is running.
|
||||
- **Pause** (amber) turns auto-rescan off and lets the current scan finish.
|
||||
- **Stop** (red) turns auto-rescan off and cancels the current scan.
|
||||
|
||||
While a scan runs, a progress bar spans the top of the table and the status bar
|
||||
shows progress such as `1935/4590 - scanning 192.168.1.86 (92 found)`. Afterwards
|
||||
it shows the count and the time to the next scan, for example
|
||||
`245 miners - next scan in 4m 12s`.
|
||||
|
||||
Actions that change miners wait for the scan to finish; see
|
||||
[Actions](05-actions.md).
|
||||
@@ -0,0 +1,80 @@
|
||||
# The table and header
|
||||
|
||||
## Summary cards
|
||||
|
||||
The cards at the top count the miners **currently shown** (after any filter).
|
||||
Each miner is in exactly one status: slow, paused, hashing or not hashing.
|
||||
|
||||
| Card | Counts | Click |
|
||||
|---|---|---|
|
||||
| Total | rows in the view | - |
|
||||
| Hashing (green rabbit) | mining at 80% of expected hashrate or more | show only these; click again to clear |
|
||||
| Slow (amber turtle) | mining below 80% of expected hashrate | show only these |
|
||||
| Not hashing (red glass) | answering but not mining | show only these |
|
||||
| Paused (blue otter) | stopped on purpose (paused, stopped, suspended) | show only these |
|
||||
| SHA-256 Hashrate | total hashrate, per algorithm | switch algorithm when the fleet runs more than one |
|
||||
| Est. power | total reported power draw | - |
|
||||
|
||||
On a narrow window the hashrate and power cards are hidden.
|
||||
|
||||
## Columns
|
||||
|
||||
IP is always the first column. The default view shows Model, Health,
|
||||
Hashrate, Power, Chip temp, Firmware, CPU, Access and Light. More than seventy
|
||||
other columns are available, grouped as Identity, Firmware and board, Health
|
||||
and status, Performance, Temperature, Cooling, Hardware and Pools.
|
||||
|
||||
- **Columns** opens a checklist: tick to show, drag to reorder, or sort the list
|
||||
alphabetically or by category. *Hide columns with no scanned values* hides
|
||||
columns that are empty for every miner (it resets when the app restarts).
|
||||
- Drag a column header to move it.
|
||||
- Right-click a header to sort by it, auto-size one or all columns, hide it, or
|
||||
open the column chooser.
|
||||
|
||||
Some values worth knowing:
|
||||
|
||||
| Column | Shows |
|
||||
|---|---|
|
||||
| Hashrate | actual/expected, for example `95.0T/96.0T`; the actual part is red at 50% of expected or less, amber around 75%, green at 100% |
|
||||
| Chip temp | hottest chip on each hashboard, for example `77 / 64 / 74`; blue when cool, red at 90 C and above |
|
||||
| Firmware | the firmware family, coloured (Braiins purple, LuxOS gold, VNish green, ePIC light blue, Hiveon orange, Bixbit pink); stock firmware uses the normal text colour |
|
||||
| Pool account / Worker | the pool user split at the first dot |
|
||||
| Board HR / V / freq | per-hashboard hashrate, voltage and frequency |
|
||||
|
||||
A blank cell means the miner did not report that value.
|
||||
|
||||
## Sorting
|
||||
|
||||
Click a header to sort ascending, again for descending, again to clear.
|
||||
|
||||
- **Hashrate** also sorts by *relative* hashrate (actual as a share of
|
||||
expected), shown as `%^` and `%v` in the header.
|
||||
- **Health** sorts by overall health, then by power (`Pwr`), fans (`Fan`) and
|
||||
hashboards (`Brd`). Ascending puts the most broken miners first.
|
||||
|
||||
## Selecting miners
|
||||
|
||||
Click a row to select it; Ctrl-click and Shift-click add to the selection, and
|
||||
you can drag across rows to select a block. The selection follows miners by IP,
|
||||
so it survives rescans. Double-click a row (or press Enter) to open the miner's
|
||||
web page in your browser. Right-click the selection for [actions](05-actions.md).
|
||||
|
||||
## Filters and presets
|
||||
|
||||
**Filter** keeps only the rows that match. Pick a column, then:
|
||||
|
||||
- for numbers: between, =, !=, >, >=, < or <= (blank cells never match);
|
||||
- for text: *is any of* (tick values; `(blank)` matches empty cells), contains,
|
||||
does not contain, begins with, ends with or equals (case does not matter).
|
||||
|
||||
Filters on different columns must all match. **Reset** clears them. Clicking a
|
||||
status card is a quick filter of its own.
|
||||
|
||||
**Presets** saves and loads whole views: column order and visibility, sort and
|
||||
filters. *Default* is built in and cannot be deleted; saving under an existing
|
||||
name replaces it.
|
||||
|
||||
## Zoom and theme
|
||||
|
||||
The slider in the bottom-right corner zooms the table: text, icons and column
|
||||
widths scale together. The window follows the system light or dark theme.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Health, access and light
|
||||
|
||||
## The Health column
|
||||
|
||||
Each miner gets a row of icons, always in the same order, so problems line up
|
||||
across the table:
|
||||
|
||||
1. **Bolt**: the power supply
|
||||
2. **Brain**: the control board
|
||||
3. **Fan**: one icon per fan
|
||||
4. **Chip**: one icon per hashboard
|
||||
|
||||
Hover over any icon to see its details: PSU voltage and current, the fan speed,
|
||||
or a hashboard's actual and expected hashrate, frequency and voltage, and any
|
||||
fault message with its code.
|
||||
|
||||
| Colour | Meaning |
|
||||
|---|---|
|
||||
| Green | healthy |
|
||||
| Amber | working but below par (a slow board, a fan well below the others, a PSU fault while still mining) |
|
||||
| Red | detected but down (a faulted board, a stopped fan, a PSU that is not delivering) |
|
||||
| Grey | expected but not detected or not reachable |
|
||||
| Blue | the miner is paused, so its boards and stopped fans are idle on purpose |
|
||||
|
||||
How each part is judged:
|
||||
|
||||
- **Power** is green when the miner draws power, its PSU fan turns or it is
|
||||
mining; a reported PSU fault makes it amber (still mining) or red.
|
||||
- **Control board** is red for a control-board fault and amber for a
|
||||
miner-wide warning such as a high ambient temperature.
|
||||
- **Fans** are red at 0 rpm and amber below half the speed of the fastest fan.
|
||||
- **Hashboards** follow the status the miner reports for each board. When the
|
||||
firmware names the failing boards, only those turn red. A board the miner
|
||||
cannot see is grey.
|
||||
|
||||
While an action runs on a miner, its Health cell shows progress such as
|
||||
`restarting...` or `refreshing...`.
|
||||
|
||||
## Access
|
||||
|
||||
The padlock shows whether the toolkit can change the miner:
|
||||
|
||||
- **green, open**: changes are possible with the saved credentials;
|
||||
- **red, closed**: view only;
|
||||
- **blank**: not known yet.
|
||||
|
||||
After a scan the padlock is an estimate from what the firmware offers. Use
|
||||
**Check access (auth)** in the right-click menu for a real, read-only login
|
||||
test.
|
||||
|
||||
## Light
|
||||
|
||||
A flashing green-over-red dot means the miner's locate light is on. Turn it on
|
||||
or off with **Flash lights** / **Stop flashing lights**.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Actions
|
||||
|
||||
Right-click one or more selected miners for the actions menu. With several
|
||||
miners selected, labels show the count, for example *Restart (12)*. An action
|
||||
appears only when **every** selected miner's firmware supports it, so the menu
|
||||
changes with the selection.
|
||||
|
||||
| Action | What it does | Changes the miner |
|
||||
|---|---|---|
|
||||
| Open in browser | opens each miner's web page | no |
|
||||
| Refresh | re-reads just these miners | no |
|
||||
| Check access (auth) | tests whether the saved login is accepted | no |
|
||||
| View log (API)... | shows the first selected miner's log (WhatsMiner: its active fault codes) | no |
|
||||
| Restore to stock firmware... | removes aftermarket firmware; see [Restore to stock](07-restore.md) | yes, reboots |
|
||||
| Flash lights / Stop flashing lights | locate light on or off | yes, harmless |
|
||||
| Pause mining / Resume mining | stop or start hashing | yes |
|
||||
| Set tuning %... | tuning level, 0 to 100 | yes |
|
||||
| Set power target... | power target in watts; the prompt shows the current value and the allowed range | yes |
|
||||
| Set hashrate target... | hashrate target in TH/s, for firmware that tunes by hashrate | yes |
|
||||
| Set profile... | pick a firmware profile or preset (only profiles every selected miner has are listed) | yes |
|
||||
| Restart | reboot | yes |
|
||||
| Configure pools... | set up to three pools | yes |
|
||||
| Set timezone... | IANA time zone, for example `America/Edmonton` | yes |
|
||||
| Change password... | new web/API password | yes |
|
||||
| Factory reset... | wipes pools, tuning and network settings and reboots; the miner may come back on a new DHCP address | yes, destructive |
|
||||
|
||||
## Safety
|
||||
|
||||
- Pause, Resume, Restart and Factory reset ask for confirmation. Value prompts
|
||||
(tuning, targets, timezone, password) apply when you confirm the value.
|
||||
- Actions that change miners do not start while a scan is running, including an
|
||||
automatic rescan. Wait for it to finish or press **Pause**. Scans in turn wait
|
||||
for running actions.
|
||||
- Each changed miner is re-read automatically when the action finishes. Results
|
||||
and failures appear in the bottom-right corner of the status bar and in
|
||||
**Settings > Logs**.
|
||||
- If **Change password** succeeds on every selected miner, the saved global
|
||||
login is updated to the new password. If only some succeed, the saved login
|
||||
is left alone and the log says so.
|
||||
|
||||
## Configuring pools
|
||||
|
||||
The pool dialog has three rows: Address, Account, Worker and Password. A row is
|
||||
used only when it has an address and an account. A blank password becomes `x`.
|
||||
The miner's username becomes `account.worker`.
|
||||
|
||||
Each field has a **+** menu with common pool addresses and the values you saved
|
||||
before (**Add new...** edits that list). Worker names can use placeholders that
|
||||
are filled in per miner:
|
||||
|
||||
| Placeholder | Becomes |
|
||||
|---|---|
|
||||
| `{ip1}` to `{ip4}` | one octet of the miner's IP |
|
||||
| `{serial}`, `{mac}` | serial number; MAC without colons |
|
||||
| `{hostname}` | the miner's hostname |
|
||||
| `{brand}`, `{model}`, `{submodel}` | make and model |
|
||||
| `{firmware}`, `{cpu}`, `{cb}` | firmware family, control-board CPU and board |
|
||||
| `{nameplate-hr}` | the model's rated hashrate |
|
||||
|
||||
For example, `rack3-{ip3}-{ip4}` gives `rack3-1-50` for `10.0.1.50`.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Settings and credentials
|
||||
|
||||
**Settings** opens a menu with Credentials, Language and Logs.
|
||||
|
||||
## Credentials
|
||||
|
||||
Miners need a login for anything beyond basic discovery: for some details, and
|
||||
for every action. The Credentials dialog has three parts:
|
||||
|
||||
- **All firmwares** at the top: one username and password tried on every miner.
|
||||
The saved password is never shown; leave the field blank to keep it. Blank
|
||||
username and password clear it.
|
||||
- **SSH (restore)**: the control-board SSH login used to restore Braiins OS to
|
||||
stock (see [SSH login](#ssh-login)).
|
||||
- **One row per firmware**, pre-filled with that firmware's factory default.
|
||||
Change a row to override the login for that firmware only.
|
||||
|
||||
The toolkit tries, in order, the firmware's own row, then the global login,
|
||||
then the firmware's built-in default.
|
||||
|
||||
| Firmware | Factory default (user / password) |
|
||||
|---|---|
|
||||
| AntMiner Stock | root / root |
|
||||
| WhatsMiner Stock | admin / admin |
|
||||
| Braiins | root / root |
|
||||
| VNish | (none) / admin |
|
||||
| LuxOS | root / root |
|
||||
| UMC OS | (none) / letmein |
|
||||
| Marathon | root / root |
|
||||
| VolcMiner Stock | root / ltc@dog |
|
||||
| Elphapex Stock | root / root |
|
||||
| FutureBit Stock | futurebit / futurebit123 |
|
||||
| SealMiner Stock | seal / seal |
|
||||
| Auradine Stock | admin / admin |
|
||||
|
||||
**Reset to defaults** clears every override, the global login and the SSH
|
||||
login at once.
|
||||
|
||||
Logins are stored as plain text in the settings folder, readable only by your
|
||||
user account (Linux file mode 0600; on Windows, your profile folder's
|
||||
permissions).
|
||||
|
||||
### SSH login
|
||||
|
||||
Restoring Braiins to stock runs a command over SSH, using the system `ssh`
|
||||
client (built into Windows 10/11). Set its login in the **SSH (restore)** row
|
||||
of the Credentials dialog. The username defaults to `root`. As with the global
|
||||
login, the saved password is never shown and a blank password keeps it.
|
||||
|
||||
## Language
|
||||
|
||||
English, Chinese, Russian, French, Spanish and Portuguese. The toolbar, cards
|
||||
and column headers switch immediately; menus and dialogs not yet translated
|
||||
stay in English.
|
||||
|
||||
## Logs
|
||||
|
||||
An activity log of scans, actions, errors and exports, newest last, kept for
|
||||
the current session (the last 2000 lines). Times are shown in UTC.
|
||||
|
||||
## Files in the settings folder
|
||||
|
||||
| File | Holds |
|
||||
|---|---|
|
||||
| `scan-ranges.txt` | scan ranges, one per line |
|
||||
| `auto-rescan-secs.txt`, `scan-timeout-secs.txt`, `scan-concurrency.txt` | the three scan numbers |
|
||||
| `scan-credentials.txt` | global login |
|
||||
| `firmware-credentials.txt` | per-firmware logins |
|
||||
| `ssh-credentials.txt` | SSH login |
|
||||
| `presets.json` | saved views |
|
||||
| `language.txt` | UI language |
|
||||
| `pool-addresses.txt`, `pool-accounts.txt`, `pool-workers.txt`, `pool-passwords.txt` | saved pool values |
|
||||
@@ -0,0 +1,18 @@
|
||||
# Restore to stock firmware
|
||||
|
||||
**Restore to stock firmware...** removes aftermarket firmware and returns the
|
||||
miner to the manufacturer's firmware it keeps on board. Nothing is uploaded.
|
||||
The miner reboots, and some firmwares come back on a new address.
|
||||
|
||||
It is offered when the selection includes a supported firmware, and asks for
|
||||
confirmation with the list of miners first.
|
||||
|
||||
| Firmware | How it is removed | Login used |
|
||||
|---|---|---|
|
||||
| VNish (and builds based on it) | web API: unlock, then remove firmware; reboots in seconds | the VNish row in Credentials, else `admin` |
|
||||
| LuxOS | miner API: log on, then uninstall | none |
|
||||
| Braiins OS | SSH: runs the firmware's own `uninstall.sh` | the SSH row in Credentials (see [Settings](06-settings.md#ssh-login)) |
|
||||
|
||||
Miners are restored one at a time. A dropped connection after the command is
|
||||
sent counts as success, because that is the reboot. A refused login counts as
|
||||
a failure and leaves the miner unchanged.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Export
|
||||
|
||||
**Export** saves the scan as a CSV file for spreadsheets or other tools.
|
||||
|
||||
1. Choose the fields to include (all are ticked by default; **All** and
|
||||
**None** help).
|
||||
2. Pick where to save. The suggested name is `alkane-export-YYYYMMDD-HHMMSS.csv`.
|
||||
|
||||
The export contains **every scanned miner**, not just the rows the current
|
||||
filter shows. Per-board temperatures, fan speeds, board status and pools
|
||||
become numbered columns (`board_temp_1_c`, `fan_2_rpm`, `pool_1_url`, ...).
|
||||
|
||||
Values that start with `=`, `+`, `-` or `@` are prefixed with `'` so a
|
||||
spreadsheet treats them as text, not formulas.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Command line and environment
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Effect |
|
||||
|---|---|
|
||||
| `ALKANE_FAKE_SCAN=1` | demo mode: a built-in sample fleet, no network traffic, simulated actions |
|
||||
| `ALKANE_APPEARANCE=light` or `dark` | force the light or dark theme |
|
||||
| `ALKANE_SELFTEST=1` | run the built-in UI self-test on the sample fleet and exit (prints `SELFTEST PASS` or `FAIL`) |
|
||||
| `ALKANE_ACCESS_PROBE="<ip> <make>"` | print whether the saved login can change that miner, then exit |
|
||||
| `ALKANE_LOG_SCAN="<ip> <brand>"` | fetch that miner's log through its API, print the size, then exit |
|
||||
|
||||
On Windows these one-shot modes print to the Command Prompt they are started
|
||||
from.
|
||||
|
||||
## miner_probe
|
||||
|
||||
`miner_probe` is a command-line companion for scripting and diagnosis. These
|
||||
commands only read:
|
||||
|
||||
| Command | Prints |
|
||||
|---|---|
|
||||
| `miner_probe scan <cidr> [<cidr>...]` | discovered miners and their telemetry, as tab-separated values |
|
||||
| `miner_probe hashrate <cidr>...` | raw hashrate and algorithm |
|
||||
| `miner_probe msgs <ip>` | fault messages and per-board data |
|
||||
| `miner_probe tune <ip>` | tuning support and limits |
|
||||
| `miner_probe presets <ip>` | available firmware profiles |
|
||||
| `miner_probe timezone <ip>` | the current time zone |
|
||||
|
||||
Its other commands change miners. It uses the global login from the settings
|
||||
folder, or `ALKANE_PROBE_USER` and `ALKANE_PROBE_PASS`, and
|
||||
`ALKANE_PROBE_CONCURRENCY` (default 128).
|
||||
@@ -0,0 +1,28 @@
|
||||
# Troubleshooting
|
||||
|
||||
**Windows says "Windows protected your PC".** SmartScreen warns about new
|
||||
downloads until a certificate has built up reputation. The publisher shown
|
||||
should be *BlueFlare Energy Solutions Inc.*; click **More info**, then **Run
|
||||
anyway**. If no publisher is shown, do not run the file and download it again
|
||||
from the releases page.
|
||||
|
||||
**A miner is missing.** Check that its address is inside the scan ranges and
|
||||
that it answers on its web page from this computer. On busy or slow networks,
|
||||
raise **Timeout** or lower **Concurrency** in the Scan ranges dialog.
|
||||
|
||||
**An action is missing from the right-click menu.** Actions appear only when
|
||||
every selected miner supports them. Select fewer miners, or only miners with
|
||||
the same firmware.
|
||||
|
||||
**An action does nothing and the status says a scan is in progress.** Changes
|
||||
wait for scans. Press **Pause**, let the scan finish, then try again.
|
||||
|
||||
**Check access says locked.** The saved login is not accepted. Set the right
|
||||
password in **Settings > Credentials**, either for all firmwares or for that
|
||||
firmware's row.
|
||||
|
||||
**Values are blank.** The firmware did not report them, or it needs a login to
|
||||
report them. Try **Check access** and the Credentials dialog.
|
||||
|
||||
**The window is too small or too large.** It opens at most as large as your
|
||||
screen's work area. Use the zoom slider in the status bar to scale the table.
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# 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 Energy Solutions Inc." 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 a Windows 11 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,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"
|
||||
|
||||
Executable
+58
@@ -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))"
|
||||
Executable
+58
@@ -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
|
||||
Executable
+27
@@ -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"
|
||||
Executable
+38
@@ -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
|
||||
Executable
+20
@@ -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" "$@"
|
||||
@@ -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())
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
Subject: [PATCH 0034] vnish: keep the reported boards and infer the algorithm for unknown models
|
||||
|
||||
Field report 2026-11-03: VNish Antminer S19 (88) units showed no hashboard
|
||||
icons while hashing. VNish reports the model as "Antminer S19 (88)", which is
|
||||
not in asic-rs' alias table, so it parses to AntMinerModel::Unknown with no
|
||||
hardware table. parse_hashboards sized the board list from that table
|
||||
(board_count() = None -> 0 boards) and dropped all three live chains the
|
||||
miner reports in /summary. The same Unknown model also got
|
||||
HashAlgorithm::Unknown, so its hashrate was bucketed as "Unknown Hashrate".
|
||||
|
||||
- VNish v1.2.x and v1.3.x parse_hashboards: when the model has no hardware
|
||||
table, size the boards from the highest 1-based chain id the miner reports
|
||||
(a dead middle board keeps its slot). Known models are unchanged.
|
||||
- infer_antminer_algo (family letter: S/T -> SHA-256, L -> Scrypt,
|
||||
Z -> Equihash, ambiguous -> Unknown) moves from the stock v2020 backend
|
||||
into asic-rs-makes-antminer as a public function; the stock backend and
|
||||
both VNish backends now use it for models the table cannot place.
|
||||
|
||||
Tests: unknown_model_keeps_the_reported_chains (both VNish backends, chain
|
||||
data from the live 10.4.0.179 unit); the existing
|
||||
unknown_models_infer_algo_from_family_letter still passes against the moved
|
||||
helper. Live-verified read-only on all 13 fleet S19 (88) units (10.4.x,
|
||||
10.7.1.190): three hashboard icons each, per-board state intact (e.g. one red
|
||||
board on 10.4.1.111), and the KPI reads "SHA-256 Hashrate".
|
||||
|
||||
diff --git a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
index 71195737..872bd1de 100644
|
||||
--- a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
@@ -202,27 +202,7 @@ fn miner_conf_with_fan_config(miner_conf: &Value, config: FanConfig) -> Value {
|
||||
Value::Object(payload)
|
||||
}
|
||||
|
||||
-/// Infer an Antminer's hash algorithm from its model-family letter, for models
|
||||
-/// asic-rs' alias table doesn't recognise (round 13 #5). Only the families whose
|
||||
-/// entire product line shares one algorithm are inferred; anything ambiguous
|
||||
-/// (the K-series spans Kadena/KHeavyHash/Eaglesong, DR is Blake256 while D is
|
||||
-/// X11) is left Unknown rather than guessed wrong.
|
||||
-fn infer_antminer_algo(model: &str) -> HashAlgorithm {
|
||||
- let upper = model.to_ascii_uppercase();
|
||||
- let name = upper
|
||||
- .strip_prefix("ANTMINER ")
|
||||
- .unwrap_or(&upper)
|
||||
- .trim_start();
|
||||
- match name.chars().next() {
|
||||
- // Z9 / Z11 / Z15 / Z15 Pro / Z15J -- the whole Z line is Equihash.
|
||||
- Some('Z') => HashAlgorithm::Equihash,
|
||||
- // L3+ / L7 / L9 / L11 -- the whole L line is Scrypt.
|
||||
- Some('L') => HashAlgorithm::Scrypt,
|
||||
- // S9..S21 and T9..T21 (and future revisions) are all SHA-256.
|
||||
- Some('S') | Some('T') => HashAlgorithm::SHA256,
|
||||
- _ => HashAlgorithm::Unknown,
|
||||
- }
|
||||
-}
|
||||
+use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
|
||||
impl AntMinerV2020 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
diff --git a/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs b/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs
|
||||
index 2c14f217..3c8e1bee 100644
|
||||
--- a/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, time::Duration};
|
||||
|
||||
+use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
use anyhow;
|
||||
use asic_rs_core::{
|
||||
config::{
|
||||
@@ -17,7 +18,7 @@ use asic_rs_core::{
|
||||
DataCollector, DataExtensions, DataExtractor, DataField, DataLocation, get_by_pointer,
|
||||
},
|
||||
command::MinerCommand,
|
||||
- device::DeviceInfo,
|
||||
+ device::{DeviceInfo, HashAlgorithm},
|
||||
fan::FanData,
|
||||
hashrate::{HashRate, HashRateUnit},
|
||||
message::{MessageSeverity, MinerComponent, MinerMessage},
|
||||
@@ -52,7 +53,14 @@ pub struct VnishV120 {
|
||||
impl VnishV120 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
let auth = Self::default_auth();
|
||||
- let algo = model.hash_algorithm();
|
||||
+ // A model outside asic-rs' alias table (VNish's "Antminer S19 (88)")
|
||||
+ // resolves to HashAlgorithm::Unknown, which left its hashrate bucketed
|
||||
+ // as "Unknown Hashrate". Infer it from the Antminer family letter, as
|
||||
+ // the stock backend does.
|
||||
+ let algo = match model.hash_algorithm() {
|
||||
+ HashAlgorithm::Unknown => infer_antminer_algo(&model.to_string()),
|
||||
+ known => known,
|
||||
+ };
|
||||
VnishV120 {
|
||||
ip,
|
||||
web: VnishWebAPI::new(ip, 80, auth),
|
||||
@@ -509,8 +517,24 @@ impl GetHashboards for VnishV120 {
|
||||
.and_then(|v| v.pointer("/factory"))
|
||||
.and_then(|v| v.as_array());
|
||||
|
||||
- let mut hashboards: Vec<BoardData> =
|
||||
- (0..self.device_info.hardware.board_count().unwrap_or(0) as usize)
|
||||
+ // The model's hardware table gives the board count. For a model asic-rs
|
||||
+ // does not know (e.g. VNish "Antminer S19 (88)") there is no table, and
|
||||
+ // sizing from it dropped every live chain -- the boards then vanished
|
||||
+ // from the data although the miner reports them. Fall back to what the
|
||||
+ // miner reports: the highest 1-based chain id, so a dead middle board
|
||||
+ // still keeps its slot.
|
||||
+ let reported_boards = all_chains
|
||||
+ .iter()
|
||||
+ .filter_map(|c| c.pointer("/id").and_then(|v| v.as_u64()))
|
||||
+ .max()
|
||||
+ .unwrap_or(0) as usize;
|
||||
+ let board_count = self
|
||||
+ .device_info
|
||||
+ .hardware
|
||||
+ .board_count()
|
||||
+ .map(|n| n as usize)
|
||||
+ .unwrap_or(reported_boards);
|
||||
+ let mut hashboards: Vec<BoardData> = (0..board_count)
|
||||
.map(|idx| {
|
||||
BoardData::new(idx as u8, self.device_info.hardware.chips_for_board(idx))
|
||||
})
|
||||
@@ -1524,4 +1548,42 @@ mod tests {
|
||||
assert!(config.available.contains(&Tz::Etc__GMT));
|
||||
assert_eq!(config.available.last(), Some(&Tz::Etc__GMTMinus14));
|
||||
}
|
||||
+
|
||||
+ /// Same as the 1.3.x backend: a model with no hardware table (VNish's
|
||||
+ /// "Antminer S19 (88)") must keep the chains the miner reports instead of
|
||||
+ /// sizing the board list to zero. Live 1.2.7 units (e.g. 10.4.1.111) run it.
|
||||
+ #[tokio::test]
|
||||
+ async fn unknown_model_keeps_the_reported_chains() {
|
||||
+ let miner = VnishV120::new(
|
||||
+ IpAddr::from([127, 0, 0, 1]),
|
||||
+ AntMinerModel::Unknown("ANTMINER S19 (88)".to_string()),
|
||||
+ );
|
||||
+ let mut results = HashMap::new();
|
||||
+ results.insert(
|
||||
+ MinerCommand::WebAPI {
|
||||
+ command: "info",
|
||||
+ parameters: None,
|
||||
+ },
|
||||
+ json!({ "miner": "Antminer S19 (88)", "hr_measure": "GH/s", "fw_version": "1.2.7" }),
|
||||
+ );
|
||||
+ results.insert(
|
||||
+ MinerCommand::WebAPI {
|
||||
+ command: "summary",
|
||||
+ parameters: None,
|
||||
+ },
|
||||
+ json!({ "miner": { "hr_realtime": 82600.0, "chains": [
|
||||
+ { "id": 1, "hashrate_rt": 27537.83 },
|
||||
+ { "id": 2, "hashrate_rt": 27511.20 },
|
||||
+ { "id": 3, "hashrate_rt": 27601.04 }
|
||||
+ ] } }),
|
||||
+ );
|
||||
+ let mock_api = MockAPIClient::new(results);
|
||||
+ let mut collector = DataCollector::new_with_client(&miner, &mock_api);
|
||||
+ let miner_data = miner.parse_data(collector.collect_all().await);
|
||||
+
|
||||
+ assert_eq!(miner_data.hashboards.len(), 3, "one board per reported chain");
|
||||
+ // ...and its hashrate is SHA-256 (family letter S), not "Unknown".
|
||||
+ assert_eq!(miner_data.hashrate.expect("hashrate").algo, HashAlgorithm::SHA256);
|
||||
+ assert!(miner_data.hashboards.iter().all(|b| b.hashrate.is_some()));
|
||||
+ }
|
||||
}
|
||||
diff --git a/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs b/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs
|
||||
index e6247923..0e009f1c 100644
|
||||
--- a/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, time::Duration};
|
||||
|
||||
+use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
use anyhow;
|
||||
use asic_rs_core::{
|
||||
config::{
|
||||
@@ -17,7 +18,7 @@ use asic_rs_core::{
|
||||
DataCollector, DataExtensions, DataExtractor, DataField, DataLocation, get_by_pointer,
|
||||
},
|
||||
command::MinerCommand,
|
||||
- device::DeviceInfo,
|
||||
+ device::{DeviceInfo, HashAlgorithm},
|
||||
fan::FanData,
|
||||
hashrate::{HashRate, HashRateUnit},
|
||||
message::{MessageSeverity, MinerComponent, MinerMessage},
|
||||
@@ -52,7 +53,14 @@ pub struct VnishV130 {
|
||||
impl VnishV130 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
let auth = Self::default_auth();
|
||||
- let algo = model.hash_algorithm();
|
||||
+ // A model outside asic-rs' alias table (VNish's "Antminer S19 (88)")
|
||||
+ // resolves to HashAlgorithm::Unknown, which left its hashrate bucketed
|
||||
+ // as "Unknown Hashrate". Infer it from the Antminer family letter, as
|
||||
+ // the stock backend does.
|
||||
+ let algo = match model.hash_algorithm() {
|
||||
+ HashAlgorithm::Unknown => infer_antminer_algo(&model.to_string()),
|
||||
+ known => known,
|
||||
+ };
|
||||
VnishV130 {
|
||||
ip,
|
||||
web: VnishWebAPI::new(ip, 80, auth),
|
||||
@@ -516,8 +524,24 @@ impl GetHashboards for VnishV130 {
|
||||
.and_then(|v| v.pointer("/factory"))
|
||||
.and_then(|v| v.as_array());
|
||||
|
||||
- let mut hashboards: Vec<BoardData> =
|
||||
- (0..self.device_info.hardware.board_count().unwrap_or(0) as usize)
|
||||
+ // The model's hardware table gives the board count. For a model asic-rs
|
||||
+ // does not know (e.g. VNish "Antminer S19 (88)") there is no table, and
|
||||
+ // sizing from it dropped every live chain -- the boards then vanished
|
||||
+ // from the data although the miner reports them. Fall back to what the
|
||||
+ // miner reports: the highest 1-based chain id, so a dead middle board
|
||||
+ // still keeps its slot.
|
||||
+ let reported_boards = all_chains
|
||||
+ .iter()
|
||||
+ .filter_map(|c| c.pointer("/id").and_then(|v| v.as_u64()))
|
||||
+ .max()
|
||||
+ .unwrap_or(0) as usize;
|
||||
+ let board_count = self
|
||||
+ .device_info
|
||||
+ .hardware
|
||||
+ .board_count()
|
||||
+ .map(|n| n as usize)
|
||||
+ .unwrap_or(reported_boards);
|
||||
+ let mut hashboards: Vec<BoardData> = (0..board_count)
|
||||
.map(|idx| {
|
||||
BoardData::new(idx as u8, self.device_info.hardware.chips_for_board(idx))
|
||||
})
|
||||
@@ -1661,4 +1685,46 @@ mod tests {
|
||||
assert!(config.available.contains(&Tz::Etc__GMT));
|
||||
assert_eq!(config.available.last(), Some(&Tz::Etc__GMTMinus14));
|
||||
}
|
||||
+
|
||||
+ /// A model asic-rs has no hardware table for -- VNish reports the 88-chip
|
||||
+ /// S19 as "Antminer S19 (88)" -- must still surface the boards the miner
|
||||
+ /// reports. Sizing the board list from the (absent) table dropped all
|
||||
+ /// three live chains, so the GUI drew no hashboard icons for a hashing
|
||||
+ /// miner. Chain values match the live 10.4.0.179 unit.
|
||||
+ #[tokio::test]
|
||||
+ async fn unknown_model_keeps_the_reported_chains() {
|
||||
+ let miner = VnishV130::new(
|
||||
+ IpAddr::from([127, 0, 0, 1]),
|
||||
+ AntMinerModel::Unknown("ANTMINER S19 (88)".to_string()),
|
||||
+ );
|
||||
+ let mut results = HashMap::new();
|
||||
+ results.insert(
|
||||
+ web("info"),
|
||||
+ json!({ "miner": "Antminer S19 (88)", "model": "s19-88", "hr_measure": "GH/s" }),
|
||||
+ );
|
||||
+ results.insert(
|
||||
+ web("summary"),
|
||||
+ json!({
|
||||
+ "miner": {
|
||||
+ "hr_realtime": 82600.0,
|
||||
+ "chains": [
|
||||
+ { "id": 1, "hashrate_rt": 27537.83, "chip_statuses": { "grey": 88 } },
|
||||
+ { "id": 2, "hashrate_rt": 27511.20, "chip_statuses": { "grey": 88 } },
|
||||
+ { "id": 3, "hashrate_rt": 27601.04, "chip_statuses": { "grey": 88 } }
|
||||
+ ]
|
||||
+ }
|
||||
+ }),
|
||||
+ );
|
||||
+ let mock_api = MockAPIClient::new(results);
|
||||
+ let mut collector = DataCollector::new_with_client(&miner, &mock_api);
|
||||
+ let miner_data = miner.parse_data(collector.collect_all().await);
|
||||
+
|
||||
+ assert_eq!(miner_data.hashboards.len(), 3, "one board per reported chain");
|
||||
+ // ...and its hashrate is SHA-256 (family letter S), not "Unknown".
|
||||
+ assert_eq!(miner_data.hashrate.expect("hashrate").algo, HashAlgorithm::SHA256);
|
||||
+ for (i, board) in miner_data.hashboards.iter().enumerate() {
|
||||
+ assert_eq!(board.position as usize, i);
|
||||
+ assert!(board.hashrate.is_some(), "board {i} keeps its live hashrate");
|
||||
+ }
|
||||
+ }
|
||||
}
|
||||
diff --git a/vendor/asic-rs-makes-antminer/src/models.rs b/vendor/asic-rs-makes-antminer/src/models.rs
|
||||
index f52639fe..e3185089 100644
|
||||
--- a/vendor/asic-rs-makes-antminer/src/models.rs
|
||||
+++ b/vendor/asic-rs-makes-antminer/src/models.rs
|
||||
@@ -201,6 +201,29 @@ pub enum AntMinerModel {
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
+/// Infer an Antminer's hash algorithm from its model-family letter, for models
|
||||
+/// asic-rs' alias table doesn't recognise (round 13 #5). Only the families whose
|
||||
+/// entire product line shares one algorithm are inferred; anything ambiguous
|
||||
+/// (the K-series spans Kadena/KHeavyHash/Eaglesong, DR is Blake256 while D is
|
||||
+/// X11) is left Unknown rather than guessed wrong. Shared by every firmware
|
||||
+/// backend that runs on Antminer hardware (stock, VNish).
|
||||
+pub fn infer_antminer_algo(model: &str) -> HashAlgorithm {
|
||||
+ let upper = model.to_ascii_uppercase();
|
||||
+ let name = upper
|
||||
+ .strip_prefix("ANTMINER ")
|
||||
+ .unwrap_or(&upper)
|
||||
+ .trim_start();
|
||||
+ match name.chars().next() {
|
||||
+ // Z9 / Z11 / Z15 / Z15 Pro / Z15J -- the whole Z line is Equihash.
|
||||
+ Some('Z') => HashAlgorithm::Equihash,
|
||||
+ // L3+ / L7 / L9 / L11 -- the whole L line is Scrypt.
|
||||
+ Some('L') => HashAlgorithm::Scrypt,
|
||||
+ // S9..S21 and T9..T21 (and future revisions) are all SHA-256.
|
||||
+ Some('S') | Some('T') => HashAlgorithm::SHA256,
|
||||
+ _ => HashAlgorithm::Unknown,
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
impl FromStr for AntMinerModel {
|
||||
type Err = ModelSelectionError;
|
||||
|
||||
Vendored
+4
-2
@@ -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
@@ -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
@@ -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);
|
||||
@@ -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
|
||||
-
|
||||
-[](https://crates.io/crates/wx-rs)
|
||||
-[](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
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() }
|
||||
}
|
||||
Vendored
+33
@@ -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.
|
||||
BIN
Binary file not shown.
+78
-31
@@ -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
@@ -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
@@ -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
@@ -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() }
|
||||
}
|
||||
|
||||
Vendored
+4
@@ -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.
|
||||
|
||||
+23
@@ -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
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user