Compare commits

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:32:14 -06:00
noah 9ad8b56c1f Gate first-party Toolkit Rust formatting 2026-10-20 19:42:41 -06:00
noah 28f8f9ce80 Install rustfmt before CI format gates 2026-10-20 19:32:20 -06:00
noah d35cedd056 Describe formatting in quality badge 2026-10-20 19:30:25 -06:00
noah a825299ebc Format first-party GUI and gate Rust style 2026-10-20 19:29:43 -06:00
noah a17f108050 Clarify Toolkit quality badge scope 2026-10-20 19:28:47 -06:00
noah 3faa35ea70 Clarify Toolkit quality badge scope 2026-10-20 19:11:50 -06:00
noah 16490dd3b9 Merge pull request 'Isolate trusted toolkit jobs from fast runner' (#10) from ci/isolate-fast-runner-main into main 2026-10-20 18:58:53 -06:00
noah e6ae9d9d50 Isolate trusted toolkit jobs from fast runner 2026-10-20 18:45:04 -06:00
noah fc1ed3e4e5 Merge pull request 'Clarify Toolkit control and flashing scope' (#8) from docs/readme-scope into main 2026-10-19 23:52:32 -06:00
noah d7a914258e ci: close documentation-only verification block 2026-10-19 23:42:07 -06:00
noah 2108f47eea docs: clarify toolkit control and flash scope 2026-10-19 23:38:44 -06:00
noah d4a1db7243 Merge pull request 7: ci benchmark input context 2026-10-19 07:23:37 -06:00
noah 18acc31a28 ci: mark benchmark deltas with unchanged build inputs 2026-10-19 07:04:44 -06:00
noah d780fe007a Merge pull request 'ci: scope Toolkit workflow-only pull request checks' (#6) from ci/workflow-only-pr into main 2026-10-19 06:45:20 -06:00
noah f18bad36f3 ci: scope Toolkit workflow-only pull request checks 2026-10-19 06:31:16 -06:00
120 changed files with 75878 additions and 1469 deletions
+3 -1
View File
@@ -12,7 +12,9 @@ concurrency:
jobs:
publish:
runs-on: alkane-pages
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
permissions:
contents: read
steps:
+2 -2
View File
@@ -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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
permissions:
actions: read
contents: write
+80 -3
View File
@@ -12,10 +12,75 @@ 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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
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: 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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
@@ -65,11 +130,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: |
+135 -5
View File
@@ -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,111 @@ 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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
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: 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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
@@ -35,6 +137,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"
@@ -218,11 +329,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'
+1 -1
View File
@@ -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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
env:
CARGO_BUILD_JOBS: 2
steps:
+110 -5
View File
@@ -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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
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"
@@ -43,17 +48,46 @@ jobs:
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
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; 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 +172,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 +181,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 +189,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:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
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
+87
View File
@@ -0,0 +1,87 @@
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 }}
steps:
- name: Fetch the cross-built Windows build
shell: powershell
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: Unit tests (native Windows)
shell: powershell
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)
shell: powershell
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()
shell: powershell
run: |
if ($env:ALKANE_NATIVE) { Remove-Item -Recurse -Force $env:ALKANE_NATIVE -ErrorAction SilentlyContinue }
+16 -7
View File
@@ -10,9 +10,12 @@
![dependencies](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/dependencies.svg)
![license](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/license.svg)
The code quality grade reports GUI Clippy and first-party Rust formatting checks
from the last successful main build. Test coverage has a separate badge.
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 +26,24 @@ 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. See the [implementation plan](docs/IMPLEMENTATION-PLAN.md)
and [firmware matrix](docs/aftermarket-parity-roadmap.md) for planned coverage.
## Development
+70 -9
View File
@@ -15,6 +15,7 @@ import subprocess
import importlib.util
from urllib.error import HTTPError
from urllib.parse import quote
import yaml
from badge_store import BADGE_BRANCH, publish_file, request_json
from bench_host import identity as benchmark_host
@@ -26,6 +27,12 @@ bench_spec.loader.exec_module(bench_badge)
INDEX = "history/index.json"
MAX_INDEX_ENTRIES = 50
BENCH_INPUT_PATHS = (
"Cargo.toml", "Cargo.lock", ".cargo", "crates", "thirdparty", "vendor",
"rust-toolchain.toml", "ci/bench-badge.py", "ci/bench_host.py",
"ci/ensure-build-deps.sh", "ci/ensure-wx-prefix.sh",
"ci/configure-rust-cache.sh", "ci/wx-cache-key.sh",
)
def read_artifact(api: str, repo: str, token: str, filename: str):
@@ -51,6 +58,8 @@ def valid_benches(metrics: dict) -> dict[str, float]:
def git_distance(ancestor: str, sha: str) -> int | None:
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
return None
result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"),
capture_output=True, text=True, check=False)
if result.returncode != 0:
@@ -60,7 +69,7 @@ def git_distance(ancestor: str, sha: str) -> int | None:
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
def previous_entry(index: dict, sha: str, distance=None, host=None) -> dict | None:
distance = distance or git_distance
choices = []
for entry in index.get("entries", []):
@@ -73,8 +82,41 @@ def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dic
if gap is not None and gap > 0:
choices.append((gap, entry))
if not choices:
return {}
return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"])
return None
return min(choices, key=lambda item: item[0])[1]
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
entry = previous_entry(index, sha, distance, host)
return valid_benches(entry["metrics"]) if entry else {}
def benchmark_build_settings(sha: str, root: Path | str = ".") -> dict:
source = subprocess.check_output(
("git", "show", f"{sha}:.gitea/workflows/release.yml"),
cwd=root, text=True)
job = yaml.load(source, Loader=yaml.BaseLoader)["jobs"]["release"]
commands = {step.get("name", ""): step.get("run") for step in job["steps"]}
selected = ("Install build dependencies", "Configure bounded Rust compiler cache",
"Build wxWidgets (once, then cached)", "Build release", "Microbenchmarks")
return {"image": job["container"]["image"], "env": job.get("env", {}),
"commands": {name: commands.get(name) for name in selected}}
def same_benchmark_inputs(ancestor: str, sha: str, root: Path | str = ".") -> bool:
"""Identify changes that only reroute CI without changing benchmark inputs."""
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ValueError("invalid benchmark comparison commit")
diff = subprocess.run(("git", "diff", "--quiet", ancestor, sha, "--",
*BENCH_INPUT_PATHS), cwd=root, check=False)
if diff.returncode not in (0, 1):
raise ValueError("cannot inspect benchmark input changes")
if diff.returncode == 1:
return False
try:
return benchmark_build_settings(ancestor, root) == benchmark_build_settings(sha, root)
except (KeyError, TypeError, subprocess.CalledProcessError, yaml.YAMLError):
return False
def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict:
@@ -101,6 +143,12 @@ def render_html(index: dict) -> str:
host = entry["metrics"].get("bench_host", {})
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
cells.append(f'<td>{html.escape(str(host_label))}</td>')
context = entry["metrics"].get("bench_context", {})
if isinstance(context, dict) and context.get("schema") == 1:
context_label = "same inputs" if context.get("same_inputs") else "changed inputs"
else:
context_label = "unclassified"
cells.append(f'<td>{context_label}</td>')
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
for name in names]
rows.append("<tr>" + "".join(cells) + "</tr>")
@@ -115,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"
+6 -2
View File
@@ -22,6 +22,10 @@ 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:
@@ -32,8 +36,8 @@ def main() -> int:
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("Benchmark Pages must follow main CI on the trusted verifier", file=sys.stderr)
return 1
release = yaml.load(
(ROOT / ".gitea/workflows/release.yml").read_text(),
+8 -2
View File
@@ -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
+11
View File
@@ -11,6 +11,7 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
FILES = ("bench-current.txt",)
BADGE_FILES = ("bench-baseline.json", "bench-context.json")
def cleanup() -> None:
@@ -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__":
+6 -2
View File
@@ -36,10 +36,14 @@ crates/alkane-gui/src/bin/*)
ui=true ;;
crates/alkane-core/*|crates/alkane-discovery/*|crates/alkane-access/*|\
crates/alkane-flash/*|crates/alkane-artifacts/*|crates/alkane-cli/*|\
crates/alkane-gui/src/*|Cargo.toml|Cargo.lock|.gitea/*|ci/*|scripts/*|\
crates/alkane-gui/src/*|crates/alkane-gui/Cargo.toml|crates/alkane-gui/build.rs|\
crates/alkane-gui/windows/*|crates/alkane-gui/assets/*|\
Cargo.toml|Cargo.lock|.gitea/*|ci/*|scripts/*|\
vendor/*|thirdparty/asic-rs/*)
# Any other GUI source file (naming, scan, model, pool_prefs, restore,
# access_probe, credentials, ...) is backend logic. ui.rs/fixtures.rs/bin
# access_probe, credentials, ...) is backend logic, as is how the binary
# is built and packaged (build.rs, the Windows manifest/icon/version
# resources, embedded assets). ui.rs/fixtures.rs/bin
# match the UI arm above first, so they still bump Z, not Y.
backend=true ;;
*) : ;; # docs, HANDOFF, README, thirdparty/wxwidgets tree: no bump
+5 -1
View File
@@ -3,13 +3,17 @@
# 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}"
case "$mode" in
base) packages=(libssl-dev pkg-config ca-certificates) ;;
ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;;
ssh) packages=(openssh-client) ;;
all) packages=(libssl-dev pkg-config ca-certificates openssh-client
xvfb xauth dbus-x11 fonts-dejavu-core) ;;
# Windows cross build (mingw-w64, posix threads) + Wine for its tests.
windows) packages=(libssl-dev pkg-config ca-certificates
gcc-mingw-w64-x86-64-posix g++-mingw-w64-x86-64-posix
binutils-mingw-w64-x86-64 mingw-w64-x86-64-dev wine wine64 xvfb xauth) ;;
*) echo "unknown dependency set: $mode" >&2; exit 2 ;;
esac
+21 -6
View File
@@ -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"
+24 -8
View File
@@ -11,8 +11,10 @@ Metrics not passed on the command line are computed here (LOC from the source
tree, dependency count from Cargo.lock, license from Cargo.toml).
"""
import argparse
import json
import math
import os
from pathlib import Path
import re
import sys
@@ -38,7 +40,8 @@ def text_width(s: str) -> float:
return len(s) * CHAR_W + 2 * PAD
def badge_svg(label: str, message: str, color: str) -> str:
def badge_svg(label: str, message: str, color: str,
description: str | None = None) -> str:
color = COLORS.get(color, color)
lw = round(text_width(label), 1)
mw = round(text_width(message), 1)
@@ -46,8 +49,9 @@ def badge_svg(label: str, message: str, color: str) -> str:
lx = round(lw / 2, 1)
mx = round(lw + mw / 2, 1)
# Text is drawn twice (a dark shadow then the light glyphs) for the shields look.
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{label}: {message}">
<title>{label}: {message}</title>
description = description or f"{label}: {message}"
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{description}">
<title>{description}</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -172,10 +176,10 @@ def main() -> int:
os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
def write(name, label, message, color):
def write(name, label, message, color, description=None):
path = os.path.join(args.root, args.out, name + ".svg")
with open(path, "w", encoding="utf-8") as fh:
fh.write(badge_svg(label, message, color))
fh.write(badge_svg(label, message, color, description))
print(f"wrote {path}: {label}={message}")
loc = count_loc(args.root)
@@ -188,7 +192,8 @@ def main() -> int:
grade = quality_grade(args.clippy)
write("quality", "code quality", grade,
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
"D": "orange", "F": "red", "pending": "lightgrey"}[grade])
"D": "orange", "F": "red", "pending": "lightgrey"}[grade],
f"code quality: {grade} (GUI Clippy and first-party rustfmt)")
if args.tests is not None:
write("tests", "tests", f"{args.tests} passing", "brightgreen")
if args.coverage is not None:
@@ -196,6 +201,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,8 +219,11 @@ 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:
+47
View File
@@ -0,0 +1,47 @@
# 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
#
# 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 \
&& rm -rf /var/lib/apt/lists/*
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 \
&& rustup target list --installed | grep -qx x86_64-pc-windows-gnu
@@ -0,0 +1,4 @@
# Only what the image build copies: the vendored wx tree and its build script.
*
!thirdparty/wxwidgets/**
!scripts/build-wx-windows.sh
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Build the CI image from ci/images/alkane-ci.Dockerfile, push it to the Gitea
# registry, and pin the pushed digest in ci/runner-image.txt and every
# workflow (ci/check-runner-image.py enforces the pin).
#
# Run on the workstation, which holds the registry credential; it is passed to
# a throwaway Docker config that is deleted afterwards, never to a runner.
# ci/images/build-image.sh TAG e.g. ci/images/build-image.sh windows-2026-11-02
set -eu
TAG=${1:?usage: build-image.sh TAG}
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
REGISTRY=gitea.bluefla.re
IMAGE=$REGISTRY/blueflare/alkane-ci
TOKEN_FILE=${GITEA_TOKEN_FILE:-$HOME/.config/gitea/token}
cd "$REPO"
DOCKER_CONFIG=$(mktemp -d)
export DOCKER_CONFIG
trap 'rm -rf "$DOCKER_CONFIG"' 0
user=$(curl -sS --config - "https://$REGISTRY/api/v1/user" <<CFG | python3 -c 'import json,sys; print(json.load(sys.stdin)["login"])'
header = "Authorization: token $(cat "$TOKEN_FILE")"
CFG
)
docker login "$REGISTRY" -u "$user" --password-stdin < "$TOKEN_FILE" >/dev/null
DOCKER_BUILDKIT=1 docker build -f ci/images/alkane-ci.Dockerfile -t "$IMAGE:$TAG" .
docker push "$IMAGE:$TAG" >/dev/null
digest=$(docker inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE:$TAG" \
| grep "^$IMAGE@sha256:" | head -1)
[ -n "$digest" ] || { echo "no registry digest for $IMAGE:$TAG" >&2; exit 1; }
old=$(cat ci/runner-image.txt)
printf '%s\n' "$digest" > ci/runner-image.txt
grep -rl "$old" .gitea/workflows | while read -r f; do
python3 - "$f" "$old" "$digest" <<'PY'
import pathlib, sys
p, old, new = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3]
p.write_text(p.read_text().replace(old, new))
PY
done
python3 ci/check-runner-image.py
echo "pinned $digest"
+89
View File
@@ -0,0 +1,89 @@
#!/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 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}")
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"
"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 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
View File
@@ -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 -1
View File
@@ -1 +1 @@
gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
gitea.bluefla.re/blueflare/alkane-ci@sha256:8f20439b38ae1c070b1a692a89c084f69134f4fa16a755d02783f621cd9ac041
+11
View File
@@ -50,6 +50,17 @@ 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_is_only_the_clippy_result(self):
self.assertEqual(gen_badges.quality_grade("clean"), "A")
self.assertEqual(gen_badges.quality_grade("failed"), "F")
self.assertEqual(gen_badges.quality_grade(None), "pending")
svg = gen_badges.badge_svg(
"code quality", "A", "brightgreen",
"code quality: A (GUI Clippy and first-party rustfmt)",
)
self.assertIn('aria-label="code quality: A (GUI Clippy and first-party rustfmt)"', svg)
self.assertIn('>A</text>', svg)
if __name__ == "__main__":
unittest.main()
+62 -2
View File
@@ -3,11 +3,15 @@
"""Exercise benchmark history selection and safe site rendering."""
import sys
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
from bench_history import bench_badge, previous_measurement, render_html, updated_index
from bench_history import (bench_badge, git_distance, previous_measurement, render_html,
same_benchmark_inputs, updated_index)
class HistoryTests(unittest.TestCase):
@@ -41,6 +45,7 @@ class HistoryTests(unittest.TestCase):
self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5)
def test_invalid_measurement_and_sha_rejected(self):
self.assertIsNone(git_distance("--bad", "a" * 40))
with self.assertRaises(ValueError):
updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now")
with self.assertRaises(ValueError):
@@ -56,14 +61,69 @@ class HistoryTests(unittest.TestCase):
{"hash": 10.0})
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
def test_routing_change_is_marked_same_inputs_but_code_or_build_change_is_not(self):
with tempfile.TemporaryDirectory(prefix="alkane-bench-inputs-") as directory:
root = Path(directory)
workflow = root / ".gitea/workflows/release.yml"
workflow.parent.mkdir(parents=True)
code = root / "crates/alkane-gui/src/main.rs"
code.parent.mkdir(parents=True)
code.write_text("fn main() {}\n")
workflow.write_text(
"jobs:\n release:\n runs-on: alkane-verify\n"
" container:\n image: pinned-image\n"
" env:\n RUSTFLAGS: stable\n steps:\n"
" - name: Build release\n run: cargo build --release\n"
" - name: Microbenchmarks\n run: cargo test --release bench_\n")
def git(*args):
return subprocess.check_output(("git", "-C", str(root), *args),
text=True, stderr=subprocess.DEVNULL).strip()
git("init", "-q")
git("config", "user.name", "CI Test")
git("config", "user.email", "ci@example.invalid")
git("add", ".")
git("commit", "-qm", "base")
base = git("rev-parse", "HEAD")
workflow.write_text(workflow.read_text().replace("alkane-verify", "alkane-ci"))
git("commit", "-qam", "route")
route = git("rev-parse", "HEAD")
self.assertTrue(same_benchmark_inputs(base, route, root))
code.write_text("fn main() { println!(\"changed\"); }\n")
git("commit", "-qam", "code")
changed_code = git("rev-parse", "HEAD")
self.assertFalse(same_benchmark_inputs(route, changed_code, root))
workflow.write_text(workflow.read_text().replace("RUSTFLAGS: stable", "RUSTFLAGS: tuned"))
git("commit", "-qam", "flags")
flags = git("rev-parse", "HEAD")
self.assertFalse(same_benchmark_inputs(changed_code, flags, root))
def test_badge_keeps_raw_delta_and_marks_identical_inputs(self):
with tempfile.TemporaryDirectory(prefix="alkane-bench-badge-context-") as directory:
root = Path(directory)
badges = root / "badges"
badges.mkdir()
(badges / "bench-context.json").write_text(
json.dumps({"schema": 1, "same_inputs": True, "baseline_sha": "a" * 40}))
command = (sys.executable, str(Path(__file__).with_name("gen-badges.py")),
"--root", str(root), "--bench-delta=-36.4")
subprocess.run(command, check=True, capture_output=True)
self.assertIn("-36.4% same inputs", (badges / "bench.svg").read_text())
(badges / "bench-context.json").unlink()
subprocess.run(command, check=True, capture_output=True)
self.assertIn("-36.4% vs prev", (badges / "bench.svg").read_text())
def test_site_escapes_history_content(self):
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
"metrics": {"bench_ns_per_op": {"hash": 10.0},
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
"bench_host": {"cpu_model": "<script>cpu</script>"},
"bench_context": {"schema": 1, "same_inputs": True}}}
page = render_html({"entries": [entry]})
self.assertIn("&lt;script&gt;", page)
self.assertNotIn("<script>", page)
self.assertIn("10.000", page)
self.assertIn("same inputs", page)
if __name__ == "__main__":
+6
View File
@@ -53,6 +53,12 @@ R="$(new_repo)"; mkdir -p "$R/ci"; printf '2' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init
run_case first_release_prebumped_x "$R" version=2.0.0 bump=initial release=true
# 3b. Windows packaging (build script / resources) is release-relevant: bumps Y
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/windows"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf '<assembly/>' > "$R/crates/alkane-gui/windows/alkane-toolkit.exe.manifest"; commit "$R" winres
run_case windows_resources_bump "$R" version=1.3.0 bump=backend release=true
# 3. Backend path change bumps Y
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
+104 -1
View File
@@ -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,108 @@ 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)",
"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", "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"}:
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 +208,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__":
+70
View File
@@ -0,0 +1,70 @@
#!/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 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"
;;
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"
;;
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,16p' "$0" >&2
exit 2
;;
esac
+16 -1
View File
@@ -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
+1 -1
View File
@@ -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")
+2
View File
@@ -1 +1,3 @@
// alkane-core
pub mod platform;
+148
View File
@@ -0,0 +1,148 @@
//! The few places the toolkit's behaviour depends on the operating system,
//! kept together so the rest of the code stays platform-neutral.
//!
//! - where per-user settings live ([`config_dir`]),
//! - how a secret file is written so only its owner can read it
//! ([`write_private`]),
//! - the null device for tools that insist on an output path ([`NULL_DEVICE`]),
//! - how helper programs (`ssh`, `curl`) are started from the GUI without a
//! console window popping up on Windows ([`quiet_command`]).
use std::path::{Path, PathBuf};
use std::process::Command;
/// Directory name of the toolkit's settings under the per-user config root.
pub const APP_DIR: &str = "alkane-toolkit";
/// Environment variable whose value is the per-user config root on this
/// platform: `HOME` (settings in `$HOME/.config/alkane-toolkit`) on Unix,
/// `APPDATA` (settings in `%APPDATA%\alkane-toolkit`) on Windows. Tests point it
/// at a scratch directory.
#[cfg(not(windows))]
pub const CONFIG_ROOT_VAR: &str = "HOME";
#[cfg(windows)]
pub const CONFIG_ROOT_VAR: &str = "APPDATA";
/// The per-user settings directory (not created here).
///
/// Unix keeps the long-standing `$HOME/.config/alkane-toolkit`. Windows uses
/// the roaming application-data folder, `%APPDATA%\alkane-toolkit`, which is
/// where Windows applications keep per-user settings and which the user
/// profile's ACL already restricts to its owner. A missing variable falls back
/// to the working directory, as before.
pub fn config_dir() -> PathBuf {
let root = std::env::var_os(CONFIG_ROOT_VAR).unwrap_or_else(|| ".".into());
if cfg!(windows) {
PathBuf::from(root).join(APP_DIR)
} else {
PathBuf::from(root).join(".config").join(APP_DIR)
}
}
/// `config_dir()/file`.
pub fn config_path(file: &str) -> PathBuf {
config_dir().join(file)
}
/// The null device, for tools that want an output path (`curl -o`,
/// `ssh -o UserKnownHostsFile=`).
#[cfg(not(windows))]
pub const NULL_DEVICE: &str = "/dev/null";
#[cfg(windows)]
pub const NULL_DEVICE: &str = "NUL";
/// Write `data` to `path` so only the owner can read it.
///
/// On Unix the file is created 0600 (so a secret is never momentarily
/// world-readable between write and chmod), and a pre-existing file is
/// re-tightened while it is still empty, before the plaintext is written. On
/// Windows the settings directory inherits the user profile's owner-only ACL,
/// so a plain write already has the equivalent protection.
pub fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(data)
}
#[cfg(not(unix))]
{
std::fs::write(path, data)
}
}
/// A [`Command`] for a helper program run in the background of the GUI.
///
/// On Windows a console program (`ssh.exe`, `curl.exe`) started from a GUI
/// process gets a new console window by default, so every probe would flash a
/// black window; `CREATE_NO_WINDOW` suppresses that while keeping its piped
/// stdin/stdout/stderr. Elsewhere this is `Command::new`.
pub fn quiet_command(program: &str) -> Command {
#[allow(unused_mut)]
let mut command = Command::new(program);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
command
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_dir_is_under_the_platform_root() {
let dir = config_dir();
assert!(dir.ends_with(APP_DIR), "{dir:?}");
if cfg!(windows) {
assert!(!dir.to_string_lossy().contains(".config"), "{dir:?}");
} else {
assert!(dir.parent().unwrap().ends_with(".config"), "{dir:?}");
}
assert_eq!(config_path("x.txt"), dir.join("x.txt"));
}
#[test]
fn write_private_round_trips_and_restricts() {
let dir = std::env::temp_dir().join(format!("alkane-private-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("secret.txt");
write_private(&path, b"one").unwrap();
write_private(&path, b"two").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"two");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn quiet_command_runs_with_piped_output() {
// `cmd /C echo` and `sh -c echo` are the platform's own shells.
let mut command = if cfg!(windows) {
let mut c = quiet_command("cmd");
c.args(["/C", "echo alkane"]);
c
} else {
let mut c = quiet_command("sh");
c.args(["-c", "echo alkane"]);
c
};
let out = command.output().unwrap();
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stdout).contains("alkane"));
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Build script for the alkane-toolkit binary. On Windows targets it compiles
//! windows/alkane-toolkit.rc (application manifest, icon, version info, and
//! wxMSW's stock resources) and links the result into the GUI executable only.
//! Other targets need nothing here.
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
for f in [
"alkane-toolkit.rc",
"alkane-toolkit.exe.manifest",
"alkane-toolkit.ico",
] {
println!("cargo:rerun-if-changed=windows/{f}");
}
println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
if let Err(e) = compile_resources() {
panic!("alkane-gui: Windows resources: {e}");
}
}
fn compile_resources() -> Result<(), String> {
// The resource compiler and wx's resource include path come from the same
// wx-config the wx-rs bridge builds against, so they always match the
// linked wxMSW (and the mingw cross windres when cross-compiling).
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| "wx-config".into());
let run = |arg: &str| -> Result<String, String> {
let out = Command::new(&wxconfig)
.arg(arg)
.output()
.map_err(|e| format!("cannot run {wxconfig} {arg}: {e}"))?;
if !out.status.success() {
return Err(format!("{wxconfig} {arg} failed"));
}
String::from_utf8(out.stdout).map_err(|e| e.to_string())
};
let rescomp = run("--rescomp")?;
let mut words = rescomp.split_whitespace();
let windres = words.next().ok_or("wx-config --rescomp printed nothing")?;
let mut args: Vec<String> = words.map(str::to_owned).collect();
// rcdefs.h lives in the build-specific setup directory, which --rescomp
// omits; it is the -I entry of --cxxflags.
for flag in run("--cxxflags")?.split_whitespace() {
if let Some(dir) = flag.strip_prefix("-I") {
args.push("--include-dir".into());
args.push(dir.into());
}
}
let version = env::var("CARGO_PKG_VERSION").unwrap_or_default();
let mut parts = version
.split(['.', '-', '+'])
.map(|p| p.parse::<u16>().unwrap_or(0));
let (major, minor, patch) = (
parts.next().unwrap_or(0),
parts.next().unwrap_or(0),
parts.next().unwrap_or(0),
);
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(|e| e.to_string())?);
let out =
PathBuf::from(env::var("OUT_DIR").map_err(|e| e.to_string())?).join("alkane-toolkit-res.o");
let status = Command::new(windres)
.args(&args)
.arg("--include-dir")
.arg(manifest_dir.join("windows"))
.arg(format!("--define=ALKANE_VER_MAJOR={major}"))
.arg(format!("--define=ALKANE_VER_MINOR={minor}"))
.arg(format!("--define=ALKANE_VER_PATCH={patch}"))
.arg(format!("--define=ALKANE_VER_STR=\\\"{version}\\\""))
.arg("--input")
.arg(manifest_dir.join("windows/alkane-toolkit.rc"))
.arg("--output-format=coff")
.arg("--output")
.arg(&out)
.status()
.map_err(|e| format!("cannot run {windres}: {e}"))?;
if !status.success() {
return Err(format!("{windres} failed ({status})"));
}
// Only the GUI binary carries the manifest/icon; miner_probe stays a plain
// console tool. A linked object (not an archive member) is never dropped by
// the linker, which is what keeps the resource section in the .exe.
println!("cargo:rustc-link-arg-bin=alkane-toolkit={}", out.display());
Ok(())
}
+69 -23
View File
@@ -29,10 +29,10 @@ use std::net::{SocketAddr, TcpStream};
use std::process::Command;
use std::time::Duration;
use aes::cipher::{block_padding::ZeroPadding, BlockEncryptMut, KeyInit};
use aes::Aes256;
use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use sha2::{Digest, Sha256};
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
@@ -42,9 +42,9 @@ type Aes256EcbEnc = ecb::Encryptor<Aes256>;
/// authenticated/unauthorized answer is `None`.
pub fn classify_http_code(code: &str) -> Option<bool> {
match code.trim() {
"200" | "204" => Some(false), // authenticated -> unlocked/writable
"401" | "403" => Some(true), // rejected -> locked/view-only
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
"200" | "204" => Some(false), // authenticated -> unlocked/writable
"401" | "403" => Some(true), // rejected -> locked/view-only
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
}
}
@@ -77,11 +77,11 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
return Ok(probe_whatsminer_access(ip, &candidates));
}
let url = format!("http://{ip}{}", endpoint(make));
let mut cmd = Command::new("curl");
let mut cmd = alkane_core::platform::quiet_command("curl");
cmd.args([
"-s",
"-o",
"/dev/null",
alkane_core::platform::NULL_DEVICE,
"-w",
"%{http_code}",
"--digest",
@@ -95,7 +95,10 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
]);
// The user:pass goes through a curl config on stdin, never argv, so it can't
// be read from the process list (round 18 #12).
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
let config = format!(
"user = \"{}\"\n",
curl_config_quote(&format!("{user}:{pass}"))
);
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
// curl prints the status code to stdout regardless of exit status (000 on a
// connection failure), so classify the code rather than the exit status.
@@ -113,7 +116,8 @@ fn wait_with_timeout(
stdin_data: Option<&[u8]>,
) -> Result<std::process::Output, String> {
use std::io::{Read, Write};
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
if stdin_data.is_some() {
cmd.stdin(std::process::Stdio::piped());
}
@@ -135,7 +139,11 @@ fn wait_with_timeout(
if let Some(mut e) = child.stderr.take() {
let _ = e.read_to_end(&mut stderr);
}
return Ok(std::process::Output { status, stdout, stderr });
return Ok(std::process::Output {
status,
stdout,
stderr,
});
}
None => {
if start.elapsed() >= timeout {
@@ -158,7 +166,8 @@ fn curl_config_quote(s: &str) -> String {
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
fn whatsminer_password_candidates() -> Vec<String> {
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock") {
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock")
{
if !pass.is_empty() {
return vec![pass.clone()];
}
@@ -170,9 +179,17 @@ fn whatsminer_password_candidates() -> Vec<String> {
/// get_error_code command and format them one per line for the log viewer
/// (round 12 #12). Returns None if the miner does not answer.
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?;
let resp = wm_rpc(
ip,
"{\"command\":\"get_error_code\"}",
Duration::from_secs(6),
)
.ok()?;
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array());
let codes = v
.get("Msg")
.and_then(|m| m.get("error_code"))
.and_then(|c| c.as_array());
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
match codes {
Some(arr) if !arr.is_empty() => {
@@ -198,7 +215,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?;
stream.set_read_timeout(Some(timeout)).ok();
stream.set_write_timeout(Some(timeout)).ok();
stream.write_all(payload.as_bytes()).map_err(|e| e.to_string())?;
stream
.write_all(payload.as_bytes())
.map_err(|e| e.to_string())?;
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
loop {
@@ -213,7 +232,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
Err(_) => break,
}
}
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
Ok(String::from_utf8_lossy(&buf)
.trim_matches('\u{0}')
.to_string())
}
/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact
@@ -278,15 +299,20 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
// 2. Derive the md5crypt password hash + write-token from the password.
let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes());
let full = String::from_utf8_lossy(&crypted);
let Some(pwd_md5) = full.split('$').nth(3) else { continue };
let sign_crypted = md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
let Some(pwd_md5) = full.split('$').nth(3) else {
continue;
};
let sign_crypted =
md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
let sign_full = String::from_utf8_lossy(&sign_crypted);
let host_sign = sign_full.split('$').nth(3).unwrap_or("");
// 3. Send an encrypted, read-only `summary`. If the AES key (from the
// password) is right the miner replies encrypted; if wrong it returns
// a plaintext "enc json load err".
let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}");
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else { continue };
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else {
continue;
};
let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}");
let resp = match wm_rpc(ip, &payload, timeout) {
Ok(s) => s,
@@ -302,7 +328,11 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
}
// Only report "locked" when we cleanly reached the miner and every candidate
// was rejected with no transient errors; otherwise the result is indeterminate.
if reachable && !errored { Some(true) } else { None }
if reachable && !errored {
Some(true)
} else {
None
}
}
#[cfg(test)]
@@ -311,14 +341,30 @@ mod tests {
#[test]
fn classify_codes() {
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
assert_eq!(
classify_http_code("200"),
Some(false),
"authenticated -> unlocked"
);
assert_eq!(classify_http_code("204"), Some(false));
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
assert_eq!(
classify_http_code("401"),
Some(true),
"unauthorized -> locked"
);
assert_eq!(classify_http_code("403"), Some(true));
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
assert_eq!(
classify_http_code("404"),
None,
"endpoint absent -> unknown"
);
assert_eq!(classify_http_code("500"), None);
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
assert_eq!(
classify_http_code(" 200 "),
Some(false),
"whitespace tolerated"
);
assert_eq!(classify_http_code(""), None);
}
+122
View File
@@ -0,0 +1,122 @@
//! Non-interactive SSH password logins without `sshpass`.
//!
//! OpenSSH (Linux, and the `ssh.exe` built into Windows 10/11) asks the
//! program named by `SSH_ASKPASS` for a password when `SSH_ASKPASS_REQUIRE=force`
//! (OpenSSH 8.4+). The toolkit names its own executable: when ssh runs it with
//! [`ROLE_ENV`] set, `main()` calls [`serve_if_askpass`] first thing, which
//! prints the password from [`SECRET_ENV`] and exits before any GUI starts.
//!
//! This replaces `sshpass`, which Windows does not have, with one mechanism for
//! every platform. Like `sshpass -e` the password travels in the child's
//! environment, never on a command line where the process list would show it.
use std::ffi::OsStr;
use std::process::{Command, Stdio};
/// Set (to "1") in the environment of an ssh child whose askpass helper is us.
pub const ROLE_ENV: &str = "ALKANE_SSH_ASKPASS";
/// The password the askpass helper hands back to ssh.
pub const SECRET_ENV: &str = "ALKANE_SSH_SECRET";
/// If this process is ssh's askpass helper, answer the prompt and return the
/// exit code to use; otherwise `None` and the app starts normally.
pub fn serve_if_askpass() -> Option<i32> {
std::env::var_os(ROLE_ENV)?;
let prompt = std::env::args_os().nth(1).unwrap_or_default();
Some(answer(&prompt, std::env::var_os(SECRET_ENV).as_deref()))
}
/// Print the secret for a password prompt. Anything else ssh might ask through
/// askpass (a host-key "yes/no" confirmation, a passphrase for a key we never
/// configured) is refused, so a changed prompt can never be answered with the
/// password by accident.
fn answer(prompt: &OsStr, secret: Option<&OsStr>) -> i32 {
let Some(secret) = secret else { return 1 };
if !is_password_prompt(&prompt.to_string_lossy()) {
return 1;
}
use std::io::Write;
let mut out = std::io::stdout().lock();
if out
.write_all(secret.to_string_lossy().as_bytes())
.and_then(|_| out.write_all(b"\n"))
.and_then(|_| out.flush())
.is_err()
{
return 1;
}
0
}
fn is_password_prompt(prompt: &str) -> bool {
let p = prompt.to_ascii_lowercase();
p.contains("password") && !p.contains("yes/no")
}
/// Configure an `ssh` command to log in with `password` and never block on a
/// terminal prompt. ssh tries password (and keyboard-interactive) auth once;
/// a wrong password fails fast with "Permission denied" instead of hanging.
pub fn ssh_with_password(cmd: &mut Command, password: &str) -> Result<(), String> {
let exe = std::env::current_exe().map_err(|e| format!("locate askpass helper: {e}"))?;
cmd.env("SSH_ASKPASS", exe)
.env("SSH_ASKPASS_REQUIRE", "force")
.env(ROLE_ENV, "1")
.env(SECRET_ENV, password)
.stdin(Stdio::null());
Ok(())
}
/// ssh `-o` options that go with [`ssh_with_password`].
pub const PASSWORD_AUTH_OPTIONS: [&str; 4] = [
"-o",
"PreferredAuthentications=password,keyboard-interactive",
"-o",
"NumberOfPasswordPrompts=1",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_password_prompts_are_answered() {
assert!(is_password_prompt("root@10.0.0.1's password: "));
assert!(is_password_prompt("Password:"));
assert!(!is_password_prompt(
"Are you sure you want to continue connecting (yes/no/[fingerprint])?"
));
assert!(!is_password_prompt(
"Enter passphrase for key '/x/id_ed25519':"
));
assert_eq!(
answer(OsStr::new("Password:"), None),
1,
"no secret -> refuse"
);
assert_eq!(
answer(OsStr::new("Continue (yes/no)?"), Some(OsStr::new("pw"))),
1
);
}
#[test]
fn ssh_command_gets_askpass_environment() {
let mut cmd = Command::new("ssh");
ssh_with_password(&mut cmd, "hunter2").unwrap();
let env: std::collections::HashMap<_, _> = cmd
.get_envs()
.map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned())))
.collect();
assert_eq!(
env[OsStr::new("SSH_ASKPASS_REQUIRE")].as_deref(),
Some(OsStr::new("force"))
);
assert_eq!(
env[OsStr::new(SECRET_ENV)].as_deref(),
Some(OsStr::new("hunter2"))
);
assert!(env[OsStr::new("SSH_ASKPASS")].is_some());
// The password is never an argument.
assert!(cmd.get_args().all(|a| a != "hunter2"));
}
}
+29 -12
View File
@@ -19,18 +19,19 @@
//! ALKANE_PROBE_USER / ALKANE_PROBE_PASS if set (so a test can authenticate
//! without touching the app's saved config).
use asic_rs::MinerFactory;
use asic_rs::core::traits::miner::MinerAuth;
use asic_rs::MinerFactory;
use futures_util::StreamExt;
use measurements::Power;
fn load_creds() -> Option<(String, String)> {
if let (Ok(u), Ok(pw)) = (std::env::var("ALKANE_PROBE_USER"), std::env::var("ALKANE_PROBE_PASS")) {
if let (Ok(u), Ok(pw)) = (
std::env::var("ALKANE_PROBE_USER"),
std::env::var("ALKANE_PROBE_PASS"),
) {
return Some((u, pw));
}
let home = std::env::var("HOME").ok()?;
let p = std::path::PathBuf::from(home)
.join(".config/alkane-toolkit/scan-credentials.txt");
let p = alkane_core::platform::config_path("scan-credentials.txt");
let s = std::fs::read_to_string(p).ok()?;
let mut l = s.lines();
let u = l.next()?.to_string();
@@ -92,8 +93,14 @@ async fn scan(cidrs: &[String]) {
.map(|c| c.to_string())
.unwrap_or_default();
let fw_ver = data.firmware_version.clone().unwrap_or_default();
let bs = data.best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
let sbs = data.session_best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
let bs = data
.best_share
.map(|v| format!("{v:.0}"))
.unwrap_or_default();
let sbs = data
.session_best_share
.map(|v| format!("{v:.0}"))
.unwrap_or_default();
println!(
"{ip}\t{}\t{}\t{}\t{}\t{}\t{watts:.0}\t{}\t{}\t{bs}\t{sbs}",
data.device_info.make,
@@ -281,7 +288,10 @@ async fn msgs(ip_s: &str) {
Ok(Some(m)) => {
let d = m.get_data().await;
let th = |h: &Option<asic_rs::core::data::hashrate::HashRate>| {
h.clone().map(|x| x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
h.clone().map(|x| {
x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
.value
})
};
println!(
"{ip}: {} {} hashboards={:?} expected={:?}",
@@ -389,7 +399,7 @@ async fn lifecycle(ip_s: &str, verb: &str) {
/// Read (no tz arg) or set the miner's timezone (round 16 / G10). Capability-gated.
async fn timezone(ip_s: &str, tz: Option<&str>) {
use asic_rs::core::config::timezone::{Tz, TimezoneConfig};
use asic_rs::core::config::timezone::{TimezoneConfig, Tz};
let Ok(ip) = ip_s.parse::<std::net::IpAddr>() else {
eprintln!("bad ip {ip_s}");
return;
@@ -566,7 +576,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
TuningTarget::HashRate(hr)
}
None => {
eprintln!("miner reports no current hashrate; cannot build a hashrate target");
eprintln!(
"miner reports no current hashrate; cannot build a hashrate target"
);
return;
}
},
@@ -593,7 +605,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
}
} else if kind == "power" && m.supports_set_power_limit() {
match m.set_power_limit(Power::from_watts(value)).await {
Ok(v) => println!("set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"),
Ok(v) => println!(
"set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"
),
Err(e) => println!("set_power_limit({value} W) -> Err: {e:#}"),
}
} else {
@@ -680,7 +694,10 @@ async fn setpreset(ip_s: &str, name: &str) {
fn main() {
let args: Vec<String> = std::env::args().collect();
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(e) => {
eprintln!("tokio runtime: {e}");
+77 -53
View File
@@ -6,11 +6,11 @@
//! firmware registry, so `scan`'s callers never have to think about it.
use std::collections::HashMap;
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use asic_rs::MinerFactory;
use alkane_core::platform::write_private;
use asic_rs::core::traits::miner::MinerAuth;
use asic_rs::MinerFactory;
use crate::scan::config_path;
@@ -40,20 +40,9 @@ fn save_creds_file(file: &str, user: &str, pass: &str) -> std::io::Result<()> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
// Open (and create) with mode 0600 up front so a freshly created file is
// never world/group-readable, even for the instant before the write. For a
// pre-existing file the create mode is ignored, so also tighten it to 0600
// while it is still empty (post-truncate, pre-write) -- the plaintext is
// never on disk under a looser mode.
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(format!("{user}\n{pass}\n").as_bytes())?;
Ok(())
// Owner-only from creation on (0600 on Unix, re-tightened if the file
// already existed): the plaintext is never on disk under a looser mode.
write_private(&p, format!("{user}\n{pass}\n").as_bytes())
}
fn clear_creds_file(file: &str) -> std::io::Result<()> {
@@ -164,20 +153,14 @@ pub fn save_firmware_credentials(map: &HashMap<String, (String, String)>) -> std
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
let mut names: Vec<&String> = map.keys().collect();
names.sort();
let mut body = String::new();
for name in names {
let (user, pass) = &map[name];
f.write_all(format!("{name}\t{user}\t{pass}\n").as_bytes())?;
body.push_str(&format!("{name}\t{user}\t{pass}\n"));
}
Ok(())
write_private(&p, body.as_bytes())
}
/// Remove the per-firmware overrides file, if any. Not an error if none exists.
@@ -195,8 +178,8 @@ pub fn configured_factory() -> MinerFactory {
// (round 18 #12: config actions / refresh / pools / flash previously used
// asic-rs's 10s default, so on a slow link they could fail to reach miners a
// longer-timeout scan had found). start_scan may still override it explicitly.
let mut factory =
MinerFactory::new().with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
let mut factory = MinerFactory::new()
.with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
let global = load_credentials();
let per_fw = load_firmware_credentials();
if global.is_none() && per_fw.is_empty() {
@@ -218,25 +201,47 @@ pub fn configured_factory() -> MinerFactory {
mod tests {
use super::*;
/// Unix: the file is mode 0600. Windows relies on the profile directory's
/// owner-only ACL (see `alkane_core::platform::write_private`), so only
/// existence is checked there.
fn assert_owner_only(path: &std::path::Path, why: &str) {
let meta = std::fs::metadata(path).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "{why}");
}
#[cfg(not(unix))]
assert!(meta.is_file(), "{why}");
}
#[test]
fn credentials_round_trip_and_file_perms() {
// config_path() reads $HOME; point it at a private temp dir. HOME is
// process-global, so serialise against other HOME-mutating tests via the
// shared lock and restore HOME afterward (round 18 #12).
let _home = crate::model::HOME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let prev = std::env::var_os("HOME");
let _home = crate::model::HOME_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let root_var = alkane_core::platform::CONFIG_ROOT_VAR;
let prev = std::env::var_os(root_var);
let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("HOME", &dir);
std::env::set_var(root_var, &dir);
assert_eq!(load_credentials(), None, "no file -> None");
save_credentials("admin", "hunter2").unwrap();
assert_eq!(load_credentials(), Some(("admin".to_string(), "hunter2".to_string())));
assert_eq!(
load_credentials(),
Some(("admin".to_string(), "hunter2".to_string()))
);
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600");
assert_owner_only(
&config_path(CREDENTIALS_FILE),
"credentials file must be 0600",
);
// configured_factory() must construct in both branches without panicking:
// with saved credentials (fans auth across every firmware backend) ...
@@ -246,15 +251,20 @@ mod tests {
// 0600 by save_credentials (the create-mode is ignored for an existing
// file, so the explicit set_permissions is what protects it).
let path = config_path(CREDENTIALS_FILE);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
}
save_credentials("admin2", "s3cr3t").unwrap();
let meta = std::fs::metadata(&path).unwrap();
assert_owner_only(
&path,
"save over a pre-existing 0644 file must re-tighten to 0600",
);
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"save over a pre-existing 0644 file must re-tighten to 0600"
load_credentials(),
Some(("admin2".to_string(), "s3cr3t".to_string()))
);
assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string())));
clear_credentials().unwrap();
// ... and with no saved credentials (plain MinerFactory::new()).
@@ -265,35 +275,49 @@ mod tests {
// Per-firmware overrides (round 12 #13). Kept in this same test because
// HOME is process-global: a second #[test] mutating it would race under
// cargo's default parallel runner.
assert!(load_firmware_credentials().is_empty(), "no file -> empty map");
assert!(
load_firmware_credentials().is_empty(),
"no file -> empty map"
);
let mut fw = HashMap::new();
fw.insert("WhatsMiner Stock".to_string(), ("super".to_string(), "sup3r".to_string()));
fw.insert(
"WhatsMiner Stock".to_string(),
("super".to_string(), "sup3r".to_string()),
);
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
save_firmware_credentials(&fw).unwrap();
// 0600, and it round-trips (an empty username survives the tab format).
let fwpath = config_path(FIRMWARE_CREDENTIALS_FILE);
assert_eq!(
std::fs::metadata(&fwpath).unwrap().permissions().mode() & 0o777,
0o600,
"per-firmware creds file must be 0600"
);
assert_owner_only(&fwpath, "per-firmware creds file must be 0600");
let back = load_firmware_credentials();
assert_eq!(back.get("WhatsMiner Stock"), Some(&("super".into(), "sup3r".into())));
assert_eq!(
back.get("WhatsMiner Stock"),
Some(&("super".into(), "sup3r".into()))
);
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
assert_eq!(back.len(), 2);
// Shipped-default lookup: known firmware resolves, unknown blanks.
assert_eq!(firmware_default_for("AntMiner Stock"), ("root".into(), "root".into()));
assert_eq!(firmware_default_for("nonexistent"), (String::new(), String::new()));
assert_eq!(
firmware_default_for("AntMiner Stock"),
("root".into(), "root".into())
);
assert_eq!(
firmware_default_for("nonexistent"),
(String::new(), String::new())
);
// Overrides + no global still builds a factory.
let _ = configured_factory();
// Saving an empty map clears the file (no stale overrides linger).
save_firmware_credentials(&HashMap::new()).unwrap();
assert!(load_firmware_credentials().is_empty(), "empty save -> cleared");
assert!(
load_firmware_credentials().is_empty(),
"empty save -> cleared"
);
clear_firmware_credentials().unwrap(); // idempotent
match prev {
Some(v) => std::env::set_var("HOME", v),
None => std::env::remove_var("HOME"),
Some(v) => std::env::set_var(root_var, v),
None => std::env::remove_var(root_var),
}
let _ = std::fs::remove_dir_all(&dir);
}
+77 -20
View File
@@ -100,28 +100,62 @@ fn scalar_columns() -> Vec<Col> {
("slow", |r| r.slow.to_string()),
("paused", |r| r.paused.to_string()),
("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")),
("write_locked", |r| opt_bool(r.write_locked, "locked", "unlocked")),
("light_flashing", |r| opt_bool(r.light_flashing, "on", "off")),
("write_locked", |r| {
opt_bool(r.write_locked, "locked", "unlocked")
}),
("light_flashing", |r| {
opt_bool(r.light_flashing, "on", "off")
}),
("hashrate_ths", |r| num(r.hashrate_ths)),
("expected_ths", |r| num(r.expected_ths)),
("efficiency_j_th", |r| num(r.efficiency)),
("power_w", |r| num(r.power_w)),
("tuning_percent", |r| r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()),
("tuning_percent", |r| {
r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()
}),
("chip_temp_c", |r| num(r.chip_temp_c)),
("fluid_temp_c", |r| num(r.fluid_temp_c)),
("env_temp_c", |r| num(r.env_temp_c)),
("outlet_temp_c", |r| num(r.outlet_temp_c)),
("psu_fan_rpm", |r| num(r.psu_fan_rpm)),
("fan_count", |r| r.fan_count.map(|v| v.to_string()).unwrap_or_default()),
("expected_fans", |r| r.expected_fans.map(|v| v.to_string()).unwrap_or_default()),
("total_chips", |r| r.total_chips.map(|v| v.to_string()).unwrap_or_default()),
("expected_chips", |r| r.expected_chips.map(|v| v.to_string()).unwrap_or_default()),
("hashboards", |r| r.hashboards.map(|v| v.to_string()).unwrap_or_default()),
("expected_hashboards", |r| r.expected_hashboards.map(|v| v.to_string()).unwrap_or_default()),
("uptime_secs", |r| if r.uptime_secs > 0 { r.uptime_secs.to_string() } else { String::new() }),
("fan_count", |r| {
r.fan_count.map(|v| v.to_string()).unwrap_or_default()
}),
("expected_fans", |r| {
r.expected_fans.map(|v| v.to_string()).unwrap_or_default()
}),
("total_chips", |r| {
r.total_chips.map(|v| v.to_string()).unwrap_or_default()
}),
("expected_chips", |r| {
r.expected_chips.map(|v| v.to_string()).unwrap_or_default()
}),
("hashboards", |r| {
r.hashboards.map(|v| v.to_string()).unwrap_or_default()
}),
("expected_hashboards", |r| {
r.expected_hashboards
.map(|v| v.to_string())
.unwrap_or_default()
}),
("uptime_secs", |r| {
if r.uptime_secs > 0 {
r.uptime_secs.to_string()
} else {
String::new()
}
}),
("best_share", |r| r.best_share.map(num).unwrap_or_default()),
("session_best_share", |r| r.session_best_share.map(num).unwrap_or_default()),
("pool_account", |r| r.worker.split_once('.').map(|(a, _)| a).unwrap_or(&r.worker).to_string()),
("session_best_share", |r| {
r.session_best_share.map(num).unwrap_or_default()
}),
("pool_account", |r| {
r.worker
.split_once('.')
.map(|(a, _)| a)
.unwrap_or(&r.worker)
.to_string()
}),
("pool_url", |r| r.pool_url.clone()),
("errors", |r| r.errors.join("; ")),
]
@@ -137,7 +171,10 @@ pub const GROUP_POOLS: &str = "pools";
/// Every selectable export field, in output order: each scalar column header,
/// then the four variable-length group keys.
pub fn export_field_names() -> Vec<String> {
let mut v: Vec<String> = scalar_columns().iter().map(|(h, _)| (*h).to_string()).collect();
let mut v: Vec<String> = scalar_columns()
.iter()
.map(|(h, _)| (*h).to_string())
.collect();
v.push(GROUP_BOARD_TEMPS.to_string());
v.push(GROUP_FANS.to_string());
v.push(GROUP_BOARD_STATUS.to_string());
@@ -152,16 +189,26 @@ pub fn rows_to_csv_selected(
rows: &[MinerRow],
selected: &std::collections::HashSet<String>,
) -> String {
let cols: Vec<Col> =
scalar_columns().into_iter().filter(|(h, _)| selected.contains(*h)).collect();
let cols: Vec<Col> = scalar_columns()
.into_iter()
.filter(|(h, _)| selected.contains(*h))
.collect();
// A group's columns appear only when it is selected; an unselected group's
// width stays 0, so the header/value loops below emit nothing for it.
let width = |want: bool, f: &dyn Fn(&MinerRow) -> usize| -> usize {
if want { rows.iter().map(f).max().unwrap_or(0) } else { 0 }
if want {
rows.iter().map(f).max().unwrap_or(0)
} else {
0
}
};
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| r.board_temps.len());
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| {
r.board_temps.len()
});
let max_fans = width(selected.contains(GROUP_FANS), &|r| r.fan_rpms.len());
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| r.board_status.len());
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| {
r.board_status.len()
});
let max_pools = width(selected.contains(GROUP_POOLS), &|r| r.pools.len());
// Header.
@@ -193,7 +240,13 @@ pub fn rows_to_csv_selected(
vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default());
}
for i in 0..max_boards {
vals.push(r.board_status.get(i).map(board_health_str).unwrap_or("").to_string());
vals.push(
r.board_status
.get(i)
.map(board_health_str)
.unwrap_or("")
.to_string(),
);
}
for i in 0..max_pools {
let (u, w) = r.pools.get(i).cloned().unwrap_or_default();
@@ -222,7 +275,11 @@ mod tests {
fan_rpms: vec![6000.0, 6100.0],
..Default::default()
},
MinerRow { ip: "10.0.0.2".into(), model: "M30S".into(), ..Default::default() },
MinerRow {
ip: "10.0.0.2".into(),
model: "M30S".into(),
..Default::default()
},
];
let all: std::collections::HashSet<String> = export_field_names().into_iter().collect();
let csv = rows_to_csv_selected(&rows, &all);
+203 -39
View File
@@ -42,9 +42,22 @@ impl Board {
let slow = is_slow(self.mining, self.hashrate, self.expected);
// A few extra metrics so the demo/offline mode shows non-empty values
// for some of the additional columns.
let last_octet: u8 = self.ip.rsplit('.').next().and_then(|s| s.parse().ok()).unwrap_or(0);
let last_octet: u8 = self
.ip
.rsplit('.')
.next()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let (boards, chips, efficiency) = if self.mining {
(Some(3u32), Some(210u32), if self.hashrate > 0.0 { self.power / self.hashrate } else { 0.0 })
(
Some(3u32),
Some(210u32),
if self.hashrate > 0.0 {
self.power / self.hashrate
} else {
0.0
},
)
} else {
(None, None, 0.0)
};
@@ -63,7 +76,11 @@ impl Board {
// Per-board hashrate for the R2 Health tooltip demo: split the total three
// ways with a little variety (index-aligned with the 3 boards).
let board_hashrates = if self.mining && self.hashrate > 0.0 {
vec![self.hashrate * 0.34, self.hashrate * 0.35, self.hashrate * 0.31]
vec![
self.hashrate * 0.34,
self.hashrate * 0.35,
self.hashrate * 0.31,
]
} else {
vec![]
};
@@ -147,7 +164,10 @@ impl Board {
slow,
paused: self.paused,
// offline defaults to false (online); these bench rows are reachable.
mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)),
mac: format!(
"AA:BB:CC:00:{:02X}:{last_octet:02X}",
last_octet.wrapping_mul(3)
),
hostname: format!("miner-{last_octet}"),
hashboards: boards,
expected_hashboards: Some(3),
@@ -156,22 +176,40 @@ impl Board {
psu_fan_rpm: if self.mining { self.fan * 0.9 } else { 0.0 },
// PSU info demo (round 17 R5): mining units show a version + rated
// envelope + live output, so the columns and the R2 PSU tooltip render.
psu_version: if self.mining { "22 (117)".to_string() } else { String::new() },
psu_version: if self.mining {
"22 (117)".to_string()
} else {
String::new()
},
psu_voltage_min_v: self.mining.then_some(11.88),
psu_voltage_max_v: self.mining.then_some(15.18),
psu_out_voltage_v: self.mining.then_some(13.2),
psu_out_current_a: self.mining.then_some(210.0),
uptime_secs: if self.mining { 3600 * 24 * 2 + 3600 * 5 } else { 0 },
uptime_secs: if self.mining {
3600 * 24 * 2 + 3600 * 5
} else {
0
},
// One unit is "being located" so the Light column's yellow dot is
// demonstrable offline (round 11 #10).
light_flashing: Some(self.ip == "10.255.1.167"),
pool_url: if self.worker.is_empty() { String::new() } else { "stratum+tcp://pool.blueflare:3333".to_string() },
pool_url: if self.worker.is_empty() {
String::new()
} else {
"stratum+tcp://pool.blueflare:3333".to_string()
},
pools: if self.worker.is_empty() {
Vec::new()
} else {
vec![
("stratum+tcp://pool.blueflare:3333".to_string(), self.worker.to_string()),
("stratum+tcp://backup.blueflare:3333".to_string(), format!("{}_bak", self.worker)),
(
"stratum+tcp://pool.blueflare:3333".to_string(),
self.worker.to_string(),
),
(
"stratum+tcp://backup.blueflare:3333".to_string(),
format!("{}_bak", self.worker),
),
]
},
operating_state: if self.paused {
@@ -223,9 +261,18 @@ impl Board {
// is exercisable offline on units that advertise preset support.
presets: if self.mining {
vec![
crate::model::MinerPreset { name: "default".into(), pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()) },
crate::model::MinerPreset { name: "540MHz".into(), pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()) },
crate::model::MinerPreset { name: "490MHz".into(), pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()) },
crate::model::MinerPreset {
name: "default".into(),
pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()),
},
crate::model::MinerPreset {
name: "540MHz".into(),
pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()),
},
crate::model::MinerPreset {
name: "490MHz".into(),
pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()),
},
]
} else {
Vec::new()
@@ -247,35 +294,152 @@ pub fn bench_fleet() -> Vec<MinerRow> {
let boards = [
// firmware families span the palette (Stock/VNish/Braiins/LuxOS/ePIC/
// Hive/BixBit/Alkane) so the offline demo shows the Firmware colouring.
Board { ip: "10.255.1.112", make: "Antminer", model_id: "S17", board: "Xilinx", firmware: "Stock", fw_version: "",
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
worker: "", mining: false, paused: false },
Board { ip: "10.255.1.166", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "VNish", fw_version: "1.2.8",
hashrate: 95.0, expected: 96.0, power: 3250.0, temp: 65.0, fan: 4200.0,
worker: "blueflare.s19", mining: true, paused: false },
Board { ip: "10.255.1.152", make: "Antminer", model_id: "S19jPro", board: "AMLogic", firmware: "Braiins", fw_version: "25.05.1",
hashrate: 100.0, expected: 104.0, power: 3100.0, temp: 62.0, fan: 3900.0,
worker: "blueflare.s19jpro", mining: true, paused: false },
Board { ip: "10.255.1.167", make: "Antminer", model_id: "S19KPro", board: "AMLogic", firmware: "LuxOS", fw_version: "2024.9.0",
hashrate: 120.0, expected: 128.0, power: 3300.0, temp: 68.0, fan: 4500.0,
worker: "blueflare.s19kpro", mining: true, paused: false },
Board { ip: "10.255.1.149", make: "Antminer", model_id: "S21Pro", board: "CVITek", firmware: "ePIC", fw_version: "1.0.3",
hashrate: 60.0, expected: 200.0, power: 1500.0, temp: 55.0, fan: 3000.0,
worker: "blueflare.s21pro", mining: true, paused: false }, // slow: 60/200 = 30%
Board { ip: "10.255.1.126", make: "Whatsminer", model_id: "M30SVE40", board: "H3", firmware: "Stock", fw_version: "H3.0.1",
hashrate: 92.0, expected: 96.0, power: 3400.0, temp: 70.0, fan: 4800.0,
worker: "blueflare.h3", mining: true, paused: false },
Board { ip: "10.255.1.131", make: "Whatsminer", model_id: "M30SPlusVE40", board: "H616", firmware: "Hiveon", fw_version: "1.05",
hashrate: 100.0, expected: 100.0, power: 3450.0, temp: 71.0, fan: 4900.0,
worker: "blueflare.h616", mining: true, paused: false },
Board { ip: "10.255.1.148", make: "Whatsminer", model_id: "M50VH50", board: "H6", firmware: "Bixbit", fw_version: "0.9.9.4",
hashrate: 118.0, expected: 122.0, power: 3300.0, temp: 66.0, fan: 4600.0,
worker: "blueflare.m50", mining: true, paused: false },
Board {
ip: "10.255.1.112",
make: "Antminer",
model_id: "S17",
board: "Xilinx",
firmware: "Stock",
fw_version: "",
hashrate: 0.0,
expected: 0.0,
power: 0.0,
temp: 0.0,
fan: 0.0,
worker: "",
mining: false,
paused: false,
},
Board {
ip: "10.255.1.166",
make: "Antminer",
model_id: "S19",
board: "BeagleBoneBlack",
firmware: "VNish",
fw_version: "1.2.8",
hashrate: 95.0,
expected: 96.0,
power: 3250.0,
temp: 65.0,
fan: 4200.0,
worker: "blueflare.s19",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.152",
make: "Antminer",
model_id: "S19jPro",
board: "AMLogic",
firmware: "Braiins",
fw_version: "25.05.1",
hashrate: 100.0,
expected: 104.0,
power: 3100.0,
temp: 62.0,
fan: 3900.0,
worker: "blueflare.s19jpro",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.167",
make: "Antminer",
model_id: "S19KPro",
board: "AMLogic",
firmware: "LuxOS",
fw_version: "2024.9.0",
hashrate: 120.0,
expected: 128.0,
power: 3300.0,
temp: 68.0,
fan: 4500.0,
worker: "blueflare.s19kpro",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.149",
make: "Antminer",
model_id: "S21Pro",
board: "CVITek",
firmware: "ePIC",
fw_version: "1.0.3",
hashrate: 60.0,
expected: 200.0,
power: 1500.0,
temp: 55.0,
fan: 3000.0,
worker: "blueflare.s21pro",
mining: true,
paused: false,
}, // slow: 60/200 = 30%
Board {
ip: "10.255.1.126",
make: "Whatsminer",
model_id: "M30SVE40",
board: "H3",
firmware: "Stock",
fw_version: "H3.0.1",
hashrate: 92.0,
expected: 96.0,
power: 3400.0,
temp: 70.0,
fan: 4800.0,
worker: "blueflare.h3",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.131",
make: "Whatsminer",
model_id: "M30SPlusVE40",
board: "H616",
firmware: "Hiveon",
fw_version: "1.05",
hashrate: 100.0,
expected: 100.0,
power: 3450.0,
temp: 71.0,
fan: 4900.0,
worker: "blueflare.h616",
mining: true,
paused: false,
},
Board {
ip: "10.255.1.148",
make: "Whatsminer",
model_id: "M50VH50",
board: "H6",
firmware: "Bixbit",
fw_version: "0.9.9.4",
hashrate: 118.0,
expected: 122.0,
power: 3300.0,
temp: 66.0,
fan: 4600.0,
worker: "blueflare.m50",
mining: true,
paused: false,
},
// Rebucketed from idle/not-hashing to paused so the "paused"
// status/KPI bucket is exercisable in the fake-scan/offline demo.
Board { ip: "10.255.1.115", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "Alkane", fw_version: "0.1",
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
worker: "", mining: false, paused: true },
Board {
ip: "10.255.1.115",
make: "Antminer",
model_id: "S19",
board: "BeagleBoneBlack",
firmware: "Alkane",
fw_version: "0.1",
hashrate: 0.0,
expected: 0.0,
power: 0.0,
temp: 0.0,
fan: 0.0,
worker: "",
mining: false,
paused: true,
},
];
boards.into_iter().map(Board::into_row).collect()
}
+2 -3
View File
@@ -27,7 +27,7 @@ impl Lang {
pub fn label(self) -> &'static str {
match self {
Lang::En => "English",
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
Lang::Ru => "\u{0420}\u{0443}\u{0441}\u{0441}\u{043a}\u{0438}\u{0439}", // Русский
Lang::Fr => "Fran\u{e7}ais",
Lang::Es => "Espa\u{f1}ol",
@@ -71,8 +71,7 @@ static CURRENT: AtomicU8 = AtomicU8::new(0);
const LANG_FILE: &str = "language.txt";
fn config_path() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
PathBuf::from(home).join(".config/alkane-toolkit").join(LANG_FILE)
alkane_core::platform::config_path(LANG_FILE)
}
/// Load the saved language into the global (call once at startup).
+10 -3
View File
@@ -32,13 +32,17 @@ pub fn scan_log(ip: &str, brand: &str, timeout_secs: u64) -> Result<LogScan, Str
if brand.eq_ignore_ascii_case("whatsminer") {
let resp = crate::access_probe::whatsminer_get_error_code(ip)
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
return Ok(LogScan { text: tail(&resp, MAX_LOG_BYTES) });
return Ok(LogScan {
text: tail(&resp, MAX_LOG_BYTES),
});
}
let text = crate::scan::fetch_log(ip, timeout_secs)?;
if text.trim().is_empty() {
return Err("the miner returned an empty log".to_string());
}
Ok(LogScan { text: tail(&text, MAX_LOG_BYTES) })
Ok(LogScan {
text: tail(&text, MAX_LOG_BYTES),
})
}
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
@@ -55,7 +59,10 @@ fn tail(s: &str, max: usize) -> String {
start += 1;
}
// then advance to the next line boundary so we don't cut a line in half
let start = s[start..].find('\n').map(|i| start + i + 1).unwrap_or(start);
let start = s[start..]
.find('\n')
.map(|i| start + i + 1)
.unwrap_or(start);
format!("[... earlier log trimmed ...]\n{}", &s[start..])
}
+4 -1
View File
@@ -12,7 +12,10 @@ static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Local wall-clock HH:MM:SS for a log line. Uses the system clock offset from
/// UTC via the TZ-less epoch; good enough for an activity log timestamp.
fn stamp() -> String {
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let t = secs % 86_400;
format!("{:02}:{:02}:{:02}", t / 3600, (t % 3600) / 60, t % 60)
}
+53 -6
View File
@@ -1,13 +1,18 @@
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
//! alkane-toolkit: primary view (docs/UI-SPEC.md).
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
// A GUI application on Windows: no console window opens behind it. The
// headless modes below re-attach to the console they were started from.
#![cfg_attr(windows, windows_subsystem = "windows")]
mod access_probe;
mod askpass;
mod credentials;
mod export;
mod fixtures;
mod i18n;
mod logs;
mod log_scan;
mod logs;
mod model;
mod naming;
mod pool_prefs;
@@ -16,8 +21,16 @@ mod restore;
mod scan;
mod ui;
fn main() {
// ssh runs this executable as its askpass helper for password logins
// (askpass.rs); answer and exit before anything else starts.
if let Some(code) = askpass::serve_if_askpass() {
std::process::exit(code);
}
if headless_mode() {
attach_parent_console();
}
// Headless workflow self-test: render the bench-fleet fixtures through the
// real widgets and check the table + KPIs against the expected hardware
// output. Run under a virtual display (see scripts/ui-selftest.sh).
@@ -61,10 +74,10 @@ fn main() {
// Load the saved UI language before any strings are built (round 15 #13).
i18n::init();
// Bootstrap the wx app + main frame (upstream bridge).
// Bootstrap the wx app + main frame (upstream bridge). This also picks the
// light/dark appearance (system, or ALKANE_APPEARANCE=light|dark) before the
// frame exists, which wxMSW requires.
wx_rs::init_app("alkane-toolkit", 1280, 800);
// Follow the system light/dark appearance.
wx_rs::set_appearance_system();
// Build the UI-SPEC primary view into the frame.
let frame = wx_rs::Widget::main_frame();
@@ -93,3 +106,37 @@ fn run_selftest() -> i32 {
1
}
}
/// True when the process runs one of the headless check modes instead of the GUI.
fn headless_mode() -> bool {
["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"]
.iter()
.any(|v| std::env::var_os(v).is_some())
}
/// A Windows GUI-subsystem process has no console, so output from the headless
/// modes would vanish when they are run from a terminal. Attach to the parent's
/// console in that case. Redirected output (pipes, files, CI) already has valid
/// standard handles and is left alone.
#[cfg(windows)]
fn attach_parent_console() {
type Handle = *mut core::ffi::c_void;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
#[link(name = "kernel32")]
extern "system" {
fn GetStdHandle(which: u32) -> Handle;
fn AttachConsole(process_id: u32) -> i32;
}
// SAFETY: plain Win32 calls with constant arguments; failure (no parent
// console, already attached) is harmless and leaves the process unchanged.
unsafe {
let out = GetStdHandle(STD_OUTPUT_HANDLE);
if out.is_null() || out as isize == -1 {
AttachConsole(ATTACH_PARENT_PROCESS);
}
}
}
#[cfg(not(windows))]
fn attach_parent_console() {}
File diff suppressed because it is too large Load Diff
+68 -17
View File
@@ -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()))
+34 -33
View File
@@ -6,8 +6,6 @@
use std::path::PathBuf;
const CONFIG_DIR: &str = ".config/alkane-toolkit";
/// Which pool field a "+" menu belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolField {
@@ -36,8 +34,20 @@ impl PoolField {
PoolField::Account => Vec::new(),
// Per-miner worker-name placeholders (see MinerRow::expand_worker_template).
PoolField::Worker => vec![
"{ip1}", "{ip2}", "{ip3}", "{ip4}", "{serial}", "{mac}", "{nameplate-hr}",
"{brand}", "{model}", "{submodel}", "{cpu}", "{cb}", "{firmware}", "{hostname}",
"{ip1}",
"{ip2}",
"{ip3}",
"{ip4}",
"{serial}",
"{mac}",
"{nameplate-hr}",
"{brand}",
"{model}",
"{submodel}",
"{cpu}",
"{cb}",
"{firmware}",
"{hostname}",
],
PoolField::Password => vec!["x"],
}
@@ -60,15 +70,20 @@ pub const POOL_STRATUMS: &[(&str, &str)] = &[
];
fn config_path(file: &str) -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
PathBuf::from(home).join(CONFIG_DIR).join(file)
alkane_core::platform::config_path(file)
}
/// The user's saved values for `field`, in save order (most recent last).
pub fn load_saved(field: PoolField) -> Vec<String> {
std::fs::read_to_string(config_path(field.saved_file()))
.ok()
.map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect())
.map(|s| {
s.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(String::from)
.collect()
})
.unwrap_or_default()
}
@@ -88,28 +103,9 @@ pub fn save_all(field: PoolField, values: &[String]) -> std::io::Result<usize> {
Ok(out.len())
}
/// Write `data` to `path` with owner-only (0600) permissions from creation on
/// Unix, so a secret is never momentarily world-readable between write and chmod.
/// `mode()` only takes effect when the file is created, so an already-existing
/// file is also re-tightened; elsewhere this is a plain write.
/// Saved pool values can carry worker passwords, so they are written owner-only.
fn write_private(path: &std::path::Path, data: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
f.write_all(data)
}
#[cfg(not(unix))]
{
std::fs::write(path, data)
}
alkane_core::platform::write_private(path, data)
}
/// Trim every value, then drop empties, values equal to a built-in preset, and
@@ -153,13 +149,18 @@ mod tests {
#[test]
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
let presets = ["x", "{ip1}"];
let vals: Vec<String> = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"]
.iter()
.map(|s| s.to_string())
.collect();
let vals: Vec<String> = [
" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep",
]
.iter()
.map(|s| s.to_string())
.collect();
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
// "keep" all drop; " keep " is trimmed and kept.
assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]);
assert_eq!(
dedupe_saved(&presets, &vals),
vec!["myworker".to_string(), "keep".to_string()]
);
}
#[test]
+20 -4
View File
@@ -43,7 +43,12 @@ impl PresetView {
PresetView {
order: v.order.clone(),
// keep the visible columns in display order for stability
visible: v.order.iter().copied().filter(|c| v.visible.contains(c)).collect(),
visible: v
.order
.iter()
.copied()
.filter(|c| v.visible.contains(c))
.collect(),
sort: v.sort,
filters: v.filters.iter().map(|(k, f)| (*k, f.clone())).collect(),
}
@@ -62,7 +67,12 @@ impl PresetView {
let mut visible: HashSet<Column> = self.visible.iter().copied().collect();
visible.insert(Column::Ip); // IP is always shown
let filters: HashMap<Column, ColFilter> = self.filters.iter().cloned().collect();
ViewState { order, visible, sort: self.sort, filters }
ViewState {
order,
visible,
sort: self.sort,
filters,
}
}
}
@@ -134,8 +144,14 @@ mod tests {
// The Health column (round 13 #3) replaced these in the default profile.
assert!(!view.visible.contains(&Column::Error));
// Columns dropped from the default profile in round 11.
assert!(!view.visible.contains(&Column::BoardCode), "not in the default profile");
assert!(!view.visible.contains(&Column::Fan1), "not in the default profile");
assert!(
!view.visible.contains(&Column::BoardCode),
"not in the default profile"
);
assert!(
!view.visible.contains(&Column::Fan1),
"not in the default profile"
);
// to_view covers every column in `order`.
assert_eq!(view.order.len(), ALL_COLUMNS.len());
// Round-trip a snapshot back out.
+123 -37
View File
@@ -16,16 +16,20 @@
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use std::time::Duration;
use crate::scan::fake_scan_enabled;
pub enum RestoreMsg {
Started,
Result { ip: String, ok: bool, detail: String },
Result {
ip: String,
ok: bool,
detail: String,
},
Done,
}
@@ -87,7 +91,14 @@ pub fn start_restore(
break;
}
let (ok, detail) = restore_one(&t, &vnish_pass, &ssh_user, &ssh_pass);
if tx.send(RestoreMsg::Result { ip: t.ip, ok, detail }).is_err() {
if tx
.send(RestoreMsg::Result {
ip: t.ip,
ok,
detail,
})
.is_err()
{
return;
}
}
@@ -106,7 +117,12 @@ pub fn start_restore(
RestoreHandle { rx, cancel }
}
fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &str) -> (bool, String) {
fn restore_one(
t: &RestoreTarget,
vnish_pass: &str,
ssh_user: &str,
ssh_pass: &str,
) -> (bool, String) {
let fw = t.firmware.to_ascii_lowercase();
if fw.contains("vnish") || fw.contains("wildrose") || fw.contains("anthill") {
restore_vnish(&t.ip, vnish_pass)
@@ -115,7 +131,10 @@ fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &s
} else if fw.contains("braiins") || fw.contains("bos") {
restore_braiins(&t.ip, ssh_user, ssh_pass)
} else {
(false, format!("no restore-to-stock path for firmware '{}'", t.firmware))
(
false,
format!("no restore-to-stock path for firmware '{}'", t.firmware),
)
}
}
@@ -127,9 +146,17 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
let body = serde_json::json!({ "pw": pass }).to_string();
let unlock = match curl(
&[
"-s", "--connect-timeout", "5", "--max-time", "9",
"-X", "POST", "-H", "Content-Type: application/json",
"-d", "@-",
"-s",
"--connect-timeout",
"5",
"--max-time",
"9",
"-X",
"POST",
"-H",
"Content-Type: application/json",
"-d",
"@-",
&format!("http://{ip}/api/v1/unlock"),
],
Some(body.as_bytes()),
@@ -146,8 +173,15 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
};
match curl(
&[
"-s", "--connect-timeout", "5", "--max-time", "12",
"-X", "POST", "-H", &format!("Authorization: Bearer {token}"),
"-s",
"--connect-timeout",
"5",
"--max-time",
"12",
"-X",
"POST",
"-H",
&format!("Authorization: Bearer {token}"),
&format!("http://{ip}/api/v1/firmware/remove"),
],
None,
@@ -174,7 +208,10 @@ fn restore_luxos(ip: &str) -> (bool, String) {
.map(str::to_string)
});
let Some(session) = session.filter(|s| !s.is_empty()) else {
return (false, format!("no SessionID in logon response: {}", logon.trim()));
return (
false,
format!("no SessionID in logon response: {}", logon.trim()),
);
};
// serde-encode so the miner-supplied SessionID can't break or inject into the
// JSON-RPC command (round 18 #12).
@@ -206,22 +243,32 @@ fn restore_luxos(ip: &str) -> (bool, String) {
/// Braiins: SSH `uninstall.sh` (re-flashes the retained on-NAND stock backup).
fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
if pass.is_empty() {
return (false, "Braiins restore needs an SSH password (set the SSH login)".into());
return (
false,
"Braiins restore needs an SSH password (set the SSH login)".into(),
);
}
let target = format!("{user}@{ip}");
// sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it
// never shows up in the process list (round 18 #12). Host-key checking is
// deliberately disabled: these are LAN miners whose SSH host key changes on
// every reflash, so pinning it would break the very revert this performs.
// BatchMode stops any interactive prompt from hanging out the 60 s cap.
let mut cmd = Command::new("sshpass");
cmd.env("SSHPASS", pass);
cmd.arg("-e").arg("ssh");
// The password reaches ssh through the toolkit's own askpass helper (its
// environment, never argv, so it stays out of the process list; round 18
// #12), which works the same with Linux OpenSSH and Windows' ssh.exe. One
// password attempt and no terminal: a bad password fails fast instead of
// hanging out the 60 s cap. Host-key checking is deliberately disabled: these
// are LAN miners whose SSH host key changes on every reflash, so pinning it
// would break the very revert this performs.
let mut cmd = alkane_core::platform::quiet_command("ssh");
if let Err(e) = crate::askpass::ssh_with_password(&mut cmd, pass) {
return (false, e);
}
let known_hosts = format!("UserKnownHostsFile={}", alkane_core::platform::NULL_DEVICE);
cmd.args(crate::askpass::PASSWORD_AUTH_OPTIONS);
cmd.args([
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=8",
"-o",
"StrictHostKeyChecking=no",
"-o",
&known_hosts,
"-o",
"ConnectTimeout=8",
&target,
"uninstall.sh || /sbin/uninstall.sh",
]);
@@ -247,7 +294,12 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be
/// reported as a FAILURE, never a false success. A dropped connection or a
/// timeout after the command started is the expected signature of the reboot.
fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bool) -> (bool, String) {
fn classify_braiins(
stdout: &str,
stderr: &str,
code: Option<i32>,
timed_out: bool,
) -> (bool, String) {
let err = stderr.to_lowercase();
// ssh's own connection/auth failures (exit 255) never reach the remote command.
let conn_fail = [
@@ -264,7 +316,10 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
.any(|m| err.contains(m));
if conn_fail {
let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty());
return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error")));
return (
false,
format!("SSH failed: {}", why.unwrap_or("connection/auth error")),
);
}
let out = stdout.to_lowercase();
if out.contains("not found") || out.contains("no such") || err.contains("not found") {
@@ -273,14 +328,19 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
match code {
Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()),
None => (true, "SSH dropped (miner likely rebooting to stock)".into()),
_ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()),
_ if timed_out => (
true,
"SSH timed out (miner likely rebooting to stock)".into(),
),
Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())),
}
}
/// One luxminer :4028 request/response (line-framed, socket closes after reply).
fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?;
let addr: SocketAddr = format!("{ip}:4028")
.parse()
.map_err(|e| format!("bad addr: {e}"))?;
let t = Duration::from_secs(8);
let mut s = TcpStream::connect_timeout(&addr, t).map_err(|e| e.to_string())?;
s.set_read_timeout(Some(t)).ok();
@@ -300,7 +360,9 @@ fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
Err(_) => break,
}
}
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
Ok(String::from_utf8_lossy(&buf)
.trim_matches('\u{0}')
.to_string())
}
/// The captured result of a timed subprocess run.
@@ -316,7 +378,7 @@ struct CmdOutput {
/// timed out (a black-holed host); otherwise returns stdout even on a non-zero
/// exit (curl prints useful bodies/status on failures).
fn curl(args: &[&str], stdin_data: Option<&[u8]>) -> Result<String, String> {
let mut cmd = Command::new("curl");
let mut cmd = alkane_core::platform::quiet_command("curl");
cmd.args(args);
let out = run_with_timeout(cmd, Duration::from_secs(15), stdin_data)?;
if out.timed_out && out.stdout.is_empty() {
@@ -391,24 +453,45 @@ mod tests {
// The critical regression guard (round 18 #12): a wrong password or an
// unreachable miner writes to stderr, leaves stdout empty, and exits
// non-zero -- it must report failure, never "restored".
let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false);
let (ok, msg) =
classify_braiins("", "Permission denied, please try again.", Some(255), false);
assert!(!ok, "wrong password must not report success");
assert!(msg.to_lowercase().contains("ssh failed"), "{msg}");
let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false);
let (ok, _) = classify_braiins(
"",
"ssh: connect to host 10.0.0.9 port 22: Connection refused",
Some(255),
false,
);
assert!(!ok, "unreachable miner must not report success");
let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false);
let (ok, _) = classify_braiins(
"",
"ssh: Could not resolve hostname miner: Name or service not known",
Some(255),
false,
);
assert!(!ok, "unresolvable host must not report success");
// Genuine outcomes.
let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false);
assert!(ok, "clean exit 0 is success");
let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false);
let (ok, _) = classify_braiins(
"",
"Connection to 10.0.0.5 closed by remote host.",
None,
false,
);
assert!(ok, "connection dropped mid-command (reboot) is success");
let (ok, _) = classify_braiins("", "", None, true);
assert!(ok, "timeout after the command started (reboot) is success");
let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false);
let (ok, _) = classify_braiins(
"bash: uninstall.sh: command not found\n",
"",
Some(127),
false,
);
assert!(!ok, "missing uninstall.sh is a failure");
}
@@ -416,7 +499,10 @@ mod tests {
fn firmware_selects_the_right_flow() {
// The dispatcher only recognises the three revertible aftermarket
// families; anything else has no restore path.
let mk = |fw: &str| RestoreTarget { ip: "0.0.0.0".into(), firmware: fw.into() };
let mk = |fw: &str| RestoreTarget {
ip: "0.0.0.0".into(),
firmware: fw.into(),
};
// Unknown firmware is rejected cleanly (no network attempt in the branch).
let (ok, detail) = restore_one(&mk("Stock"), "", "", "");
assert!(!ok);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
Application manifest for alkane-toolkit.exe (embedded by windows/alkane-toolkit.rc).
- Common Controls v6: themed native controls (Windows 10/11 visual styles)
instead of the Windows 95 look.
- Per-monitor DPI awareness v2: crisp at any scale factor; wx rescales
windows when they move between monitors.
- supportedOS Windows 10/11 (the Rust toolchain's own minimum).
- activeCodePage UTF-8: the C runtime and any narrow-string Win32 call speak
the same UTF-8 the Rust side does.
- longPathAware: settings/export paths beyond MAX_PATH work when enabled.
- asInvoker: never asks for elevation.
-->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="Blueflare.AlkaneToolkit" version="1.0.0.0"
processorArchitecture="amd64"/>
<description>Alkane Toolkit</description>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls"
version="6.0.0.0" processorArchitecture="*"
publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
<activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
</windowsSettings>
</application>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

@@ -0,0 +1,42 @@
// Windows resources for alkane-toolkit.exe, compiled by crates/alkane-gui/build.rs
// with the windres named by `wx-config --rescomp`. ALKANE_VER_* come from the
// crate version (which CI stamps per release).
// wxMSW's own resources (stock cursors and bitmaps). Its built-in manifest is
// suppressed: the application manifest below replaces it.
#define wxUSE_NO_MANIFEST 1
#include "wx/msw/wx.rc"
// The first icon in the file is the one Explorer and the taskbar show.
aaaa ICON "alkane-toolkit.ico"
CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "alkane-toolkit.exe.manifest"
VS_VERSION_INFO VERSIONINFO
FILEVERSION ALKANE_VER_MAJOR, ALKANE_VER_MINOR, ALKANE_VER_PATCH, 0
PRODUCTVERSION ALKANE_VER_MAJOR, ALKANE_VER_MINOR, ALKANE_VER_PATCH, 0
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS 0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "CompanyName", "Blueflare"
VALUE "FileDescription", "Alkane Toolkit"
VALUE "FileVersion", ALKANE_VER_STR
VALUE "InternalName", "alkane-toolkit"
VALUE "LegalCopyright", "Copyright (c) 2026 Blueflare (MIT License)"
VALUE "OriginalFilename", "alkane-toolkit.exe"
VALUE "ProductName", "Alkane Toolkit"
VALUE "ProductVersion", ALKANE_VER_STR
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0409, 1200
END
END
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Regenerate alkane-toolkit.ico (the Windows executable/taskbar icon) from the
# in-repo microchip glyph: a white chip on a rounded amber tile, at the sizes
# Windows asks for (16-256 px). Needs rsvg-convert and ImageMagick; the .ico is
# committed, so a normal build never runs this.
set -e
cd "$(dirname "$0")"
GLYPH=../assets/icons/microchip-solid-full.svg
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' 0
sed 's/currentColor/#ffffff/g; s/<svg /<svg fill="#ffffff" /' "$GLYPH" > "$TMP/glyph.svg"
for s in 16 20 24 32 40 48 64 256; do
r=$((s * 22 / 100)); g=$((s * 64 / 100)); o=$(((s - g) / 2))
rsvg-convert -w "$g" -h "$g" "$TMP/glyph.svg" -o "$TMP/g$s.png"
convert -size "${s}x${s}" xc:none -fill '#d9822b' \
-draw "roundrectangle 0,0 $((s - 1)),$((s - 1)) $r,$r" \
"$TMP/g$s.png" -geometry "+$o+$o" -composite "PNG32:$TMP/i$s.png"
done
convert "$TMP"/i16.png "$TMP"/i20.png "$TMP"/i24.png "$TMP"/i32.png "$TMP"/i40.png \
"$TMP"/i48.png "$TMP"/i64.png "$TMP"/i256.png alkane-toolkit.ico
echo "wrote $(pwd)/alkane-toolkit.ico"
+48
View File
@@ -0,0 +1,48 @@
# ADR 0004: Windows port
Date: 2026-11-02
## Context
The GUI is wxWidgets through the patched `wx-rs` bridge (ADR 0002), so most
of it is portable, but the patches and the app had only ever run on GTK. The
Windows build has to look and behave like a native Windows 10/11 application,
ship from the same CI as Linux, and stay maintainable for a team that develops
on Linux.
## Decision
- Build on Linux: cross-compile with mingw-w64 (posix threads) against the
vendored wxWidgets built as static wxMSW (`scripts/build-wx-windows.sh`).
The `wx-rs` build script now picks the platform from `CARGO_CFG_TARGET_*`
(a build script's `cfg!()` describes the host) and builds Windows/GNU through
`wx-config` exactly like GTK. The C++ runtime is linked statically; the
`.exe` imports only Windows system DLLs.
- Native look comes from wxMSW plus an application manifest
(`crates/alkane-gui/windows/`): Common Controls v6, per-monitor DPI
awareness v2, UTF-8 code page, Windows 10/11 compatibility, icon and
version resources. Light/dark follows the Windows app mode.
- Platform code is contained: OS differences in Rust live in
`alkane_core::platform` (config directory, owner-only secret files, null
device, console-less child processes); in C++ they are `#ifdef __WXMSW__` /
`__WXGTK__` sections of the bridge, with shared logic (icon hit-testing) in
plain functions both use.
- Sizes cross the Rust/C++ boundary in DIPs, converted per window with
`FromDIP`/`ToDIP`. That is the identity on GTK, so Linux output is unchanged.
- SSH password logins use `SSH_ASKPASS` with the toolkit's own executable as
the helper, on every platform, replacing `sshpass` (absent on Windows).
- CI tests the Windows build under Wine on the existing Linux runners (the
release gate), and again on real Windows 11 through a self-hosted VM runner
(advisory, never blocking).
- The `wx-rs` patch queue must reproduce the patched tree from the pristine
upstream crate; `scripts/wx_rs_patches.py check` enforces it in CI.
## Consequences
- One toolchain and one CI fleet for both platforms; no Windows build machine.
- Wine is a good but not perfect stand-in for Windows; the native VM job
covers the gap without making releases depend on the VM being up.
- Bridge changes need checking on both toolkits: GTK uses the native tree
view, wxMSW the generic data view, which differ in input routing, painting
and selection style (see docs/windows.md).
- macOS remains out of scope (no Mac to build or test on).
+83
View File
@@ -0,0 +1,83 @@
# 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.
## Native Windows runner
`windows-native.yml` runs on the self-hosted runner `win11-test-vm`
(label `alkane-windows`, host mode) inside the Windows 11 test VM
(a local test VM). It downloads the
`alkane-toolkit-windows-tests` artifact of the triggering main run, runs every
test executable and the UI self-test natively, and never blocks a release:
while the VM is off, the job waits for the runner.
In the VM, `gitea-runner` v3.5.0 lives in `C:\gitea-runner` and starts at boot
as the scheduled task `gitea-runner`, running as `LOCAL SERVICE` (log:
`C:\gitea-runner\runner.log`).
## Differences from Linux worth knowing
- wxMSW's `wxDataViewCtrl` is wx's generic implementation (GTK uses the native
`GtkTreeView`), so drag-select and per-cell tooltips are implemented in the
bridge for it.
- Selected rows use the Windows 10/11 list-view highlight: a light tint under
normal text, not a solid colour with white text.
- The app is per-monitor DPI aware: the bridge converts every size it gets
from Rust from DIPs to physical pixels for the window it applies to.
+22 -18
View File
@@ -1,22 +1,26 @@
#!/bin/sh
# Build the alkane-toolkit GUI for Windows (x86_64) from Linux, via mingw-w64.
# wx-rs upstream supports MSW (it downloads and builds wx 3.2.2.1 with MSVC
# via nmake, or links an msys2 mingw64 wx). Two supported routes:
# Build the alkane-toolkit GUI for Windows (x86_64) on Linux by cross-compiling
# with mingw-w64 against the vendored wxWidgets 3.3.3 (wxMSW), the same way CI
# builds the release .exe. The result is one self-contained executable: the C++
# runtime is linked statically and it imports only DLLs Windows itself ships.
#
# A) On Windows: install msys2/mingw64 wx + rust-gnu, run `cargo build
# --release -p alkane-gui` there (wx-rs build.rs handles msys2 paths).
# B) Cross from Linux: not automated yet - wxMSW needs the MSVC or msys2
# toolchain; tracked as follow-up. The Rust side cross-compiles fine;
# only the C++ bridge + wx need the Windows toolchain.
#
# This script documents route A and fails here if run on Linux.
# Usage: scripts/build-gui-windows.sh [cargo build args...]
# defaults to `--release`; e.g. `scripts/build-gui-windows.sh` or
# `scripts/build-gui-windows.sh --profile dev`.
# Needs: mingw-w64 (posix-threads variant), the rustup target
# x86_64-pc-windows-gnu, and the wxMSW prefix from build-wx-windows.sh
# (built on first use).
set -e
if [ "$(uname -s)" = "Linux" ]; then
echo "Route B (Linux cross to MSW) is not automated yet."
echo "Run scripts/build-gui-windows.sh on Windows (msys2 mingw64 + rust),"
echo "or use CI with a Windows runner."
exit 1
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$REPO"
. "$REPO/scripts/windows-cross-env.sh"
if [ ! -x "$WX_RS_WXCONFIG" ]; then
sh "$REPO/scripts/build-wx-windows.sh"
fi
cd "$(dirname -- "$0")/.."
cargo build --release -p alkane-gui
echo "binary: target/release/alkane-toolkit.exe"
rustup target list --installed 2>/dev/null | grep -qx "$ALKANE_WIN_TARGET" ||
rustup target add "$ALKANE_WIN_TARGET"
[ "$#" -gt 0 ] || set -- --release
cargo build --offline --target "$ALKANE_WIN_TARGET" -p alkane-gui "$@"
TDIR=$(cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \
| tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4)
echo "binary: ${TDIR:-$REPO/target}/$ALKANE_WIN_TARGET/<profile>/alkane-toolkit.exe"
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# Cross-build the vendored wxWidgets 3.3.3 for Windows (wxMSW, x86_64, static,
# monolithic) from Linux with mingw-w64. Mirrors build-wx-linux.sh: the repo
# tree stays pristine, the build lives in ~/.cache/wxbuild, and the result is a
# prefix whose bin/wx-config the wx-rs build script reads (WX_RS_WXCONFIG).
#
# Every third-party library wx needs is the copy bundled in the wx source tree
# ("builtin"), so the prefix needs nothing from the build host and the final
# .exe needs no DLLs beyond the ones Windows itself ships. TIFF and WebP are
# off: the app never loads either format.
#
# Needs: mingw-w64 (the posix-threads g++ variant), make.
set -e
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3"
HOST=x86_64-w64-mingw32
BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3-mingw"
PREFIX="${WX_WINDOWS_PREFIX:-$HOME/.cache/wx-3.3.3-mingw}"
# std::thread/std::mutex need the posix thread model; Debian's default
# x86_64-w64-mingw32-g++ alternative is the win32 model.
CC="${WX_WINDOWS_CC:-$HOST-gcc-posix}"
CXX="${WX_WINDOWS_CXX:-$HOST-g++-posix}"
command -v "$CXX" >/dev/null || { echo "$CXX not found (apt install mingw-w64)"; exit 1; }
cleanup_wx_build() {
python3 - "$BUILD" "$HOME/.cache/wxbuild" <<'PY'
from pathlib import Path
import shutil
import sys
build, parent = map(Path, sys.argv[1:])
if (build.name != "wxWidgets-3.3.3-mingw" or build.parent != parent
or build.is_symlink() or parent.is_symlink()):
raise SystemExit("refusing unsafe wxWidgets build cleanup path")
if build.is_dir():
shutil.rmtree(build)
PY
}
trap cleanup_wx_build 0
[ -d "$SRC" ] || { echo "thirdparty wxWidgets tree missing"; exit 1; }
[ -d "$BUILD" ] || { mkdir -p "$HOME/.cache/wxbuild"; cp -r "$SRC" "$BUILD"; }
chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true
mkdir -p "$BUILD/build-msw"
cd "$BUILD/build-msw"
# --enable-unicode is the 3.3 default. wxUSE_RC_MANIFEST/DPI awareness are
# handled by the application's own resource script (crates/alkane-gui/build.rs),
# not here, so the library stays policy-free.
sh ../configure --host="$HOST" --build="$(sh ../config.guess)" \
--prefix="$PREFIX" CC="$CC" CXX="$CXX" \
--disable-shared --enable-monolithic --with-msw \
--with-opengl=no --disable-stc --disable-tests --disable-webview \
--with-libpng=builtin --with-libjpeg=builtin --with-regex=builtin \
--with-zlib=builtin --with-expat=builtin \
--without-libtiff --without-libwebp --without-liblzma
make -j"${WX_BUILD_JOBS:-$(nproc)}"
make install
ls "$PREFIX"/lib/libwx_mswu-3.3-"$HOST".a >/dev/null
echo "installed: $PREFIX ($("$PREFIX/bin/wx-config" --version) $("$PREFIX/bin/wx-config" --selected-config))"
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# Headless UI workflow self-test of the WINDOWS build, under Wine on a private
# Xvfb display: the same ALKANE_SELFTEST check as scripts/ui-selftest.sh (bench
# fixtures rendered through the real wxMSW widgets, read back, and compared),
# run against alkane-toolkit.exe. CI runs this on every build; the native
# Windows smoke job (.gitea/workflows/windows-native.yml) repeats it on real
# Windows.
#
# Usage: scripts/ui-selftest-windows.sh [alkane-toolkit.exe]
# defaults to the cross-built release binary in the cargo target dir.
set -u
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
EXE="${1:-}"
if [ -z "$EXE" ]; then
sh "$REPO/scripts/build-gui-windows.sh" || exit 3
TDIR=$(cd "$REPO" && cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \
| tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4)
EXE="${TDIR:-$REPO/target}/x86_64-pc-windows-gnu/release/alkane-toolkit.exe"
fi
[ -f "$EXE" ] || { echo "executable not found: $EXE" >&2; exit 3; }
# xvfb-run picks a free display and cleans it up; Wine needs an X server for
# the window even though the self-test never shows it to anyone.
xvfb-run -a -s '-screen 0 1280x850x24' \
env ALKANE_SELFTEST=1 sh "$REPO/scripts/wine-run.sh" "$EXE"
RC=$?
echo "== ui-selftest-windows exit=$RC =="
exit "$RC"
+38
View File
@@ -0,0 +1,38 @@
# shellcheck shell=sh
# Toolchain environment for cross-building the toolkit for Windows
# (x86_64-pc-windows-gnu) on Linux. One definition, used by
# scripts/build-gui-windows.sh locally and by the CI Windows job:
#
# . scripts/windows-cross-env.sh # export into this shell
# sh scripts/windows-cross-env.sh --github-env # append to $GITHUB_ENV
#
# WX_WINDOWS_PREFIX selects the wxMSW prefix built by build-wx-windows.sh.
# `cargo test --target x86_64-pc-windows-gnu` runs the test .exe files through
# scripts/wine-run.sh, so the Windows build is unit-tested on every Linux host.
# The posix-threads mingw variants are required: libstdc++'s std::thread and
# the wx build both use them, and mixing in the win32-thread variant at link
# time fails on missing pthread symbols.
WX_WINDOWS_PREFIX="${WX_WINDOWS_PREFIX:-$HOME/.cache/wx-3.3.3-mingw}"
ALKANE_WIN_TARGET=x86_64-pc-windows-gnu
# Sourced scripts cannot rely on $0, so locate the checkout through git.
ALKANE_REPO="${ALKANE_REPO:-$(git rev-parse --show-toplevel)}"
_alkane_win_env() {
cat <<EOF
WX_WINDOWS_PREFIX=$WX_WINDOWS_PREFIX
WX_RS_WXCONFIG=$WX_WINDOWS_PREFIX/bin/wx-config
ALKANE_WIN_TARGET=$ALKANE_WIN_TARGET
CC_x86_64_pc_windows_gnu=x86_64-w64-mingw32-gcc-posix
CXX_x86_64_pc_windows_gnu=x86_64-w64-mingw32-g++-posix
AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc-posix
WINDRES=x86_64-w64-mingw32-windres
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=$ALKANE_REPO/scripts/wine-run.sh
EOF
}
if [ "${1:-}" = "--github-env" ]; then
_alkane_win_env >> "${GITHUB_ENV:?GITHUB_ENV is required}"
else
eval "$(_alkane_win_env | sed 's/^/export /')"
fi
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Cargo target runner for x86_64-pc-windows-gnu: run a Windows .exe under Wine.
# Set via CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER (scripts/windows-cross-env.sh).
# A private, reusable Wine prefix keeps runs isolated from any desktop Wine
# setup and avoids re-creating the prefix (~10 s) for every test binary.
set -e
export WINEPREFIX="${ALKANE_WINEPREFIX:-$HOME/.cache/alkane-wine}"
export WINEDEBUG="${WINEDEBUG:--all}"
# No Wine menu entries/file associations, no Gecko/Mono install prompts.
export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-winemenubuilder.exe=d;mscoree=d;mshtml=d}"
WINE="${WINE:-$(command -v wine64 || command -v wine)}"
if [ ! -f "$WINEPREFIX/system.reg" ]; then
mkdir -p "$WINEPREFIX"
# The registry (system.reg, the "prefix is ready" marker) is only written
# when the wine server shuts down, so finish the boot explicitly.
"$WINE" wineboot --init >/dev/null 2>&1 || true
"$WINE" wineboot --shutdown >/dev/null 2>&1 || true
wineserver -w 2>/dev/null || true
fi
exec "$WINE" "$@"
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Keep thirdparty/wx-rs/patches/ an exact recipe for the patched wx-rs tree.
The patched crate (thirdparty/wx-rs/wx-rs-0.2.0-patched) is what cargo builds;
the numbered patches are how a reviewer or an upstream bump reproduces it from
the pristine crates.io tarball (thirdparty/wx-rs/upstream/, digest pinned in
thirdparty/wx-rs/VERSION). The two drift apart whenever someone edits the tree
and forgets the patch, so:
wx_rs_patches.py check
Unpack the upstream crate, apply every patch in order (no fuzz), and
require the result to equal the patched tree byte for byte. Offline; CI
runs it on every bridge change.
wx_rs_patches.py capture NNNN-short-name "Subject line" [PATH ...]
Write the difference between (upstream + current queue) and the patched
tree as the next patch, optionally limited to PATHs, then re-check.
Workflow: edit the patched tree, build/test, capture, commit both.
"""
import argparse
import hashlib
import shutil
import subprocess
import sys
import tarfile
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
WXRS = ROOT / "thirdparty/wx-rs"
PATCHED = WXRS / "wx-rs-0.2.0-patched"
PATCHES = WXRS / "patches"
CRATE = WXRS / "upstream/wx-rs-0.2.0.crate"
# Build products and the wx source download cache are never part of the recipe.
IGNORED = {"target", "dist"}
def pinned_digest() -> str:
for line in (WXRS / "VERSION").read_text().splitlines():
if line.startswith("sha256:"):
return line.split()[1]
sys.exit("thirdparty/wx-rs/VERSION has no sha256 line")
def unpack_upstream(dest: Path) -> Path:
data = CRATE.read_bytes()
if hashlib.sha256(data).hexdigest() != pinned_digest():
sys.exit(f"{CRATE.relative_to(ROOT)} does not match the pinned sha256")
with tarfile.open(CRATE) as tar:
tar.extractall(dest, filter="data")
tree = dest / "wx-rs-0.2.0"
if not tree.is_dir():
sys.exit("upstream crate did not unpack to wx-rs-0.2.0/")
return tree
def patch_files() -> list:
return sorted(PATCHES.glob("[0-9][0-9][0-9][0-9]-*.patch"))
def apply_queue(tree: Path) -> None:
for patch in patch_files():
result = subprocess.run(
["patch", "-p1", "-s", "-F0", "--no-backup-if-mismatch", "-i", str(patch)],
cwd=tree, capture_output=True, text=True)
if result.returncode != 0:
sys.exit(f"{patch.name} does not apply cleanly:\n{result.stdout}{result.stderr}")
def copy_patched(dest: Path) -> Path:
tree = dest / "b"
shutil.copytree(PATCHED, tree, ignore=lambda d, names: [
n for n in names if Path(d) == PATCHED and n in IGNORED])
return tree
def unified_diff(work: Path, paths: list) -> str:
"""diff -ruN a b, run from `work` so headers read a/<path> and b/<path>."""
targets = [(f"a/{p}", f"b/{p}") for p in paths] if paths else [("a", "b")]
out = []
for left, right in targets:
result = subprocess.run(["diff", "-ruN", left, right], cwd=work,
capture_output=True, text=True)
if result.returncode > 1:
sys.exit(result.stderr)
out.append(result.stdout)
# Drop the mtimes diff appends to ---/+++ headers so a regenerated patch
# only changes when its content does.
return "".join(
line.split("\t", 1)[0] + "\n" if line.startswith(("--- ", "+++ ")) else line
for line in "".join(out).splitlines(keepends=True))
def prepare(work: Path) -> None:
unpack_upstream(work).rename(work / "a")
apply_queue(work / "a")
copy_patched(work)
def check() -> int:
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
prepare(work)
drift = unified_diff(work, [])
if drift:
print("wx-rs patch queue does not reproduce the patched tree;", file=sys.stderr)
print("capture the change with scripts/wx_rs_patches.py capture:", file=sys.stderr)
print(drift[:4000], file=sys.stderr)
return 1
print(f"wx-rs patch queue OK ({len(patch_files())} patches reproduce the tree)")
return 0
def capture(name: str, subject: str, paths: list) -> int:
existing = patch_files()
number = int(existing[-1].name[:4]) + 1 if existing else 1
if not name[:4].isdigit():
name = f"{number:04d}-{name}"
target = PATCHES / (name if name.endswith(".patch") else name + ".patch")
if target.exists():
sys.exit(f"{target.name} already exists")
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
prepare(work)
body = unified_diff(work, paths)
if not body:
sys.exit("nothing to capture: the queue already reproduces the tree")
target.write_text(f"Subject: [PATCH {target.name[:4]}] {subject}\n\n{body}")
print(f"wrote {target.relative_to(ROOT)}")
return check()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("check")
cap = sub.add_parser("capture")
cap.add_argument("name")
cap.add_argument("subject")
cap.add_argument("paths", nargs="*")
args = parser.parse_args()
if args.cmd == "check":
return check()
return capture(args.name, args.subject, args.paths)
if __name__ == "__main__":
sys.exit(main())
+4 -2
View File
@@ -4,5 +4,7 @@ source_url: https://static.crates.io/crates/wx-rs/wx-rs-0.2.0.crate
sha256: b70620dba2997db6640794ef43fa130d19b9a2ec1ab93925450a5b8334d99e33
state: patched tree is the used crate (path dep from crates/alkane-gui).
Upstream stubs non-Windows/macOS and has no widget surface; patches add
the Linux/GTK3 wx-config build path and the widget bridge (see patches/).
Update flow: unpack new upstream here, re-apply patches/, resolve, commit.
the wx-config build path (Linux/GTK3 and Windows/mingw wxMSW) and the
widget bridge (see patches/README.md). upstream/ holds the pristine crate.
Update flow: replace upstream/, re-apply patches/ (scripts/wx_rs_patches.py
check shows what no longer applies), resolve, capture, commit.
+33 -7
View File
@@ -1,3 +1,5 @@
Subject: [PATCH 0002] widget/event bridge, Rust side
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3,3 +3,7 @@
@@ -10,7 +12,7 @@
+pub use widgets::*;
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -0,0 +1,911 @@
@@ -0,0 +1,935 @@
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
+// wxWidgets object tree (parents own children; nothing to free in Rust).
@@ -20,6 +22,11 @@
+use std::ffi::CString;
+use std::os::raw::{c_char, c_int, c_long, c_void};
+
+/// Column alignment for `dvlc_append_text_col` / `dvlc_append_colored_col`.
+pub const ALIGN_LEFT: i32 = 0;
+pub const ALIGN_RIGHT: i32 = 1;
+pub const ALIGN_CENTER: i32 = 2;
+
+mod notsafe {
+ use std::os::raw::{c_char, c_int, c_long, c_void};
+
@@ -49,6 +56,7 @@
+ pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
+ pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
+ pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
+ pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
+ pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
+ pub fn wxbr_text_ctrl_write(win: *mut c_void, value: *const c_char);
@@ -68,8 +76,8 @@
+ pub fn wxbr_file_dialog(parent: *mut c_void, title: *const c_char, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_save_file_dialog(parent: *mut c_void, title: *const c_char, default_name: *const c_char, wildcard: *const c_char, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_dvlc(parent: *mut c_void) -> *mut c_void;
+ pub fn wxbr_dvlc_append_text_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int);
+ pub fn wxbr_dvlc_append_colored_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int) -> *mut c_void;
+ pub fn wxbr_dvlc_append_text_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int, align: c_int);
+ pub fn wxbr_dvlc_append_colored_col(win: *mut c_void, title: *const c_char, width: c_int, reorderable: c_int, align: c_int) -> *mut c_void;
+ pub fn wxbr_dvlc_append_toggle_col(win: *mut c_void, width: c_int);
+ pub fn wxbr_dvlc_append_row(win: *mut c_void, nvals: c_int, vals: *const *const c_char);
+ pub fn wxbr_dvlc_delete_row(win: *mut c_void, row: usize);
@@ -81,6 +89,7 @@
+ pub fn wxbr_dvlc_get_cell(win: *mut c_void, row: usize, col: usize, buf: *mut c_char, cap: c_int) -> c_int;
+ pub fn wxbr_dvlc_col_count(win: *mut c_void) -> c_int;
+ pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
+ pub fn wxbr_dvlc_autosize_col_capped(win: *mut c_void, pos: c_int, cap_px: c_int);
+ pub fn wxbr_dvlc_set_col_title(win: *mut c_void, col: c_int, title: *const c_char);
+ pub fn wxbr_dvlc_set_sort_indicator(win: *mut c_void, col: c_int, active: c_int, ascending: c_int);
+ pub fn wxbr_dvlc_col_at_pos(win: *mut c_void, pos: c_int) -> c_int;
@@ -450,6 +459,11 @@
+ Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
+ }
+
+ /// A single-line text control that masks its content (for password entry).
+ pub fn password_ctrl(parent: Widget) -> Widget {
+ Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
+ }
+
+ pub fn get_value(&self) -> String {
+ let mut buf = vec![0i8; 65536];
+ let n = unsafe { notsafe::wxbr_text_ctrl_get(self.0, buf.as_mut_ptr(), buf.len() as c_int) };
@@ -583,17 +597,23 @@
+ Widget(unsafe { notsafe::wxbr_dvlc(parent.0) })
+ }
+
+ pub fn dvlc_append_text_col(&self, title: &str, width: i32, reorderable: bool) {
+ /// Append a text column. `align` is the cell + header alignment:
+ /// [`ALIGN_LEFT`] (0), [`ALIGN_RIGHT`] (1) or [`ALIGN_CENTER`] (2).
+ pub fn dvlc_append_text_col(&self, title: &str, width: i32, reorderable: bool, align: i32) {
+ let c = CString::new(title).unwrap_or_default();
+ unsafe { notsafe::wxbr_dvlc_append_text_col(self.0, c.as_ptr(), width, reorderable as c_int) }
+ unsafe {
+ notsafe::wxbr_dvlc_append_text_col(self.0, c.as_ptr(), width, reorderable as c_int, align)
+ }
+ }
+
+ /// Like `dvlc_append_text_col`, but the column renders cell values through
+ /// the SegmentRenderer, so a value built with `model::encode_segments` is
+ /// drawn as coloured text runs (a plain string still renders normally).
+ pub fn dvlc_append_colored_col(&self, title: &str, width: i32, reorderable: bool) {
+ pub fn dvlc_append_colored_col(&self, title: &str, width: i32, reorderable: bool, align: i32) {
+ let c = CString::new(title).unwrap_or_default();
+ unsafe { notsafe::wxbr_dvlc_append_colored_col(self.0, c.as_ptr(), width, reorderable as c_int) };
+ unsafe {
+ notsafe::wxbr_dvlc_append_colored_col(self.0, c.as_ptr(), width, reorderable as c_int, align)
+ };
+ }
+
+ pub fn dvlc_append_toggle_col(&self, width: i32) {
@@ -660,6 +680,12 @@
+ unsafe { notsafe::wxbr_dvlc_autosize_col(self.0, pos as c_int) }
+ }
+
+ /// Size the column at display position `pos` to its content, then clamp to
+ /// `cap_px`: the width becomes min(cap, content-fit) (round 18 #10).
+ pub fn dvlc_autosize_col_capped(&self, pos: usize, cap_px: i32) {
+ unsafe { notsafe::wxbr_dvlc_autosize_col_capped(self.0, pos as c_int, cap_px) }
+ }
+
+ /// Model column index shown at display position `pos` (after drag reorder).
+ pub fn dvlc_col_at_pos(&self, pos: usize) -> Option<usize> {
+ let v = unsafe { notsafe::wxbr_dvlc_col_at_pos(self.0, pos as c_int) };
+115 -17
View File
@@ -1,6 +1,8 @@
Subject: [PATCH 0003] widget/event bridge, C++ side
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -0,0 +1,2053 @@
@@ -0,0 +1,2149 @@
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
+// render-callback bridge (which is kept untouched).
@@ -338,15 +340,32 @@
+ if (h < 8) h = 8;
+ int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h;
+ if (w < 1) w = 1;
+ const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, w, h);
+ // The Font Awesome fan and brain glyphs fill their square box more than the
+ // other health icons (chip/bolt), so at the shared size they read as oversized.
+ // Draw them a bit smaller, centred in their full-size slot, so the slot advance
+ // and the per-icon tooltip hit-test (both keyed to the full width) are
+ // unchanged (round 17 R1; round 18 #1 brain).
+ int dw = w, dh = h;
+ double glyph_scale = (shape == SHAPE_FAN) ? 0.80 : (shape == SHAPE_BRAIN) ? 0.82 : 1.0;
+ if (glyph_scale < 1.0) {
+ dh = (int)(h * glyph_scale + 0.5);
+ if (dh < 8) dh = 8;
+ dw = (sv->vbh > 0) ? (int)((double)dh * sv->vbw / sv->vbh + 0.5) : dh;
+ if (dw < 1) dw = 1;
+ }
+ const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, dw, dh);
+ if (bmp.IsOk()) {
+ if (health) {
+ // Left-align and advance by less than the icon width so adjacent health
+ // icons sit close together (the Font Awesome glyphs carry inner margin,
+ // so a small bounding-box overlap does not visually collide).
+ dc->DrawBitmap(bmp, x, cy - h / 2, true);
+ int adv = w - 3;
+ return adv < 1 ? 1 : adv;
+ // UNIFORM fixed-width slot (round 19): every health icon (and the
+ // alignment gap) advances by the same amount -- the square (h - 3) -- so
+ // power/control/fan/board icons line up in fixed columns across rows
+ // regardless of each glyph's aspect ratio (a narrow bolt or a shrunk fan
+ // no longer shifts the icons after it). Each glyph is centred in its slot.
+ // This matches SHAPE_GAP's advance and the per-icon tooltip hit-test.
+ int adv = h - 3;
+ if (adv < 1) adv = 1;
+ dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
+ return adv;
+ }
+ int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
+ dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
@@ -441,7 +460,13 @@
+ wxRect bg = cell;
+ if (wxDataViewColumn* owner = const_cast<SegmentRenderer*>(this)->GetOwner()) {
+ int cw = owner->GetWidth();
+ if (cw > bg.width) bg.width = cw;
+ // Extend BOTH directions by the column width. For a right-aligned column
+ // (round 19 #21) wx anchors `cell` at the content's left edge (near the
+ // column's right side), so extending only rightward left the column's left
+ // portion unstriped; over-spanning both sides and letting the cell-DC clip
+ // trim it fills the whole cell regardless of alignment (round 19 review M1).
+ bg.x -= cw;
+ bg.width += 2 * cw;
+ }
+ bg.y -= 40;
+ bg.height += 80;
@@ -524,7 +549,10 @@
+ } else if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
+ int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh;
+ if (health) {
+ adv = ww - 3;
+ // UNIFORM fixed-width slot (round 19), matching DrawShape + the gap, so
+ // every health icon lines up in fixed columns across rows regardless of
+ // its glyph aspect. Width is measured square (hh - 3), not per-glyph.
+ adv = hh - 3;
+ if (adv < 1) adv = 1;
+ } else if (ww > adv) {
+ adv = ww;
@@ -765,6 +793,13 @@
+ wxDefaultPosition, wxSize(-1, -1), style);
+}
+
+// A single-line text control that masks its content (wxTE_PASSWORD), for secret
+// entry so a saved password is never rendered in the clear (round 18 #12).
+void* wxbr_text_ctrl_password(void* parent) {
+ return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
+ wxDefaultPosition, wxSize(-1, -1), wxTE_PASSWORD);
+}
+
+int wxbr_text_ctrl_get(void* win, char* buf, int cap) {
+ wxTextCtrl* t = (wxTextCtrl*)win;
+ wxString v = t->GetValue();
@@ -957,7 +992,10 @@
+ GdkRectangle crect;
+ gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
+ gtk_tree_path_free(path);
+ // Icon advance matches DrawShape's health-icon width (square icons: h - 3).
+ // Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
+ // (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
+ // earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
+ // the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
+ int h = crect.height - 1;
+ int cap = (int)(28 * g_table_zoom + 0.5);
+ if (cap < 8) cap = 8;
@@ -965,13 +1003,45 @@
+ if (h < 8) h = 8;
+ int adv = h - 3;
+ if (adv < 1) adv = 1;
+ int off = bx - crect.x;
+ int n = (int)iit->second.size();
+ // A right-aligned column (round 19 #21) draws the icon block flush to the
+ // cell's right edge, so measure the pointer from the block's left, not the
+ // cell's left.
+ int block_left = crect.x;
+ if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
+ int content_w = n * adv;
+ if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
+ }
+ int off = bx - block_left;
+ if (off < 0) off = 0;
+ int slot = off / adv;
+ if (slot < 0) slot = 0;
+ if (slot >= (int)iit->second.size()) slot = (int)iit->second.size() - 1;
+ if (slot >= n) slot = n - 1;
+ const wxString& tip = iit->second[(size_t)slot];
+ if (tip.IsEmpty()) return FALSE;
+ // Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
+ // Without a tip area GTK defaults it to the whole widget, so it never re-queries
+ // or moves the tooltip as the pointer crosses from one icon to the next -- the
+ // old tooltip just stays put with stale text. Setting a per-slot area makes GTK
+ // hide + re-show + reposition the tooltip for each icon.
+ //
+ // CRITICAL (round 19 #2, the reason the health tooltips never showed): the slot
+ // geometry above (block_left, crect) is in BIN-WINDOW coordinates (what
+ // gtk_tree_view_get_cell_area and get_path_at_pos use), but
+ // gtk_tooltip_set_tip_area expects WIDGET coordinates. Feeding it bin-window
+ // coords offsets the area upward by the header height, so it does not contain
+ // the pointer -- and GTK then suppresses the tooltip entirely (it only shows a
+ // tooltip whose tip area contains the cursor). The Errors column worked because
+ // it sets no tip area. Convert the slot rect back to widget coordinates.
+ gint area_wx = 0, area_wy = 0;
+ gtk_tree_view_convert_bin_window_to_widget_coords(
+ GTK_TREE_VIEW(tv), block_left + slot * adv, crect.y, &area_wx, &area_wy);
+ GdkRectangle area;
+ area.x = area_wx;
+ area.y = area_wy;
+ area.width = adv;
+ area.height = crect.height;
+ gtk_tooltip_set_tip_area(tooltip, &area);
+ gtk_tooltip_set_text(tooltip, tip.utf8_str());
+ return TRUE;
+ }
@@ -1097,14 +1167,23 @@
+ return (void*)dv;
+}
+
+void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable) {
+// Map the bridge alignment code (0 left, 1 right, 2 centre) to a wxAlignment.
+static wxAlignment dvlc_wx_align(int align) {
+ switch (align) {
+ case 1: return wxALIGN_RIGHT;
+ case 2: return wxALIGN_CENTER;
+ default: return wxALIGN_NOT;
+ }
+}
+
+void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reorderable, int align) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ int flags = wxDATAVIEW_COL_RESIZABLE;
+ if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
+ unsigned col = dv->GetColumnCount(); // next model column index
+ dvlc_store(win)->AppendColumn("string");
+ dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
+ width, wxALIGN_NOT, flags);
+ width, dvlc_wx_align(align), flags);
+ // Record the 100% column width for the zoom (round 14 #3); the first column of
+ // a (re)built table resets the list.
+ if (col == 0) g_zoom_base_w.clear();
@@ -1115,15 +1194,17 @@
+// SegmentRenderer so its cell values can carry the '\x1f'/'\x1e' colour-run
+// encoding produced by alkane_gui::model::encode_segments. An ordinary string
+// with no encoding in it still renders fine (single default-coloured run).
+void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable) {
+void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int reorderable, int align) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ int flags = wxDATAVIEW_COL_RESIZABLE;
+ if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
+ unsigned col = dv->GetColumnCount(); // next model column index
+ dvlc_store(win)->AppendColumn("string");
+ SegmentRenderer* renderer = new SegmentRenderer();
+ wxAlignment al = dvlc_wx_align(align);
+ renderer->SetAlignment(al);
+ wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
+ width, wxALIGN_NOT, flags);
+ width, al, flags);
+ dv->AppendColumn(c);
+ // Record the 100% column width for the zoom (round 14 #3).
+ if (col == 0) g_zoom_base_w.clear();
@@ -1269,6 +1350,23 @@
+ if (c) c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
+}
+
+// Size a column to fit its content + header, then clamp to cap_px so the default
+// width is min(reasonable cap, content-fit) -- a short column shrinks to its
+// content, a long one is capped at the caller's sensible default (round 18 #10).
+// A small floor keeps a column from collapsing to nothing.
+void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ if (pos < 0 || (unsigned)pos >= dv->GetColumnCount()) return;
+ wxDataViewColumn* c = dv->GetColumn((unsigned)pos);
+ if (!c) return;
+ c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
+ int w = c->GetWidth();
+ const int floor_px = 24;
+ if (w < floor_px) w = floor_px;
+ if (cap_px > 0 && w > cap_px) w = cap_px;
+ c->SetWidth(w);
+}
+
+// Update a column's header text in place (creation index) without recreating
+// the control -- used to refresh the ASCII sort marker on a sort click.
+void wxbr_dvlc_set_col_title(void* win, int col, const char* title) {
@@ -1,39 +0,0 @@
Subject: [PATCH 0005] health tooltips: convert tip area to widget coordinates
Round 19 #2 (the real fix). The GtkTreeView "query-tooltip" handler for the Health
column set a per-icon tip area from gtk_tree_view_get_cell_area, whose rectangle is
in BIN-WINDOW coordinates, but gtk_tooltip_set_tip_area expects WIDGET coordinates.
The area was therefore offset upward by the column-header height, so it did not
contain the pointer -- and GTK suppresses a tooltip whose tip area excludes the
cursor. That is why the health icon tooltips never appeared, while the Errors column
(which sets no tip area) worked. Convert the slot rectangle back to widget
coordinates with gtk_tree_view_convert_bin_window_to_widget_coords before setting it.
diff --git a/cpp_src/widgets_bridge.cpp b/cpp_src/widgets_bridge.cpp
index ba9f1c04..6d09ccb7 100644
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -1019,9 +1019,21 @@ static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keybo
// or moves the tooltip as the pointer crosses from one icon to the next -- the
// old tooltip just stays put with stale text. Setting a per-slot area makes GTK
// hide + re-show + reposition the tooltip for each icon.
+ //
+ // CRITICAL (round 19 #2, the reason the health tooltips never showed): the slot
+ // geometry above (block_left, crect) is in BIN-WINDOW coordinates (what
+ // gtk_tree_view_get_cell_area and get_path_at_pos use), but
+ // gtk_tooltip_set_tip_area expects WIDGET coordinates. Feeding it bin-window
+ // coords offsets the area upward by the header height, so it does not contain
+ // the pointer -- and GTK then suppresses the tooltip entirely (it only shows a
+ // tooltip whose tip area contains the cursor). The Errors column worked because
+ // it sets no tip area. Convert the slot rect back to widget coordinates.
+ gint area_wx = 0, area_wy = 0;
+ gtk_tree_view_convert_bin_window_to_widget_coords(
+ GTK_TREE_VIEW(tv), block_left + slot * adv, crect.y, &area_wx, &area_wy);
GdkRectangle area;
- area.x = block_left + slot * adv;
- area.y = crect.y;
+ area.x = area_wx;
+ area.y = area_wy;
area.width = adv;
area.height = crect.height;
gtk_tooltip_set_tip_area(tooltip, &area);
+85
View File
@@ -0,0 +1,85 @@
Subject: [PATCH 0005] packaging: document the build-only reqwest; drop the case-duplicate readme.md
diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,6 +39,11 @@
[build-dependencies.embed-resource]
version = "1.3"
+# reqwest is only used by build.rs to download the wxWidgets source on
+# Windows/macOS; on Linux download_dist() returns before touching it, and it is
+# never linked into the runtime binary. Kept at the vendored 0.11 (the build tree
+# is fully vendored / offline); the h2 0.3 advisory it pulls is build-time only
+# and is documented as accepted in audit.toml (RUSTSEC-2026-0258).
[build-dependencies.reqwest]
version = "0.11"
features = ["blocking"]
diff -ruN a/readme.md b/readme.md
--- a/readme.md
+++ b/readme.md
@@ -1,64 +0,0 @@
-# wx-rs
-
-[![Crates.io](https://img.shields.io/crates/v/wx-rs)](https://crates.io/crates/wx-rs)
-[![Docs.rs](https://docs.rs/wx-rs/badge.svg)](https://docs.rs/wx-rs)
-
-*This is an alpha release. Don't expect much from me.*
-
-**Only builds on the MSVC toolchain right now**
-
-An extremely partial set of bindings to wxWidgets, for Rust. The intent is that you can import this and all the bits of wxWidgets provided are statically linked in. Implements [`HasRawWindowHandle`](https://crates.io/crates/raw-window-handle). Callbacks are used for rendering and event handling. Features:
-- Window initialization
-- Keyboard, mouse events
-- Clipboard support
-- Native menus
-- Cursor selection
-
-Some things that'd be great to have:
-- The build script has only been tested on MSVC. Previously I've gotten this to compile on OSX and Windows with the GNU toolchain. There's no reason why this can't work on Linux as well.
-- Icon support for Windows/Linux
-
-
-## Building
-The approach this crate takes is to download wxWidgets into the `./dist` directory, then build it. This means that you need to have a toolchain capable of compiling wxWidgets.
-
-Why are we doing this instead of using submodules? Because with submodules cargo would naturally check out files, but this isn't desirable since we want cargo to ignore these files when packaging (because wxWidgets is huge: The package, when you trim out all non-source files is still around 100MB).
-
-Why do we save/compile to `dist` rather than cargo's preferred `OUT_DIR`? Because with the latter, we'd have to recompile wxWidgets more frequently. Since it takes quite a while to do so, it's much nicer to only have to compile once and then have the artifact around forever.
-
-If you want to do a fresh install, just `rm -R ./dist`.
-
-# Building wxWidgets
-
-## Windows
-
-### Using the MSVC toolchain
-
-Make sure you're using ""x64 Native Tools Command Prompt for VS 2019"", and that cargo is in your path when compiling for the first time. After it's built, msys works fine to continue building things from the Rust side.
-- https://stackoverflow.com/questions/11065421/command-prompt-wont-change-directory-to-another-drive
-
-### Using the GNU toolchain on Windows
-This depends on nightly rust to build correctly
-
-#### Getting MSYS2
-https://www.msys2.org/
-
-```
-$ pacman -Syu
-$ pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-make mingw-w64-x86_64-libexpat mingw-w64-x86_64-zlib msys2-w32api-runtime pacman -S mingw-w64-x86_64-lld
-```
-
-#### Building
-This is a note of what needs to be integrated into the build script.
-
-In a MSYS2 MinGW64 terminal:
-
-```
-$ cd dist/wxWidgets
-$ mkdir msw64-release-build
-$ ../configure --with-opengl --disable-shared
-$ make -j20
-```
-
-### Using the OSX toolchain
-... why aren't I documented? :(
@@ -0,0 +1,180 @@
Subject: [PATCH 0006] build.rs: pick the platform from the target, not the build host; build Windows/GNU (mingw wxMSW) through wx-config like GTK
--- a/build.rs
+++ b/build.rs
@@ -12,22 +12,42 @@
const WX_SOURCE: &str =
"https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.2.1/wxWidgets-3.2.2.1.tar.bz2";
+// alkane-toolkit patch: decide the platform from the TARGET. A build script is
+// compiled for and runs on the build host, so `cfg!(windows)` etc. here describe
+// the host -- which made a Linux -> Windows cross build take the GTK path.
+// Cargo exposes the real target through CARGO_CFG_TARGET_* instead.
+fn target_os() -> String {
+ env::var("CARGO_CFG_TARGET_OS").unwrap_or_default()
+}
+
+fn target_env() -> String {
+ env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default()
+}
+
fn is_windows() -> bool {
- cfg!(windows)
+ target_os() == "windows"
}
fn is_msvc() -> bool {
- cfg!(target_env = "msvc")
+ is_windows() && target_env() == "msvc"
}
fn is_osx() -> bool {
- cfg!(target_os = "macos")
+ target_os() == "macos"
}
// alkane-toolkit patch: real wxGTK3 support on Linux via wx-config
// (upstream stubbed every non-Windows/macOS target).
fn is_linux() -> bool {
- cfg!(target_os = "linux")
+ target_os() == "linux"
+}
+
+// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
+// mingw-w64, natively or cross from Linux) both build against a wx prefix
+// described by its wx-config script, so they share one code path. Upstream's
+// MSVC/nmake and macOS download-and-build paths are left as they were.
+fn uses_wx_config() -> bool {
+ is_linux() || (is_windows() && !is_msvc())
}
fn is_stub() -> bool {
@@ -41,8 +61,8 @@
if is_stub() {
return Ok(());
}
- if is_linux() {
- return Ok(()); // libs are linked inside build_linux()
+ if uses_wx_config() {
+ return Ok(()); // libs are linked inside build_with_wx_config()
}
let wx_libs = get_libs(&wx_path)?;
@@ -89,7 +109,7 @@
fn download_dist() -> Result<PathBuf, Box<dyn Error>> {
let dist_path = Path::new("./dist/");
let wx_path = PathBuf::from(format!("./dist/{}", WX_PATH));
- if wx_path.exists() || is_stub() || is_linux() {
+ if wx_path.exists() || is_stub() || uses_wx_config() {
return Ok(wx_path);
}
println!("cargo:warning=wx-rs: Downloading source to './dist/");
@@ -120,8 +140,8 @@
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
- if is_linux() {
- return build_linux();
+ if uses_wx_config() {
+ return build_with_wx_config();
}
if is_windows() {
@@ -232,25 +252,27 @@
)?)
}
-fn build_linux() -> Result<(), Box<dyn Error>> {
- // alkane-toolkit patch: GTK3 build driven entirely by wx-config, so the
- // same code builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG
- // pointing at its prefix) or any system wxGTK3.
+fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
+ // alkane-toolkit patch: build driven entirely by wx-config, so the same code
+ // builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG pointing at its
+ // GTK or mingw prefix) or any system wx. wx-config is a POSIX shell script;
+ // cross builds run it on the Linux host, native mingw builds under MSYS2.
+ println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| String::from("wx-config"));
- let cxxflags = String::from_utf8(
- Command::new(&wxconfig).arg("--cxxflags").output()?.stdout,
- )?;
- let libs = String::from_utf8(Command::new(&wxconfig).arg("--libs").output()?.stdout)?;
- // The widget bridge uses GTK directly (zebra-striping CSS), so add GTK's own
- // include paths. Best-effort: if pkg-config or gtk3-dev is missing the flags
- // are simply empty and the GTK-only code stays disabled.
- let gtk_cflags = Command::new("pkg-config")
- .args(["--cflags", "gtk+-3.0"])
- .output()
- .ok()
- .filter(|o| o.status.success())
- .and_then(|o| String::from_utf8(o.stdout).ok())
- .unwrap_or_default();
+ let wx_config = |arg: &str| -> Result<String, Box<dyn Error>> {
+ let out = Command::new(&wxconfig).arg(arg).output().map_err(|e| {
+ format!("wx-rs: cannot run {wxconfig} {arg} (set WX_RS_WXCONFIG): {e}")
+ })?;
+ if !out.status.success() {
+ return Err(format!("wx-rs: {wxconfig} {arg} failed").into());
+ }
+ Ok(String::from_utf8(out.stdout)?)
+ };
+ let cxxflags = wx_config("--cxxflags")?;
+ let libs = wx_config("--libs")?;
+ if is_windows() && !cxxflags.contains("__WXMSW__") {
+ return Err(format!("wx-rs: {wxconfig} is not a wxMSW build").into());
+ }
let mut build = cc::Build::new();
build.cpp(true)
@@ -259,15 +281,37 @@
for f in cxxflags.split_whitespace() {
build.flag(f);
}
- for f in gtk_cflags.split_whitespace() {
- build.flag(f);
+ if is_linux() {
+ // The widget bridge uses GTK directly (native rubber-band selection,
+ // tooltips, themed colours), so add GTK's own include paths.
+ // Best-effort: if pkg-config or gtk3-dev is missing the flags are simply
+ // empty and the GTK-only code stays disabled.
+ let gtk_cflags = Command::new("pkg-config")
+ .args(["--cflags", "gtk+-3.0"])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+ for f in gtk_cflags.split_whitespace() {
+ build.flag(f);
+ }
+ }
+ if is_windows() {
+ // Ship one self-contained .exe: link the C++ runtime statically rather
+ // than depending on the toolchain's libstdc++-6.dll/libgcc_s_seh-1.dll/
+ // libwinpthread-1.dll, which no Windows machine has. `-bundle` hands the
+ // archives to the final link instead of copying them into this rlib.
+ build.cpp_link_stdlib(None);
+ println!("cargo:rustc-link-lib=static:-bundle=stdc++");
+ println!("cargo:rustc-link-lib=static:-bundle=winpthread");
}
build.compile("wxbridge");
for flag in libs.split_whitespace() {
- if flag.starts_with('/') && flag.ends_with(".a") {
+ if flag.ends_with(".a") && Path::new(flag).is_absolute() {
// static wx builds: wx-config emits the archive as a full path
- let file = flag.rsplit('/').next().unwrap_or(flag);
+ let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
let stem = file
.strip_prefix("lib")
.unwrap_or(file)
@@ -281,6 +325,9 @@
} else if flag == "-pthread" {
println!("cargo:rustc-link-arg=-pthread");
}
+ // `-mwindows` / `-Wl,--subsystem,windows` are deliberately dropped: the
+ // console-vs-GUI subsystem is the application's decision
+ // (`#![windows_subsystem]`), not the GUI library's.
}
Ok(())
}
+147
View File
@@ -0,0 +1,147 @@
Subject: [PATCH 0007] wxbridge: make the upstream frame usable on wxMSW (no input-swallowing overlay, appearance before the first window, work-area sizing, exe icon, UTF-8 menu fix)
--- a/cpp_src/wxbridge.cpp
+++ b/cpp_src/wxbridge.cpp
@@ -1,5 +1,7 @@
#include <wx/wx.h>
#include "wx/clipbrd.h"
+#include "wx/display.h"
+#include <algorithm>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64) || defined(WIN64) || defined(WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
@@ -34,6 +36,21 @@
void setDPIAware() {}
#endif
+#ifdef __WXMSW__
+#include <wx/msw/darkmode.h>
+// alkane-toolkit patch: wx's dark palette leaves wxSYS_COLOUR_3DLIGHT at its
+// light value, and the generic wxDataViewCtrl (the table on MSW) draws its row
+// and column rules in that colour -- bright grid lines across a dark table.
+// Give it a dark-grey rule colour; everything else stays wx's default palette.
+class DarkModeSettings : public wxDarkModeSettings {
+ public:
+ wxColour GetColour(wxSystemColour index) override {
+ if (index == wxSYS_COLOUR_3DLIGHT) return wxColour(0x3a, 0x3a, 0x3a);
+ return wxDarkModeSettings::GetColour(index);
+ }
+};
+#endif
+
enum cursor {
NO_CURSOR,
ARROW_CURSOR,
@@ -129,10 +146,19 @@
render = NULL;
handle_events = NULL;
// Needed to get App to catch key events on OSX
+ // alkane-toolkit patch: not on MSW. There this invisible child ends up above
+ // the application's own widgets in the sibling z-order, and a
+ // wxTRANSPARENT_WINDOW (WS_EX_TRANSPARENT) is transparent to painting only,
+ // not to hit-testing, so it silently swallowed every click and key press
+ // aimed at the real UI. On GTK later siblings stack above it, so it is kept.
+#ifdef __WXMSW__
+ inputWin = NULL;
+#else
inputWin = new wxWindow(this, wxID_ANY,
wxDefaultPosition,
wxSize(-1, -1),
wxBORDER_NONE | wxTRANSPARENT_WINDOW);
+#endif
InitCursors();
Show(true);
@@ -344,12 +370,43 @@
int fake_argc = 0;
char *fake_argv[1] = {NULL};
wxEntryStart(fake_argc, fake_argv);
+ // alkane-toolkit patch: light/dark appearance, decided before the first
+ // window exists because wxMSW cannot switch it afterwards (SetAppearance
+ // then returns CannotChange). System follows the desktop: the GTK theme's
+ // colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
+ // otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
+ {
+ wxString pref;
+ wxGetEnv("ALKANE_APPEARANCE", &pref);
+ pref.MakeLower();
+ wxApp::Appearance appearance = wxApp::Appearance::System;
+ if (pref == "dark") appearance = wxApp::Appearance::Dark;
+ else if (pref == "light") appearance = wxApp::Appearance::Light;
+#ifdef __WXMSW__
+ // Same as SetAppearance(), but with our dark palette tweak (below).
+ if (appearance != wxApp::Appearance::Light) {
+ wxTheApp->MSWEnableDarkMode(appearance == wxApp::Appearance::Dark
+ ? wxApp::DarkMode_Always
+ : wxApp::DarkMode_Auto,
+ new DarkModeSettings()); // wx takes ownership
+ }
+#else
+ wxTheApp->SetAppearance(appearance);
+#endif
+ }
wxTheApp->OnInit();
#ifdef __WINDOWS__
// Adjust the window according to the display scale factor
double scale = wxGetApp().frame->GetDPIScaleFactor();
wxGetApp().frame->SetSize(width * scale, height * scale);
+ // alkane-toolkit patch: title-bar/Alt-Tab icon from the executable's own
+ // icon resource. By wx convention the application icon group is named
+ // "aaaa" (first alphabetically, so Explorer shows it too); an executable
+ // without one keeps the default rather than showing a load-error dialog.
+ if (::FindResourceW(::GetModuleHandleW(NULL), L"aaaa", MAKEINTRESOURCEW(14) /* RT_GROUP_ICON */)) {
+ wxGetApp().frame->SetIcons(wxIconBundle(wxS("aaaa"), ::GetModuleHandleW(NULL)));
+ }
#else
// OSX
double scale = wxGetApp().frame->GetDPIScaleFactor();
@@ -358,6 +415,24 @@
wxGetApp().frame->Move(0.0, 20.0);
}
#endif
+ // alkane-toolkit patch: never open larger than the monitor's work area
+ // (the screen minus taskbar/panels). A 1280x800 request on a 1280x800 or
+ // 1366x768 laptop otherwise put the bottom of the window, with the status
+ // bar, behind the Windows taskbar.
+ {
+ wxFrame* frame = wxGetApp().frame;
+ int index = wxDisplay::GetFromWindow(frame);
+ wxRect work = wxDisplay(index == wxNOT_FOUND ? 0u : (unsigned)index).GetClientArea();
+ wxRect rect = frame->GetRect();
+ if (rect.width > work.width || rect.height > work.height) {
+ rect.SetSize(wxSize(std::min(rect.width, work.width), std::min(rect.height, work.height)));
+ frame->SetSize(rect.GetSize());
+ }
+ if (!work.Contains(frame->GetRect())) {
+ frame->Move(work.x + (work.width - rect.width) / 2,
+ work.y + (work.height - rect.height) / 2);
+ }
+ }
}
void set_render(void (*render)()) {
@@ -602,15 +677,21 @@
}
}
+ // alkane-toolkit patch: Rust hands UTF-8; upstream cast `help` to wxChar*,
+ // which is wchar_t* on MSW (garbage text), and fell off the end of a
+ // non-void function when `i` was out of range (undefined behaviour).
int insert_to_menu(wxMenu* menu, size_t i, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
- return menu->Insert(i, wxID_ANY, str, (help != NULL) ? (const wxChar *) help : wxEmptyString)->GetId();
+ return menu->Insert(i, wxID_ANY, wxString::FromUTF8(str),
+ help ? wxString::FromUTF8(help) : wxString())->GetId();
}
+ return -1;
}
void insert_submenu(wxMenu* menu, size_t i, wxMenu* subMenu, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
- menu->Insert(i, wxID_ANY, str, subMenu, (help != NULL) ? (const wxChar *) help : wxEmptyString);
+ menu->Insert(i, wxID_ANY, wxString::FromUTF8(str), subMenu,
+ help ? wxString::FromUTF8(help) : wxString());
}
}
+691
View File
@@ -0,0 +1,691 @@
Subject: [PATCH 0008] widget bridge: wxMSW support (generic data-view input and tooltips, DIP size boundary, anti-aliased shapes, themed selection colours)
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -36,7 +36,13 @@
#include <cstdio>
#include <cmath>
#include <map>
+#include <memory>
#include <vector>
+#ifdef __WXMSW__
+// Themed list-view colours, to draw selected rows the way the native renderer does.
+#include <wx/msw/uxtheme.h>
+#include <vssym32.h>
+#endif
#ifdef __WXGTK__
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
// enable and which cannot be done via wx mouse events on GTK (the native widget
@@ -48,8 +54,9 @@
static WxWidgetEventFn g_widget_event = nullptr;
#ifndef __WXGTK__
-// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
-// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
+// Anchor row per data-view control for the wx-mouse-event rubber-band selection
+// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
+// uses native GtkTreeView rubber-banding instead).
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
#endif
@@ -72,6 +79,26 @@
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
};
+// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
+// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
+// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
+// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
+// aware wxMSW works in physical pixels, where a 180 px column must become
+// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
+// like) pass through untouched.
+static wxWindow* DipWindow(wxWindow* win) {
+ if (win) return win;
+ return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
+}
+static int PxFromDip(wxWindow* win, int dip) {
+ wxWindow* w = DipWindow(win);
+ return (w && dip > 0) ? w->FromDIP(dip) : dip;
+}
+static int DipFromPx(wxWindow* win, int px) {
+ wxWindow* w = DipWindow(win);
+ return (w && px > 0) ? w->ToDIP(px) : px;
+}
+
// A list store that carries an optional per-row foreground colour plus an
// alternating-row (zebra) background, surfaced to the native control via
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
@@ -196,6 +223,20 @@
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
+// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
+// in DPI-independent logical pixels, so FromDIP() is the identity there and
+// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
+// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
+// size as the (already scaled) text beside it.
+static double DipFactor() {
+ return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
+}
+static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
+// Space one vector shape occupies, at the current display density.
+static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
+// Icon size factor: the table zoom (round 14 #3) times the display density.
+static double ShapeScale() { return g_table_zoom * DipFactor(); }
+
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
// the timer can invalidate exactly it.
@@ -313,7 +354,7 @@
// health icons are square, so the advance is (h - 3) just like a real one.
if (shape == SHAPE_GAP) {
int h = cell.height - 1;
- int cap = (int)(28 * g_table_zoom + 0.5);
+ int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -329,7 +370,7 @@
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int h = cell.height - (health ? 1 : 4);
- int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5);
+ int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -362,25 +403,37 @@
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
return adv;
}
- int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
+ int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
return slot;
}
}
- int cx = x + SHAPE_ADVANCE / 2;
+#ifdef __WXMSW__
+ // GDI does not anti-alias, so the dots and the padlock came out jagged next
+ // to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
+ // Cairo already does on GTK; the context inherits the DC's origin, scale and
+ // clip (the same approach wx's own generic markup renderer takes).
+ std::unique_ptr<wxGCDC> smooth;
+ if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
+ smooth.reset(new wxGCDC(gc));
+ dc = smooth.get();
+ }
+#endif
+ const int adv = ShapeAdvance();
+ int cx = x + adv / 2;
if (shape == SHAPE_LIGHT_BEACON) {
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
- int r = 3;
+ int r = Dip(3);
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(green));
dc->DrawCircle(cx, cy - (r + 1), r);
dc->SetBrush(wxBrush(red));
dc->DrawCircle(cx, cy + (r + 1), r);
- return SHAPE_ADVANCE;
+ return adv;
}
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
wxColour fill = colour;
@@ -391,21 +444,21 @@
}
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(fill));
- dc->DrawCircle(cx, cy, 4);
- return SHAPE_ADVANCE;
+ dc->DrawCircle(cx, cy, Dip(4));
+ return adv;
}
// Padlock: a filled body with a staple shackle above. The colour carries the
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
bool open = (shape == SHAPE_UNLOCK);
- int bw = 9, bh = 7;
+ int bw = Dip(9), bh = Dip(7);
int bx = cx - bw / 2;
int by = cy - bh / 2 + 1;
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(colour));
- dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5);
+ dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
dc->SetBrush(*wxTRANSPARENT_BRUSH);
- dc->SetPen(wxPen(colour, 2));
- int sr = 3;
+ dc->SetPen(wxPen(colour, Dip(2)));
+ int sr = Dip(3);
int legTop = by - sr - 1;
int lx = cx - sr, rx = cx + sr;
dc->DrawLine(lx, by, lx, legTop); // left leg
@@ -414,11 +467,45 @@
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
else
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
- return SHAPE_ADVANCE;
+ return adv;
}
} // namespace
+// True when selected rows keep their own background under a light, translucent
+// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
+// rather than a solid highlight colour.
+static bool SelectionIsTranslucent(wxWindow* win) {
+#ifdef __WXMSW__
+ if (win && wxUxThemeIsActive()) {
+ wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
+ return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
+ }
+#else
+ (void)win;
+#endif
+ return false;
+}
+
+// Text colour for a selected row, matching the platform's native data-view text
+// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
+// selection: a light translucent highlight under the normal dark text, taken
+// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
+// styles off / high contrast -- the selection is a solid highlight, so the text
+// switches to the system highlight-text colour.
+static wxColour SelectedTextColour(wxWindow* win) {
+#ifdef __WXMSW__
+ if (SelectionIsTranslucent(win)) {
+ wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
+ wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
+ if (c.IsOk()) return c;
+ }
+#else
+ (void)win;
+#endif
+ return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
+}
+
class SegmentRenderer : public wxDataViewCustomRenderer {
public:
SegmentRenderer()
@@ -467,7 +554,9 @@
bg.height += 80;
dc->DrawRectangle(bg);
}
- wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
+ wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
+ wxColour highlight =
+ SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
// firmware family, etc. -- must dim exactly like the native columns when the
// top-level window is backdropped. wxGTK dims a native cell's text via the
@@ -503,7 +592,7 @@
if (IsShapeSentinel(seg.text, shape)) {
// Background the shape sits on, so the pulsing locate dot fades toward it.
wxColour cellbg;
- if (selected) {
+ if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
@@ -530,11 +619,11 @@
if (IsShapeSentinel(seg.text, shape)) {
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
- int adv = SHAPE_ADVANCE;
+ int adv = ShapeAdvance();
// Health icons measure bigger and pack tighter, and report a taller
// content height so the row grows to fit them (round 14 #1). Sizes scale
// with the table zoom (round 14 #3).
- int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5);
+ int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
if (hh < 8) hh = 8;
// The alignment gap is one health-icon-width slot that draws nothing
// (round 15 #5); health icons are square, so its advance is hh - 3.
@@ -646,7 +735,7 @@
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
- ((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, border);
+ ((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
}
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
@@ -658,11 +747,12 @@
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
- ((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f, border);
+ ((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
+ PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
}
void wxbr_sizer_add_spacer(void* sizer, int px) {
- ((wxSizer*)sizer)->AddSpacer(px);
+ ((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
}
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
@@ -694,9 +784,11 @@
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
void wxbr_bind_size(void* win) {
- ((wxWindow*)win)->Bind(wxEVT_SIZE, [](wxSizeEvent& e) {
- if (g_widget_event) g_widget_event(WxEV_SIZE, (long)e.GetSize().GetWidth(),
- (long)e.GetSize().GetHeight());
+ wxWindow* w = (wxWindow*)win;
+ w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
+ if (g_widget_event)
+ g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
+ (long)DipFromPx(w, e.GetSize().GetHeight()));
e.Skip();
});
}
@@ -704,7 +796,8 @@
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
void wxbr_set_min_size(void* win, int w, int h) {
- ((wxWindow*)win)->SetMinSize(wxSize(w, h));
+ wxWindow* window = (wxWindow*)win;
+ window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
}
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
@@ -902,7 +995,8 @@
void* wxbr_dialog(void* parent, const char* title) {
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(title), wxDefaultPosition,
- wxSize(360, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
+ DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
+ wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
}
int wxbr_dialog_show_modal(void* win) {
@@ -957,6 +1051,96 @@
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
}
+// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
+// the GTK and generic tooltip paths so both pick the same icon. The slot advance
+// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
+// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
+// column (round 19 #21) draws the icon block flush to the cell's right edge, so
+// slots are measured from the block's left, not the cell's left.
+struct IconSlots {
+ int left; // x of the first slot, in the same coordinates as the cell
+ int adv; // width of one slot
+};
+
+static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
+ bool right_aligned) {
+ int h = cell_h - 1;
+ int cap = (int)(28 * ShapeScale() + 0.5);
+ if (cap < 8) cap = 8;
+ if (h > cap) h = cap;
+ if (h < 8) h = 8;
+ int adv = h - 3;
+ if (adv < 1) adv = 1;
+ int left = cell_x;
+ if (right_aligned) {
+ int content_w = n * adv;
+ if (content_w < cell_w) left = cell_x + (cell_w - content_w);
+ }
+ return IconSlots{left, adv};
+}
+
+static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
+ int off = x - slots.left;
+ if (off < 0) off = 0;
+ int slot = off / slots.adv;
+ if (slot >= n) slot = n - 1;
+ return slot < 0 ? 0 : slot;
+}
+
+#ifndef __WXGTK__
+// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
+// The control draws its rows in an inner main window, which is where mouse
+// events arrive, so the tooltip lives on that window. Windows only re-shows a
+// tooltip when its text is re-set, so the handler tracks the (row, column,
+// icon slot) under the pointer and replaces the tooltip only when it changes;
+// moving from one Health icon to the next therefore pops the right text.
+struct DvTipKey {
+ int row = -1;
+ unsigned col = (unsigned)-1;
+ int slot = -1;
+ bool operator==(const DvTipKey& o) const {
+ return row == o.row && col == o.col && slot == o.slot;
+ }
+};
+static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
+
+// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
+// in src/generic/datavgen.cpp); custom renderers draw inside it.
+static const int GENERIC_CELL_PADDING = 3;
+
+static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
+ const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
+ wxDataViewItem item;
+ wxDataViewColumn* col = nullptr;
+ dv->HitTest(p, item, col);
+ DvTipKey key;
+ wxString tip;
+ if (item.IsOk() && col) {
+ AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
+ key.row = (int)store->GetRow(item);
+ key.col = col->GetModelColumn();
+ auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
+ if (iit != store->icon_tip.end() && !iit->second.empty()) {
+ wxRect r = dv->GetItemRect(item, col);
+ int pad = dv->FromDIP(GENERIC_CELL_PADDING);
+ int n = (int)iit->second.size();
+ IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
+ col->GetAlignment() == wxALIGN_RIGHT);
+ key.slot = HealthIconSlotAt(slots, p.x, n);
+ tip = iit->second[(size_t)key.slot];
+ } else {
+ auto it = store->cell_tip.find({(unsigned)key.row, key.col});
+ if (it != store->cell_tip.end()) tip = it->second;
+ }
+ }
+ DvTipKey& last = g_tip_key[dv];
+ if (last == key) return;
+ last = key;
+ area->UnsetToolTip();
+ if (!tip.IsEmpty()) area->SetToolTip(tip);
+}
+#endif
+
#ifdef __WXGTK__
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
// (row, model column) under the pointer (used by the Errors column). wx does
@@ -987,31 +1171,12 @@
GdkRectangle crect;
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
gtk_tree_path_free(path);
- // Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
- // (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
- // earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
- // the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
- int h = crect.height - 1;
- int cap = (int)(28 * g_table_zoom + 0.5);
- if (cap < 8) cap = 8;
- if (h > cap) h = cap;
- if (h < 8) h = 8;
- int adv = h - 3;
- if (adv < 1) adv = 1;
int n = (int)iit->second.size();
- // A right-aligned column (round 19 #21) draws the icon block flush to the
- // cell's right edge, so measure the pointer from the block's left, not the
- // cell's left.
- int block_left = crect.x;
- if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
- int content_w = n * adv;
- if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
- }
- int off = bx - block_left;
- if (off < 0) off = 0;
- int slot = off / adv;
- if (slot < 0) slot = 0;
- if (slot >= n) slot = n - 1;
+ IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
+ wxcol->GetAlignment() == wxALIGN_RIGHT);
+ int slot = HealthIconSlotAt(slots, bx, n);
+ int adv = slots.adv;
+ int block_left = slots.left;
const wxString& tip = iit->second[(size_t)slot];
if (tip.IsEmpty()) return FALSE;
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
@@ -1103,49 +1268,61 @@
}
}
#else
- // Non-GTK fallback: track a drag anchor and extend the selection to the row
- // under the cursor. LEFT_DOWN records the anchor (and lets the native handler
- // select it); dragging with the button down selects the inclusive range.
- dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
- if (!dv) { e.Skip(); return; }
- // Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
- if (e.ControlDown() || e.ShiftDown()) { g_drag_anchor.erase(dv); e.Skip(); return; }
- wxDataViewItem item;
- wxDataViewColumn* col = nullptr;
- dv->HitTest(e.GetPosition(), item, col);
- if (item.IsOk()) {
- g_drag_anchor[dv] =
- (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
- } else {
+ // Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
+ // anchor and extend the selection to the row under the cursor. The generic
+ // control draws and receives mouse input in an inner "main window", not in
+ // the wxDataViewCtrl itself (mouse events do not propagate to parents), so
+ // the handlers bind there; HitTest wants control coordinates.
+ {
+ wxWindow* area = dv->GetMainWindow();
+ auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
+ wxDataViewItem item;
+ wxDataViewColumn* col = nullptr;
+ dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
+ if (!item.IsOk()) return false;
+ row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
+ return true;
+ };
+ area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
+ // Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
+ int row = -1;
+ if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
+ g_drag_anchor[dv] = row;
+ } else {
+ g_drag_anchor.erase(dv);
+ }
+ e.Skip(); // let the control select the anchor row
+ });
+ area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
+ e.Skip();
+ dvlc_update_tooltip(dv, area, e.GetPosition());
+ auto it = g_drag_anchor.find(dv);
+ int cur = -1;
+ if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
+ return;
+ int lo = it->second < cur ? it->second : cur;
+ int hi = it->second < cur ? cur : it->second;
+ wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
+ wxDataViewItemArray sel;
+ for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
+ dv->SetSelections(sel);
+ // Selecting programmatically does not emit SELECTION_CHANGED, so notify.
+ if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
+ });
+ area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
g_drag_anchor.erase(dv);
- }
- e.Skip(); // let the native handler select the anchor row
- });
- dv->Bind(wxEVT_MOTION, [](wxMouseEvent& e) {
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
- if (!dv || !e.LeftIsDown()) { e.Skip(); return; }
- auto it = g_drag_anchor.find(dv);
- if (it == g_drag_anchor.end()) { e.Skip(); return; }
- wxDataViewItem item;
- wxDataViewColumn* col = nullptr;
- dv->HitTest(e.GetPosition(), item, col);
- if (!item.IsOk()) { e.Skip(); return; }
- wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
- int cur = (int)model->GetRow(item);
- int lo = it->second < cur ? it->second : cur;
- int hi = it->second < cur ? cur : it->second;
- dv->UnselectAll();
- for (int r = lo; r <= hi; ++r) dv->Select(model->GetItem((unsigned)r));
- // Selecting programmatically does not emit SELECTION_CHANGED, so notify.
- if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
- e.Skip();
- });
- dv->Bind(wxEVT_LEFT_UP, [](wxMouseEvent& e) {
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
- if (dv) g_drag_anchor.erase(dv);
- e.Skip();
- });
+ e.Skip();
+ });
+ area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
+ g_tip_key.erase(dv);
+ e.Skip();
+ });
+ dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
+ g_drag_anchor.erase(dv);
+ g_tip_key.erase(dv);
+ e.Skip();
+ });
+ }
#endif
// Row activation (double-click / Enter): report the row + column so the app
// can, e.g., open the miner's IP in a browser.
@@ -1177,6 +1354,7 @@
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
+ width = PxFromDip(dv, width);
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
width, dvlc_wx_align(align), flags);
// Record the 100% column width for the zoom (round 14 #3); the first column of
@@ -1196,6 +1374,7 @@
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
SegmentRenderer* renderer = new SegmentRenderer();
+ width = PxFromDip(dv, width);
wxAlignment al = dvlc_wx_align(align);
renderer->SetAlignment(al);
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
@@ -1211,7 +1390,7 @@
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned col = dv->GetColumnCount();
dvlc_store(win)->AppendColumn("bool");
- dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
+ dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
wxALIGN_CENTRE, 0);
}
@@ -1356,7 +1535,8 @@
if (!c) return;
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
int w = c->GetWidth();
- const int floor_px = 24;
+ cap_px = PxFromDip(dv, cap_px);
+ const int floor_px = PxFromDip(dv, 24);
if (w < floor_px) w = floor_px;
if (cap_px > 0 && w > cap_px) w = cap_px;
c->SetWidth(w);
@@ -1483,7 +1663,7 @@
void* wxbr_gauge(void* parent, int range) {
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
- wxDefaultPosition, wxSize(-1, 6),
+ wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
wxGA_HORIZONTAL | wxGA_SMOOTH);
return (void*)g;
}
@@ -1510,11 +1690,10 @@
// ---- appearance / dark mode -------------------------------------------------
-void wxbr_set_appearance_system() {
-#if wxCHECK_VERSION(3, 3, 0)
- if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System);
-#endif
-}
+// init_app() now sets the appearance before the frame exists (the only point
+// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
+// kept for API compatibility and does nothing further.
+void wxbr_set_appearance_system() {}
int wxbr_is_dark() {
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
@@ -1658,7 +1837,8 @@
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
- wxSize(-1, 240), wxLC_REPORT | wxLC_NO_HEADER);
+ wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
+ wxLC_REPORT | wxLC_NO_HEADER);
lc->EnableCheckBoxes(true);
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
@@ -1874,7 +2054,9 @@
// given colour on a transparent bitmap so it reads as a coloured glyph on the
// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
- const int sz = 20;
+ // The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
+ const int sz = PxFromDip((wxWindow*)parent, 20);
+ const double scale = sz / 20.0;
wxImage img(sz, sz);
img.InitAlpha();
unsigned char* a = img.GetAlpha();
@@ -1885,6 +2067,7 @@
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
if (gc) {
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
+ gc->Scale(scale, scale);
wxColour col(r, g, b);
gc->SetBrush(wxBrush(col));
gc->SetPen(wxPen(col, 1.0));
@@ -1915,9 +2098,10 @@
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
+ // A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
+ // rasterised for the window's actual display scale.
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
- wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
- return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
+ return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
@@ -1990,7 +2174,7 @@
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
wxRect r;
if (sb->GetFieldRect(fld, r)) {
- int ew = 52;
+ int ew = PxFromDip(sb, 52);
int eh = g_zoom_entry->GetBestSize().GetHeight();
if (eh > r.height - 2) eh = r.height - 2;
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
@@ -2039,7 +2223,7 @@
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
- int widths[2] = { -1, 340 };
+ int widths[2] = { -1, PxFromDip(frame, 340) };
sb->SetFieldsCount(2);
sb->SetStatusWidths(2, widths);
if (!g_status_indicator) {
@@ -2072,12 +2256,12 @@
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
- int widths[3] = { -1, 240, 190 };
+ int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
sb->SetFieldsCount(3);
sb->SetStatusWidths(3, widths);
// A native slider needs more vertical room than a default status bar gives, so
// grow the bar to fit it (round 14 #3).
- sb->SetMinHeight(30);
+ sb->SetMinHeight(PxFromDip(frame, 30));
if (!g_zoom_slider) {
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
g_zoom_slider->SetToolTip(wxT("Table zoom"));
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -260,7 +260,8 @@
unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 }
}
-/// Ask wx to follow the system light/dark appearance (no-op before 3.3).
+/// Kept for API compatibility: `init_app` already follows the system light/dark
+/// appearance (or `ALKANE_APPEARANCE=light|dark`), before any window exists.
pub fn set_appearance_system() {
unsafe { notsafe::wxbr_set_appearance_system() }
}
+33
View File
@@ -0,0 +1,33 @@
# wx-rs patch queue
`../wx-rs-0.2.0-patched/` is the tree cargo builds. These patches, applied in
order to the pristine crate in `../upstream/` (digest pinned in `../VERSION`),
must reproduce it byte for byte; CI checks this with
`scripts/wx_rs_patches.py check`.
To change the bridge: edit the patched tree, build and test, then record the
change as the next patch and commit both:
```sh
python3 scripts/wx_rs_patches.py capture short-name "One-line subject" [PATH ...]
```
`capture` limits the patch to the given paths (default: everything that
differs) and re-runs the check. `0002` and `0003` create the widget bridge
files outright, so they carry those files as of the queue's re-baselining;
later changes go in new patches.
| Patch | What |
|-------|------|
| 0001 | Linux/GTK3 build through `wx-config` |
| 0002 | Widget/event bridge, Rust side (`src/widgets.rs`) |
| 0003 | Widget/event bridge, C++ side (`cpp_src/widgets_bridge.cpp`) |
| 0004 | Upstream fixes for wx 3.3 (uninitialised callbacks) |
| 0005 | Packaging: build-only `reqwest` note; drop the case-duplicate `readme.md` |
| 0006 | Build: platform from the target, not the host; Windows/GNU via `wx-config` |
| 0007 | `wxbridge.cpp` on wxMSW: no input-swallowing overlay, appearance before the first window, work-area sizing, executable icon, UTF-8 menu fix |
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
History: the round 19 health-tooltip fix (GTK tip area converted from
bin-window to widget coordinates) used to be a separate patch on top of an
older 0003; it is part of 0003 since the re-baselining.
Binary file not shown.
+78 -31
View File
@@ -12,22 +12,42 @@ const WX_PATH: &str = "wxWidgets-3.2.2.1";
const WX_SOURCE: &str =
"https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.2.1/wxWidgets-3.2.2.1.tar.bz2";
// alkane-toolkit patch: decide the platform from the TARGET. A build script is
// compiled for and runs on the build host, so `cfg!(windows)` etc. here describe
// the host -- which made a Linux -> Windows cross build take the GTK path.
// Cargo exposes the real target through CARGO_CFG_TARGET_* instead.
fn target_os() -> String {
env::var("CARGO_CFG_TARGET_OS").unwrap_or_default()
}
fn target_env() -> String {
env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default()
}
fn is_windows() -> bool {
cfg!(windows)
target_os() == "windows"
}
fn is_msvc() -> bool {
cfg!(target_env = "msvc")
is_windows() && target_env() == "msvc"
}
fn is_osx() -> bool {
cfg!(target_os = "macos")
target_os() == "macos"
}
// alkane-toolkit patch: real wxGTK3 support on Linux via wx-config
// (upstream stubbed every non-Windows/macOS target).
fn is_linux() -> bool {
cfg!(target_os = "linux")
target_os() == "linux"
}
// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
// mingw-w64, natively or cross from Linux) both build against a wx prefix
// described by its wx-config script, so they share one code path. Upstream's
// MSVC/nmake and macOS download-and-build paths are left as they were.
fn uses_wx_config() -> bool {
is_linux() || (is_windows() && !is_msvc())
}
fn is_stub() -> bool {
@@ -41,8 +61,8 @@ fn main() -> Result<(), Box<dyn Error>> {
if is_stub() {
return Ok(());
}
if is_linux() {
return Ok(()); // libs are linked inside build_linux()
if uses_wx_config() {
return Ok(()); // libs are linked inside build_with_wx_config()
}
let wx_libs = get_libs(&wx_path)?;
@@ -89,7 +109,7 @@ fn main() -> Result<(), Box<dyn Error>> {
fn download_dist() -> Result<PathBuf, Box<dyn Error>> {
let dist_path = Path::new("./dist/");
let wx_path = PathBuf::from(format!("./dist/{}", WX_PATH));
if wx_path.exists() || is_stub() || is_linux() {
if wx_path.exists() || is_stub() || uses_wx_config() {
return Ok(wx_path);
}
println!("cargo:warning=wx-rs: Downloading source to './dist/");
@@ -120,8 +140,8 @@ fn build_bridge_lib(wx_path: &Path) -> Result<(), Box<dyn Error>> {
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
if is_linux() {
return build_linux();
if uses_wx_config() {
return build_with_wx_config();
}
if is_windows() {
@@ -232,25 +252,27 @@ fn osx_libs(wx_path: &Path) -> Result<String, Box<dyn Error>> {
)?)
}
fn build_linux() -> Result<(), Box<dyn Error>> {
// alkane-toolkit patch: GTK3 build driven entirely by wx-config, so the
// same code builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG
// pointing at its prefix) or any system wxGTK3.
fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
// alkane-toolkit patch: build driven entirely by wx-config, so the same code
// builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG pointing at its
// GTK or mingw prefix) or any system wx. wx-config is a POSIX shell script;
// cross builds run it on the Linux host, native mingw builds under MSYS2.
println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| String::from("wx-config"));
let cxxflags = String::from_utf8(
Command::new(&wxconfig).arg("--cxxflags").output()?.stdout,
)?;
let libs = String::from_utf8(Command::new(&wxconfig).arg("--libs").output()?.stdout)?;
// The widget bridge uses GTK directly (zebra-striping CSS), so add GTK's own
// include paths. Best-effort: if pkg-config or gtk3-dev is missing the flags
// are simply empty and the GTK-only code stays disabled.
let gtk_cflags = Command::new("pkg-config")
.args(["--cflags", "gtk+-3.0"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
let wx_config = |arg: &str| -> Result<String, Box<dyn Error>> {
let out = Command::new(&wxconfig).arg(arg).output().map_err(|e| {
format!("wx-rs: cannot run {wxconfig} {arg} (set WX_RS_WXCONFIG): {e}")
})?;
if !out.status.success() {
return Err(format!("wx-rs: {wxconfig} {arg} failed").into());
}
Ok(String::from_utf8(out.stdout)?)
};
let cxxflags = wx_config("--cxxflags")?;
let libs = wx_config("--libs")?;
if is_windows() && !cxxflags.contains("__WXMSW__") {
return Err(format!("wx-rs: {wxconfig} is not a wxMSW build").into());
}
let mut build = cc::Build::new();
build.cpp(true)
@@ -259,15 +281,37 @@ fn build_linux() -> Result<(), Box<dyn Error>> {
for f in cxxflags.split_whitespace() {
build.flag(f);
}
for f in gtk_cflags.split_whitespace() {
build.flag(f);
if is_linux() {
// The widget bridge uses GTK directly (native rubber-band selection,
// tooltips, themed colours), so add GTK's own include paths.
// Best-effort: if pkg-config or gtk3-dev is missing the flags are simply
// empty and the GTK-only code stays disabled.
let gtk_cflags = Command::new("pkg-config")
.args(["--cflags", "gtk+-3.0"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
for f in gtk_cflags.split_whitespace() {
build.flag(f);
}
}
if is_windows() {
// Ship one self-contained .exe: link the C++ runtime statically rather
// than depending on the toolchain's libstdc++-6.dll/libgcc_s_seh-1.dll/
// libwinpthread-1.dll, which no Windows machine has. `-bundle` hands the
// archives to the final link instead of copying them into this rlib.
build.cpp_link_stdlib(None);
println!("cargo:rustc-link-lib=static:-bundle=stdc++");
println!("cargo:rustc-link-lib=static:-bundle=winpthread");
}
build.compile("wxbridge");
for flag in libs.split_whitespace() {
if flag.starts_with('/') && flag.ends_with(".a") {
if flag.ends_with(".a") && Path::new(flag).is_absolute() {
// static wx builds: wx-config emits the archive as a full path
let file = flag.rsplit('/').next().unwrap_or(flag);
let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
let stem = file
.strip_prefix("lib")
.unwrap_or(file)
@@ -281,6 +325,9 @@ fn build_linux() -> Result<(), Box<dyn Error>> {
} else if flag == "-pthread" {
println!("cargo:rustc-link-arg=-pthread");
}
// `-mwindows` / `-Wl,--subsystem,windows` are deliberately dropped: the
// console-vs-GUI subsystem is the application's decision
// (`#![windows_subsystem]`), not the GUI library's.
}
Ok(())
}
+293 -109
View File
@@ -36,7 +36,13 @@
#include <cstdio>
#include <cmath>
#include <map>
#include <memory>
#include <vector>
#ifdef __WXMSW__
// Themed list-view colours, to draw selected rows the way the native renderer does.
#include <wx/msw/uxtheme.h>
#include <vssym32.h>
#endif
#ifdef __WXGTK__
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
// enable and which cannot be done via wx mouse events on GTK (the native widget
@@ -48,8 +54,9 @@ typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
static WxWidgetEventFn g_widget_event = nullptr;
#ifndef __WXGTK__
// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
// Anchor row per data-view control for the wx-mouse-event rubber-band selection
// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
// uses native GtkTreeView rubber-banding instead).
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
#endif
@@ -72,6 +79,26 @@ enum WxWidgetEventKind {
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
};
// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
// aware wxMSW works in physical pixels, where a 180 px column must become
// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
// like) pass through untouched.
static wxWindow* DipWindow(wxWindow* win) {
if (win) return win;
return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
}
static int PxFromDip(wxWindow* win, int dip) {
wxWindow* w = DipWindow(win);
return (w && dip > 0) ? w->FromDIP(dip) : dip;
}
static int DipFromPx(wxWindow* win, int px) {
wxWindow* w = DipWindow(win);
return (w && px > 0) ? w->ToDIP(px) : px;
}
// A list store that carries an optional per-row foreground colour plus an
// alternating-row (zebra) background, surfaced to the native control via
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
@@ -196,6 +223,20 @@ static wxVector<int> g_zoom_base_w; // column widths at 100% (per co
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
// in DPI-independent logical pixels, so FromDIP() is the identity there and
// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
// size as the (already scaled) text beside it.
static double DipFactor() {
return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
}
static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
// Space one vector shape occupies, at the current display density.
static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
// Icon size factor: the table zoom (round 14 #3) times the display density.
static double ShapeScale() { return g_table_zoom * DipFactor(); }
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
// the timer can invalidate exactly it.
@@ -313,7 +354,7 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
// health icons are square, so the advance is (h - 3) just like a real one.
if (shape == SHAPE_GAP) {
int h = cell.height - 1;
int cap = (int)(28 * g_table_zoom + 0.5);
int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -329,7 +370,7 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int h = cell.height - (health ? 1 : 4);
int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5);
int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
@@ -362,25 +403,37 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
return adv;
}
int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
return slot;
}
}
int cx = x + SHAPE_ADVANCE / 2;
#ifdef __WXMSW__
// GDI does not anti-alias, so the dots and the padlock came out jagged next
// to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
// Cairo already does on GTK; the context inherits the DC's origin, scale and
// clip (the same approach wx's own generic markup renderer takes).
std::unique_ptr<wxGCDC> smooth;
if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
smooth.reset(new wxGCDC(gc));
dc = smooth.get();
}
#endif
const int adv = ShapeAdvance();
int cx = x + adv / 2;
if (shape == SHAPE_LIGHT_BEACON) {
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
int r = 3;
int r = Dip(3);
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(green));
dc->DrawCircle(cx, cy - (r + 1), r);
dc->SetBrush(wxBrush(red));
dc->DrawCircle(cx, cy + (r + 1), r);
return SHAPE_ADVANCE;
return adv;
}
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
wxColour fill = colour;
@@ -391,21 +444,21 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
}
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(fill));
dc->DrawCircle(cx, cy, 4);
return SHAPE_ADVANCE;
dc->DrawCircle(cx, cy, Dip(4));
return adv;
}
// Padlock: a filled body with a staple shackle above. The colour carries the
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
bool open = (shape == SHAPE_UNLOCK);
int bw = 9, bh = 7;
int bw = Dip(9), bh = Dip(7);
int bx = cx - bw / 2;
int by = cy - bh / 2 + 1;
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(colour));
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5);
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
dc->SetBrush(*wxTRANSPARENT_BRUSH);
dc->SetPen(wxPen(colour, 2));
int sr = 3;
dc->SetPen(wxPen(colour, Dip(2)));
int sr = Dip(3);
int legTop = by - sr - 1;
int lx = cx - sr, rx = cx + sr;
dc->DrawLine(lx, by, lx, legTop); // left leg
@@ -414,11 +467,45 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
else
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
return SHAPE_ADVANCE;
return adv;
}
} // namespace
// True when selected rows keep their own background under a light, translucent
// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
// rather than a solid highlight colour.
static bool SelectionIsTranslucent(wxWindow* win) {
#ifdef __WXMSW__
if (win && wxUxThemeIsActive()) {
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
}
#else
(void)win;
#endif
return false;
}
// Text colour for a selected row, matching the platform's native data-view text
// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
// selection: a light translucent highlight under the normal dark text, taken
// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
// styles off / high contrast -- the selection is a solid highlight, so the text
// switches to the system highlight-text colour.
static wxColour SelectedTextColour(wxWindow* win) {
#ifdef __WXMSW__
if (SelectionIsTranslucent(win)) {
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
if (c.IsOk()) return c;
}
#else
(void)win;
#endif
return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
}
class SegmentRenderer : public wxDataViewCustomRenderer {
public:
SegmentRenderer()
@@ -467,7 +554,9 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
bg.height += 80;
dc->DrawRectangle(bg);
}
wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
wxColour highlight =
SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
// firmware family, etc. -- must dim exactly like the native columns when the
// top-level window is backdropped. wxGTK dims a native cell's text via the
@@ -503,7 +592,7 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
if (IsShapeSentinel(seg.text, shape)) {
// Background the shape sits on, so the pulsing locate dot fades toward it.
wxColour cellbg;
if (selected) {
if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
@@ -530,11 +619,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
if (IsShapeSentinel(seg.text, shape)) {
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
int adv = SHAPE_ADVANCE;
int adv = ShapeAdvance();
// Health icons measure bigger and pack tighter, and report a taller
// content height so the row grows to fit them (round 14 #1). Sizes scale
// with the table zoom (round 14 #3).
int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5);
int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
if (hh < 8) hh = 8;
// The alignment gap is one health-icon-width slot that draws nothing
// (round 15 #5); health icons are square, so its advance is hh - 3.
@@ -646,7 +735,7 @@ void wxbr_sizer_add(void* sizer, void* win, int proportion, int flags, int borde
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, border);
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
}
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
@@ -658,11 +747,12 @@ void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags
if (flags & 16) f |= wxBOTTOM;
if (flags & 32) f |= wxLEFT;
if (flags & 64) f |= wxRIGHT;
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f, border);
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
}
void wxbr_sizer_add_spacer(void* sizer, int px) {
((wxSizer*)sizer)->AddSpacer(px);
((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
}
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
@@ -694,9 +784,11 @@ void wxbr_sizer_show(void* sizer, void* win, int show) {
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
void wxbr_bind_size(void* win) {
((wxWindow*)win)->Bind(wxEVT_SIZE, [](wxSizeEvent& e) {
if (g_widget_event) g_widget_event(WxEV_SIZE, (long)e.GetSize().GetWidth(),
(long)e.GetSize().GetHeight());
wxWindow* w = (wxWindow*)win;
w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
if (g_widget_event)
g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
(long)DipFromPx(w, e.GetSize().GetHeight()));
e.Skip();
});
}
@@ -704,7 +796,8 @@ void wxbr_bind_size(void* win) {
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
void wxbr_set_min_size(void* win, int w, int h) {
((wxWindow*)win)->SetMinSize(wxSize(w, h));
wxWindow* window = (wxWindow*)win;
window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
}
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
@@ -902,7 +995,8 @@ int wxbr_clb_string(void* win, int i, char* buf, int cap) {
void* wxbr_dialog(void* parent, const char* title) {
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
wxString::FromUTF8(title), wxDefaultPosition,
wxSize(360, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
}
int wxbr_dialog_show_modal(void* win) {
@@ -957,6 +1051,96 @@ static AttrListStore* dvlc_store(void* win) {
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
}
// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
// the GTK and generic tooltip paths so both pick the same icon. The slot advance
// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
// column (round 19 #21) draws the icon block flush to the cell's right edge, so
// slots are measured from the block's left, not the cell's left.
struct IconSlots {
int left; // x of the first slot, in the same coordinates as the cell
int adv; // width of one slot
};
static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
bool right_aligned) {
int h = cell_h - 1;
int cap = (int)(28 * ShapeScale() + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int adv = h - 3;
if (adv < 1) adv = 1;
int left = cell_x;
if (right_aligned) {
int content_w = n * adv;
if (content_w < cell_w) left = cell_x + (cell_w - content_w);
}
return IconSlots{left, adv};
}
static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
int off = x - slots.left;
if (off < 0) off = 0;
int slot = off / slots.adv;
if (slot >= n) slot = n - 1;
return slot < 0 ? 0 : slot;
}
#ifndef __WXGTK__
// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
// The control draws its rows in an inner main window, which is where mouse
// events arrive, so the tooltip lives on that window. Windows only re-shows a
// tooltip when its text is re-set, so the handler tracks the (row, column,
// icon slot) under the pointer and replaces the tooltip only when it changes;
// moving from one Health icon to the next therefore pops the right text.
struct DvTipKey {
int row = -1;
unsigned col = (unsigned)-1;
int slot = -1;
bool operator==(const DvTipKey& o) const {
return row == o.row && col == o.col && slot == o.slot;
}
};
static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
// in src/generic/datavgen.cpp); custom renderers draw inside it.
static const int GENERIC_CELL_PADDING = 3;
static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(p, item, col);
DvTipKey key;
wxString tip;
if (item.IsOk() && col) {
AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
key.row = (int)store->GetRow(item);
key.col = col->GetModelColumn();
auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
if (iit != store->icon_tip.end() && !iit->second.empty()) {
wxRect r = dv->GetItemRect(item, col);
int pad = dv->FromDIP(GENERIC_CELL_PADDING);
int n = (int)iit->second.size();
IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
col->GetAlignment() == wxALIGN_RIGHT);
key.slot = HealthIconSlotAt(slots, p.x, n);
tip = iit->second[(size_t)key.slot];
} else {
auto it = store->cell_tip.find({(unsigned)key.row, key.col});
if (it != store->cell_tip.end()) tip = it->second;
}
}
DvTipKey& last = g_tip_key[dv];
if (last == key) return;
last = key;
area->UnsetToolTip();
if (!tip.IsEmpty()) area->SetToolTip(tip);
}
#endif
#ifdef __WXGTK__
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
// (row, model column) under the pointer (used by the Errors column). wx does
@@ -987,31 +1171,12 @@ static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keybo
GdkRectangle crect;
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
gtk_tree_path_free(path);
// Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
// (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
// earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
// the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
int h = crect.height - 1;
int cap = (int)(28 * g_table_zoom + 0.5);
if (cap < 8) cap = 8;
if (h > cap) h = cap;
if (h < 8) h = 8;
int adv = h - 3;
if (adv < 1) adv = 1;
int n = (int)iit->second.size();
// A right-aligned column (round 19 #21) draws the icon block flush to the
// cell's right edge, so measure the pointer from the block's left, not the
// cell's left.
int block_left = crect.x;
if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
int content_w = n * adv;
if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
}
int off = bx - block_left;
if (off < 0) off = 0;
int slot = off / adv;
if (slot < 0) slot = 0;
if (slot >= n) slot = n - 1;
IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
wxcol->GetAlignment() == wxALIGN_RIGHT);
int slot = HealthIconSlotAt(slots, bx, n);
int adv = slots.adv;
int block_left = slots.left;
const wxString& tip = iit->second[(size_t)slot];
if (tip.IsEmpty()) return FALSE;
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
@@ -1103,49 +1268,61 @@ void* wxbr_dvlc(void* parent) {
}
}
#else
// Non-GTK fallback: track a drag anchor and extend the selection to the row
// under the cursor. LEFT_DOWN records the anchor (and lets the native handler
// select it); dragging with the button down selects the inclusive range.
dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv) { e.Skip(); return; }
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
if (e.ControlDown() || e.ShiftDown()) { g_drag_anchor.erase(dv); e.Skip(); return; }
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(e.GetPosition(), item, col);
if (item.IsOk()) {
g_drag_anchor[dv] =
(int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
} else {
// Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
// anchor and extend the selection to the row under the cursor. The generic
// control draws and receives mouse input in an inner "main window", not in
// the wxDataViewCtrl itself (mouse events do not propagate to parents), so
// the handlers bind there; HitTest wants control coordinates.
{
wxWindow* area = dv->GetMainWindow();
auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
if (!item.IsOk()) return false;
row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
return true;
};
area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
int row = -1;
if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
g_drag_anchor[dv] = row;
} else {
g_drag_anchor.erase(dv);
}
e.Skip(); // let the control select the anchor row
});
area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
e.Skip();
dvlc_update_tooltip(dv, area, e.GetPosition());
auto it = g_drag_anchor.find(dv);
int cur = -1;
if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
return;
int lo = it->second < cur ? it->second : cur;
int hi = it->second < cur ? cur : it->second;
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
wxDataViewItemArray sel;
for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
dv->SetSelections(sel);
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
});
area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
g_drag_anchor.erase(dv);
}
e.Skip(); // let the native handler select the anchor row
});
dv->Bind(wxEVT_MOTION, [](wxMouseEvent& e) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (!dv || !e.LeftIsDown()) { e.Skip(); return; }
auto it = g_drag_anchor.find(dv);
if (it == g_drag_anchor.end()) { e.Skip(); return; }
wxDataViewItem item;
wxDataViewColumn* col = nullptr;
dv->HitTest(e.GetPosition(), item, col);
if (!item.IsOk()) { e.Skip(); return; }
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
int cur = (int)model->GetRow(item);
int lo = it->second < cur ? it->second : cur;
int hi = it->second < cur ? cur : it->second;
dv->UnselectAll();
for (int r = lo; r <= hi; ++r) dv->Select(model->GetItem((unsigned)r));
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
e.Skip();
});
dv->Bind(wxEVT_LEFT_UP, [](wxMouseEvent& e) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
if (dv) g_drag_anchor.erase(dv);
e.Skip();
});
e.Skip();
});
area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
g_tip_key.erase(dv);
e.Skip();
});
dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
g_drag_anchor.erase(dv);
g_tip_key.erase(dv);
e.Skip();
});
}
#endif
// Row activation (double-click / Enter): report the row + column so the app
// can, e.g., open the miner's IP in a browser.
@@ -1177,6 +1354,7 @@ void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reor
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
width = PxFromDip(dv, width);
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
width, dvlc_wx_align(align), flags);
// Record the 100% column width for the zoom (round 14 #3); the first column of
@@ -1196,6 +1374,7 @@ void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int
unsigned col = dv->GetColumnCount(); // next model column index
dvlc_store(win)->AppendColumn("string");
SegmentRenderer* renderer = new SegmentRenderer();
width = PxFromDip(dv, width);
wxAlignment al = dvlc_wx_align(align);
renderer->SetAlignment(al);
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
@@ -1211,7 +1390,7 @@ void wxbr_dvlc_append_toggle_col(void* win, int width) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
unsigned col = dv->GetColumnCount();
dvlc_store(win)->AppendColumn("bool");
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
wxALIGN_CENTRE, 0);
}
@@ -1356,7 +1535,8 @@ void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
if (!c) return;
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
int w = c->GetWidth();
const int floor_px = 24;
cap_px = PxFromDip(dv, cap_px);
const int floor_px = PxFromDip(dv, 24);
if (w < floor_px) w = floor_px;
if (cap_px > 0 && w > cap_px) w = cap_px;
c->SetWidth(w);
@@ -1483,7 +1663,7 @@ void* wxbr_timer(int id, int ms) {
void* wxbr_gauge(void* parent, int range) {
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
wxDefaultPosition, wxSize(-1, 6),
wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
wxGA_HORIZONTAL | wxGA_SMOOTH);
return (void*)g;
}
@@ -1510,11 +1690,10 @@ int wxbr_launch_browser(const char* url) {
// ---- appearance / dark mode -------------------------------------------------
void wxbr_set_appearance_system() {
#if wxCHECK_VERSION(3, 3, 0)
if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System);
#endif
}
// init_app() now sets the appearance before the frame exists (the only point
// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
// kept for API compatibility and does nothing further.
void wxbr_set_appearance_system() {}
int wxbr_is_dark() {
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
@@ -1658,7 +1837,8 @@ static void ReorderMoveTo(wxListCtrl* lc, const wxPoint& pos) {
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
wxSize(-1, 240), wxLC_REPORT | wxLC_NO_HEADER);
wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
wxLC_REPORT | wxLC_NO_HEADER);
lc->EnableCheckBoxes(true);
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
@@ -1874,7 +2054,9 @@ void wxbr_choice_set_selection(void* win, int i) {
// given colour on a transparent bitmap so it reads as a coloured glyph on the
// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
const int sz = 20;
// The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
const int sz = PxFromDip((wxWindow*)parent, 20);
const double scale = sz / 20.0;
wxImage img(sz, sz);
img.InitAlpha();
unsigned char* a = img.GetAlpha();
@@ -1885,6 +2067,7 @@ void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
if (gc) {
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
gc->Scale(scale, scale);
wxColour col(r, g, b);
gc->SetBrush(wxBrush(col));
gc->SetPen(wxPen(col, 1.0));
@@ -1915,9 +2098,10 @@ void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
// A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
// rasterised for the window's actual display scale.
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
@@ -1990,7 +2174,7 @@ static void reposition_status_indicator() {
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
wxRect r;
if (sb->GetFieldRect(fld, r)) {
int ew = 52;
int ew = PxFromDip(sb, 52);
int eh = g_zoom_entry->GetBestSize().GetHeight();
if (eh > r.height - 2) eh = r.height - 2;
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
@@ -2039,7 +2223,7 @@ void wxbr_status_indicator_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[2] = { -1, 340 };
int widths[2] = { -1, PxFromDip(frame, 340) };
sb->SetFieldsCount(2);
sb->SetStatusWidths(2, widths);
if (!g_status_indicator) {
@@ -2072,12 +2256,12 @@ void wxbr_status_zoom_init(void* frame_ptr) {
wxFrame* frame = (wxFrame*)frame_ptr;
wxStatusBar* sb = frame->GetStatusBar();
if (!sb) sb = frame->CreateStatusBar();
int widths[3] = { -1, 240, 190 };
int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
sb->SetFieldsCount(3);
sb->SetStatusWidths(3, widths);
// A native slider needs more vertical room than a default status bar gives, so
// grow the bar to fit it (round 14 #3).
sb->SetMinHeight(30);
sb->SetMinHeight(PxFromDip(frame, 30));
if (!g_zoom_slider) {
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
g_zoom_slider->SetToolTip(wxT("Table zoom"));
+83 -2
View File
@@ -1,5 +1,7 @@
#include <wx/wx.h>
#include "wx/clipbrd.h"
#include "wx/display.h"
#include <algorithm>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64) || defined(WIN64) || defined(WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
@@ -34,6 +36,21 @@ void setDPIAware() {
void setDPIAware() {}
#endif
#ifdef __WXMSW__
#include <wx/msw/darkmode.h>
// alkane-toolkit patch: wx's dark palette leaves wxSYS_COLOUR_3DLIGHT at its
// light value, and the generic wxDataViewCtrl (the table on MSW) draws its row
// and column rules in that colour -- bright grid lines across a dark table.
// Give it a dark-grey rule colour; everything else stays wx's default palette.
class DarkModeSettings : public wxDarkModeSettings {
public:
wxColour GetColour(wxSystemColour index) override {
if (index == wxSYS_COLOUR_3DLIGHT) return wxColour(0x3a, 0x3a, 0x3a);
return wxDarkModeSettings::GetColour(index);
}
};
#endif
enum cursor {
NO_CURSOR,
ARROW_CURSOR,
@@ -129,10 +146,19 @@ MyFrame::MyFrame(const wxString& title, const wxSize& size)
render = NULL;
handle_events = NULL;
// Needed to get App to catch key events on OSX
// alkane-toolkit patch: not on MSW. There this invisible child ends up above
// the application's own widgets in the sibling z-order, and a
// wxTRANSPARENT_WINDOW (WS_EX_TRANSPARENT) is transparent to painting only,
// not to hit-testing, so it silently swallowed every click and key press
// aimed at the real UI. On GTK later siblings stack above it, so it is kept.
#ifdef __WXMSW__
inputWin = NULL;
#else
inputWin = new wxWindow(this, wxID_ANY,
wxDefaultPosition,
wxSize(-1, -1),
wxBORDER_NONE | wxTRANSPARENT_WINDOW);
#endif
InitCursors();
Show(true);
@@ -344,12 +370,43 @@ extern "C" {
int fake_argc = 0;
char *fake_argv[1] = {NULL};
wxEntryStart(fake_argc, fake_argv);
// alkane-toolkit patch: light/dark appearance, decided before the first
// window exists because wxMSW cannot switch it afterwards (SetAppearance
// then returns CannotChange). System follows the desktop: the GTK theme's
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
{
wxString pref;
wxGetEnv("ALKANE_APPEARANCE", &pref);
pref.MakeLower();
wxApp::Appearance appearance = wxApp::Appearance::System;
if (pref == "dark") appearance = wxApp::Appearance::Dark;
else if (pref == "light") appearance = wxApp::Appearance::Light;
#ifdef __WXMSW__
// Same as SetAppearance(), but with our dark palette tweak (below).
if (appearance != wxApp::Appearance::Light) {
wxTheApp->MSWEnableDarkMode(appearance == wxApp::Appearance::Dark
? wxApp::DarkMode_Always
: wxApp::DarkMode_Auto,
new DarkModeSettings()); // wx takes ownership
}
#else
wxTheApp->SetAppearance(appearance);
#endif
}
wxTheApp->OnInit();
#ifdef __WINDOWS__
// Adjust the window according to the display scale factor
double scale = wxGetApp().frame->GetDPIScaleFactor();
wxGetApp().frame->SetSize(width * scale, height * scale);
// alkane-toolkit patch: title-bar/Alt-Tab icon from the executable's own
// icon resource. By wx convention the application icon group is named
// "aaaa" (first alphabetically, so Explorer shows it too); an executable
// without one keeps the default rather than showing a load-error dialog.
if (::FindResourceW(::GetModuleHandleW(NULL), L"aaaa", MAKEINTRESOURCEW(14) /* RT_GROUP_ICON */)) {
wxGetApp().frame->SetIcons(wxIconBundle(wxS("aaaa"), ::GetModuleHandleW(NULL)));
}
#else
// OSX
double scale = wxGetApp().frame->GetDPIScaleFactor();
@@ -358,6 +415,24 @@ extern "C" {
wxGetApp().frame->Move(0.0, 20.0);
}
#endif
// alkane-toolkit patch: never open larger than the monitor's work area
// (the screen minus taskbar/panels). A 1280x800 request on a 1280x800 or
// 1366x768 laptop otherwise put the bottom of the window, with the status
// bar, behind the Windows taskbar.
{
wxFrame* frame = wxGetApp().frame;
int index = wxDisplay::GetFromWindow(frame);
wxRect work = wxDisplay(index == wxNOT_FOUND ? 0u : (unsigned)index).GetClientArea();
wxRect rect = frame->GetRect();
if (rect.width > work.width || rect.height > work.height) {
rect.SetSize(wxSize(std::min(rect.width, work.width), std::min(rect.height, work.height)));
frame->SetSize(rect.GetSize());
}
if (!work.Contains(frame->GetRect())) {
frame->Move(work.x + (work.width - rect.width) / 2,
work.y + (work.height - rect.height) / 2);
}
}
}
void set_render(void (*render)()) {
@@ -602,15 +677,21 @@ extern "C" {
}
}
// alkane-toolkit patch: Rust hands UTF-8; upstream cast `help` to wxChar*,
// which is wchar_t* on MSW (garbage text), and fell off the end of a
// non-void function when `i` was out of range (undefined behaviour).
int insert_to_menu(wxMenu* menu, size_t i, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
return menu->Insert(i, wxID_ANY, str, (help != NULL) ? (const wxChar *) help : wxEmptyString)->GetId();
return menu->Insert(i, wxID_ANY, wxString::FromUTF8(str),
help ? wxString::FromUTF8(help) : wxString())->GetId();
}
return -1;
}
void insert_submenu(wxMenu* menu, size_t i, wxMenu* subMenu, char* str, char* help) {
if (i <= menu->GetMenuItemCount()) {
menu->Insert(i, wxID_ANY, str, subMenu, (help != NULL) ? (const wxChar *) help : wxEmptyString);
menu->Insert(i, wxID_ANY, wxString::FromUTF8(str), subMenu,
help ? wxString::FromUTF8(help) : wxString());
}
}
+2 -1
View File
@@ -260,7 +260,8 @@ pub fn launch_browser(url: &str) -> bool {
unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 }
}
/// Ask wx to follow the system light/dark appearance (no-op before 3.3).
/// Kept for API compatibility: `init_app` already follows the system light/dark
/// appearance (or `ALKANE_APPEARANCE=light|dark`), before any window exists.
pub fn set_appearance_system() {
unsafe { notsafe::wxbr_set_appearance_system() }
}
+4
View File
@@ -3,3 +3,7 @@ version: 3.3.3
source_url: https://github.com/wxWidgets/wxWidgets/releases/download/v3.3.3/wxWidgets-3.3.3.tar.bz2
sha256: 81b09d6dd9f1ed9301f8c55a968a488d0491f264dc2bab19a7e407ac67009482
note: pristine dist tarball (includes 3rdparty submodules). Builds happen out-of-tree via scripts/build-wx-linux.sh - the repo tree is never built in place.
update: the tarball carries its own nested .gitignore files, so stage a new
tree with `git add -f` and check `diff -rq` against the unpacked tarball;
a plain `git add` silently drops generated files (pnglibconf.h, PCRE2's
configure, libtiff build/) that the mingw cross build needs.
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<UseFullPaths>false</UseFullPaths>
</ClCompile>
</ItemDefinitionGroup>
</Project>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+279
View File
@@ -0,0 +1,279 @@
#! /bin/sh
# Wrapper for Microsoft lib.exe
me=ar-lib
scriptversion=2024-06-19.01; # UTC
# Copyright (C) 2010-2024 Free Software Foundation, Inc.
# Written by Peter Rosin <peda@lysator.liu.se>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
# func_error message
func_error ()
{
echo "$me: $1" 1>&2
exit 1
}
file_conv=
# func_file_conv build_file
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN* | MSYS*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv in
mingw)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin | msys)
file=`cygpath -m "$file" || echo "$file"`
;;
wine)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_at_file at_file operation archive
# Iterate over all members in AT_FILE performing OPERATION on ARCHIVE
# for each of them.
# When interpreting the content of the @FILE, do NOT use func_file_conv,
# since the user would need to supply preconverted file names to
# binutils ar, at least for MinGW.
func_at_file ()
{
operation=$2
archive=$3
at_file_contents=`cat "$1"`
eval set x "$at_file_contents"
shift
for member
do
$AR -NOLOGO $operation:"$member" "$archive" || exit $?
done
}
case $1 in
'')
func_error "no command. Try '$0 --help' for more information."
;;
-h | --h*)
cat <<EOF
Usage: $me [--help] [--version] PROGRAM ACTION ARCHIVE [MEMBER...]
Members may be specified in a file named with @FILE.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
EOF
exit $?
;;
-v | --v*)
echo "$me (GNU Automake) $scriptversion"
exit $?
;;
esac
if test $# -lt 3; then
func_error "you must specify a program, an action and an archive"
fi
AR=$1
shift
while :
do
if test $# -lt 2; then
func_error "you must specify a program, an action and an archive"
fi
case $1 in
-lib | -LIB \
| -ltcg | -LTCG \
| -machine* | -MACHINE* \
| -subsystem* | -SUBSYSTEM* \
| -verbose | -VERBOSE \
| -wx* | -WX* )
AR="$AR $1"
shift
;;
-nologo | -NOLOGO)
# We always invoke AR with -nologo, so don't need to add it again.
shift
;;
*)
action=$1
shift
break
;;
esac
done
orig_archive=$1
shift
func_file_conv "$orig_archive"
archive=$file
# strip leading dash in $action
action=${action#-}
delete=
extract=
list=
quick=
replace=
index=
create=
while test -n "$action"
do
case $action in
d*) delete=yes ;;
x*) extract=yes ;;
t*) list=yes ;;
q*) quick=yes ;;
r*) replace=yes ;;
s*) index=yes ;;
S*) ;; # the index is always updated implicitly
c*) create=yes ;;
u*) ;; # TODO: don't ignore the update modifier
v*) ;; # TODO: don't ignore the verbose modifier
*)
func_error "unknown action specified"
;;
esac
action=${action#?}
done
case $delete$extract$list$quick$replace,$index in
yes,* | ,yes)
;;
yesyes*)
func_error "more than one action specified"
;;
*)
func_error "no action specified"
;;
esac
if test -n "$delete"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
for member
do
case $1 in
@*)
func_at_file "${1#@}" -REMOVE "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -REMOVE:"$file" "$archive" || exit $?
;;
esac
done
elif test -n "$extract"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
if test $# -gt 0; then
for member
do
case $1 in
@*)
func_at_file "${1#@}" -EXTRACT "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -EXTRACT:"$file" "$archive" || exit $?
;;
esac
done
else
$AR -NOLOGO -LIST "$archive" | tr -d '\r' | sed -e 's/\\/\\\\/g' \
| while read member
do
$AR -NOLOGO -EXTRACT:"$member" "$archive" || exit $?
done
fi
elif test -n "$quick$replace"; then
if test ! -f "$orig_archive"; then
if test -z "$create"; then
echo "$me: creating $orig_archive"
fi
orig_archive=
else
orig_archive=$archive
fi
for member
do
case $1 in
@*)
func_file_conv "${1#@}"
set x "$@" "@$file"
;;
*)
func_file_conv "$1"
set x "$@" "$file"
;;
esac
shift
shift
done
if test -n "$orig_archive"; then
$AR -NOLOGO -OUT:"$archive" "$orig_archive" "$@" || exit $?
else
$AR -NOLOGO -OUT:"$archive" "$@" || exit $?
fi
elif test -n "$list"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
$AR -NOLOGO -LIST "$archive" || exit $?
fi
+351
View File
@@ -0,0 +1,351 @@
#! /bin/sh
# Wrapper for compilers which do not understand '-c -o'.
scriptversion=2024-06-19.01; # UTC
# Copyright (C) 1999-2024 Free Software Foundation, Inc.
# Written by Tom Tromey <tromey@cygnus.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
nl='
'
# We need space, tab and new line, in precisely that order. Quoting is
# there to prevent tools from complaining about whitespace usage.
IFS=" "" $nl"
file_conv=
# func_file_conv build_file lazy
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts. If the determined conversion
# type is listed in (the comma separated) LAZY, no conversion will
# take place.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN* | MSYS*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv/,$2, in
*,$file_conv,*)
;;
mingw/*)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin/* | msys/*)
file=`cygpath -m "$file" || echo "$file"`
;;
wine/*)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_cl_dashL linkdir
# Make cl look for libraries in LINKDIR
func_cl_dashL ()
{
func_file_conv "$1"
if test -z "$lib_path"; then
lib_path=$file
else
lib_path="$lib_path;$file"
fi
linker_opts="$linker_opts -LIBPATH:$file"
}
# func_cl_dashl library
# Do a library search-path lookup for cl
func_cl_dashl ()
{
lib=$1
found=no
save_IFS=$IFS
IFS=';'
for dir in $lib_path $LIB
do
IFS=$save_IFS
if $shared && test -f "$dir/$lib.dll.lib"; then
found=yes
lib=$dir/$lib.dll.lib
break
fi
if test -f "$dir/$lib.lib"; then
found=yes
lib=$dir/$lib.lib
break
fi
if test -f "$dir/lib$lib.a"; then
found=yes
lib=$dir/lib$lib.a
break
fi
done
IFS=$save_IFS
if test "$found" != yes; then
lib=$lib.lib
fi
}
# func_cl_wrapper cl arg...
# Adjust compile command to suit cl
func_cl_wrapper ()
{
# Assume a capable shell
lib_path=
shared=:
linker_opts=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
eat=1
case $2 in
*.o | *.lo | *.[oO][bB][jJ])
func_file_conv "$2"
set x "$@" -Fo"$file"
shift
;;
*)
func_file_conv "$2"
set x "$@" -Fe"$file"
shift
;;
esac
;;
-I)
eat=1
func_file_conv "$2" mingw
set x "$@" -I"$file"
shift
;;
-I*)
func_file_conv "${1#-I}" mingw
set x "$@" -I"$file"
shift
;;
-l)
eat=1
func_cl_dashl "$2"
set x "$@" "$lib"
shift
;;
-l*)
func_cl_dashl "${1#-l}"
set x "$@" "$lib"
shift
;;
-L)
eat=1
func_cl_dashL "$2"
;;
-L*)
func_cl_dashL "${1#-L}"
;;
-static)
shared=false
;;
-Wl,*)
arg=${1#-Wl,}
save_ifs="$IFS"; IFS=','
for flag in $arg; do
IFS="$save_ifs"
linker_opts="$linker_opts $flag"
done
IFS="$save_ifs"
;;
-Xlinker)
eat=1
linker_opts="$linker_opts $2"
;;
-*)
set x "$@" "$1"
shift
;;
*.cc | *.CC | *.cxx | *.CXX | *.[cC]++)
func_file_conv "$1"
set x "$@" -Tp"$file"
shift
;;
*.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO])
func_file_conv "$1" mingw
set x "$@" "$file"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -n "$linker_opts"; then
linker_opts="-link$linker_opts"
fi
exec "$@" $linker_opts
exit 1
}
eat=
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: compile [--help] [--version] PROGRAM [ARGS]
Wrapper for compilers which do not understand '-c -o'.
Remove '-o dest.o' from ARGS, run PROGRAM with the remaining
arguments, and rename the output as expected.
If you are trying to build a whole package this is not the
right script to run: please start by reading the file 'INSTALL'.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
EOF
exit $?
;;
-v | --v*)
echo "compile (GNU Automake) $scriptversion"
exit $?
;;
cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \
clang-cl | *[/\\]clang-cl | clang-cl.exe | *[/\\]clang-cl.exe | \
icl | *[/\\]icl | icl.exe | *[/\\]icl.exe )
func_cl_wrapper "$@" # Doesn't return...
;;
esac
ofile=
cfile=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
# So we strip '-o arg' only if arg is an object.
eat=1
case $2 in
*.o | *.obj)
ofile=$2
;;
*)
set x "$@" -o "$2"
shift
;;
esac
;;
*.c)
cfile=$1
set x "$@" "$1"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -z "$ofile" || test -z "$cfile"; then
# If no '-o' option was seen then we might have been invoked from a
# pattern rule where we don't need one. That is ok -- this is a
# normal compilation that the losing compiler can handle. If no
# '.c' file was seen then we are probably linking. That is also
# ok.
exec "$@"
fi
# Name of file we expect compiler to create.
cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
# Create the lock directory.
# Note: use '[/\\:.-]' here to ensure that we don't use the same name
# that we are using for the .o file. Also, base the name on the expected
# object file name, since that is what matters with a parallel build.
lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
while true; do
if mkdir "$lockdir" >/dev/null 2>&1; then
break
fi
sleep 1
done
# FIXME: race condition here if user kills between mkdir and trap.
trap "rmdir '$lockdir'; exit 1" 1 2 15
# Run the compile.
"$@"
ret=$?
if test -f "$cofile"; then
test "$cofile" = "$ofile" || mv "$cofile" "$ofile"
elif test -f "${cofile}bj"; then
test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile"
fi
rmdir "$lockdir"
exit $ret
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+792
View File
@@ -0,0 +1,792 @@
#! /bin/sh
# depcomp - compile a program generating dependencies as side-effects
scriptversion=2024-06-19.01; # UTC
# Copyright (C) 1999-2024 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: depcomp [--help] [--version] PROGRAM [ARGS]
Run PROGRAMS ARGS to compile a file, generating dependencies
as side-effects.
Environment variables:
depmode Dependency tracking mode.
source Source file read by 'PROGRAMS ARGS'.
object Object file output by 'PROGRAMS ARGS'.
DEPDIR directory where to store dependencies.
depfile Dependency file to output.
tmpdepfile Temporary file to use when outputting dependencies.
libtool Whether libtool is used (yes/no).
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
EOF
exit $?
;;
-v | --v*)
echo "depcomp (GNU Automake) $scriptversion"
exit $?
;;
esac
# Get the directory component of the given path, and save it in the
# global variables '$dir'. Note that this directory component will
# be either empty or ending with a '/' character. This is deliberate.
set_dir_from ()
{
case $1 in
*/*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;;
*) dir=;;
esac
}
# Get the suffix-stripped basename of the given path, and save it the
# global variable '$base'.
set_base_from ()
{
base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'`
}
# If no dependency file was actually created by the compiler invocation,
# we still have to create a dummy depfile, to avoid errors with the
# Makefile "include basename.Plo" scheme.
make_dummy_depfile ()
{
echo "#dummy" > "$depfile"
}
# Factor out some common post-processing of the generated depfile.
# Requires the auxiliary global variable '$tmpdepfile' to be set.
aix_post_process_depfile ()
{
# If the compiler actually managed to produce a dependency file,
# post-process it.
if test -f "$tmpdepfile"; then
# Each line is of the form 'foo.o: dependency.h'.
# Do two passes, one to just change these to
# $object: dependency.h
# and one to simply output
# dependency.h:
# which is needed to avoid the deleted-header problem.
{ sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile"
sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile"
} > "$depfile"
rm -f "$tmpdepfile"
else
make_dummy_depfile
fi
}
# A tabulation character.
tab=' '
# A newline character.
nl='
'
# Character ranges might be problematic outside the C locale.
# These definitions help.
upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lower=abcdefghijklmnopqrstuvwxyz
alpha=${upper}${lower}
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
echo "depcomp: Variables source, object and depmode must be set" 1>&2
exit 1
fi
# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
depfile=${depfile-`echo "$object" |
sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
rm -f "$tmpdepfile"
# Avoid interference from the environment.
gccflag= dashmflag=
# Some modes work just like other modes, but use different flags. We
# parameterize here, but still list the modes in the big case below,
# to make depend.m4 easier to write. Note that we *cannot* use a case
# here, because this file can only contain one case statement.
if test "$depmode" = hp; then
# HP compiler uses -M and no extra arg.
gccflag=-M
depmode=gcc
fi
if test "$depmode" = dashXmstdout; then
# This is just like dashmstdout with a different argument.
dashmflag=-xM
depmode=dashmstdout
fi
cygpath_u="cygpath -u -f -"
if test "$depmode" = msvcmsys; then
# This is just like msvisualcpp but w/o cygpath translation.
# Just convert the backslash-escaped backslashes to single forward
# slashes to satisfy depend.m4
cygpath_u='sed s,\\\\,/,g'
depmode=msvisualcpp
fi
if test "$depmode" = msvc7msys; then
# This is just like msvc7 but w/o cygpath translation.
# Just convert the backslash-escaped backslashes to single forward
# slashes to satisfy depend.m4
cygpath_u='sed s,\\\\,/,g'
depmode=msvc7
fi
if test "$depmode" = xlc; then
# IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information.
gccflag=-qmakedep=gcc,-MF
depmode=gcc
fi
case "$depmode" in
gcc3)
## gcc 3 implements dependency tracking that does exactly what
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
## it if -MD -MP comes after the -MF stuff. Hmm.
## Unfortunately, FreeBSD c89 acceptance of flags depends upon
## the command line argument order; so add the flags where they
## appear in depend2.am. Note that the slowdown incurred here
## affects only configure: in makefiles, %FASTDEP% shortcuts this.
for arg
do
case $arg in
-c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
*) set fnord "$@" "$arg" ;;
esac
shift # fnord
shift # $arg
done
"$@"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
mv "$tmpdepfile" "$depfile"
;;
gcc)
## Note that this doesn't just cater to obsolete pre-3.x GCC compilers.
## but also to in-use compilers like IBM xlc/xlC and the HP C compiler.
## (see the conditional assignment to $gccflag above).
## There are various ways to get dependency output from gcc. Here's
## why we pick this rather obscure method:
## - Don't want to use -MD because we'd like the dependencies to end
## up in a subdir. Having to rename by hand is ugly.
## (We might end up doing this anyway to support other compilers.)
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
## -MM, not -M (despite what the docs say). Also, it might not be
## supported by the other compilers which use the 'gcc' depmode.
## - Using -M directly means running the compiler twice (even worse
## than renaming).
if test -z "$gccflag"; then
gccflag=-MD,
fi
"$@" -Wp,"$gccflag$tmpdepfile"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
# The second -e expression handles DOS-style file names with drive
# letters.
sed -e 's/^[^:]*: / /' \
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
## This next piece of magic avoids the "deleted header file" problem.
## The problem is that when a header file which appears in a .P file
## is deleted, the dependency causes make to die (because there is
## typically no way to rebuild the header). We avoid this by adding
## dummy dependencies for each header file. Too bad gcc doesn't do
## this for us directly.
## Some versions of gcc put a space before the ':'. On the theory
## that the space means something, we add a space to the output as
## well. hp depmode also adds that space, but also prefixes the VPATH
## to the object. Take care to not repeat it in the output.
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
sgi)
if test "$libtool" = yes; then
"$@" "-Wp,-MDupdate,$tmpdepfile"
else
"$@" -MDupdate "$tmpdepfile"
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
echo "$object : \\" > "$depfile"
# Clip off the initial element (the dependent). Don't try to be
# clever and replace this with sed code, as IRIX sed won't handle
# lines with more than a fixed number of characters (4096 in
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
# the IRIX cc adds comments like '#:fec' to the end of the
# dependency line.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \
| tr "$nl" ' ' >> "$depfile"
echo >> "$depfile"
# The second pass generates a dummy entry for each header file.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
>> "$depfile"
else
make_dummy_depfile
fi
rm -f "$tmpdepfile"
;;
xlc)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
aix)
# The C for AIX Compiler uses -M and outputs the dependencies
# in a .u file. In older versions, this file always lives in the
# current directory. Also, the AIX compiler puts '$object:' at the
# start of each line; $object doesn't have directory information.
# Version 6 uses the directory in both cases.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.u
tmpdepfile2=$base.u
tmpdepfile3=$dir.libs/$base.u
"$@" -Wc,-M
else
tmpdepfile1=$dir$base.u
tmpdepfile2=$dir$base.u
tmpdepfile3=$dir$base.u
"$@" -M
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
aix_post_process_depfile
;;
tcc)
# tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26
# FIXME: That version still under development at the moment of writing.
# Make that this statement remains true also for stable, released
# versions.
# It will wrap lines (doesn't matter whether long or short) with a
# trailing '\', as in:
#
# foo.o : \
# foo.c \
# foo.h \
#
# It will put a trailing '\' even on the last line, and will use leading
# spaces rather than leading tabs (at least since its commit 0394caf7
# "Emit spaces for -MD").
"$@" -MD -MF "$tmpdepfile"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each non-empty line is of the form 'foo.o : \' or ' dep.h \'.
# We have to change lines of the first kind to '$object: \'.
sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile"
# And for each line of the second kind, we have to emit a 'dep.h:'
# dummy dependency, to avoid the deleted-header problem.
sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile"
rm -f "$tmpdepfile"
;;
## The order of this option in the case statement is important, since the
## shell code in configure will try each of these formats in the order
## listed in this file. A plain '-MD' option would be understood by many
## compilers, so we must ensure this comes after the gcc and icc options.
pgcc)
# Portland's C compiler understands '-MD'.
# Will always output deps to 'file.d' where file is the root name of the
# source file under compilation, even if file resides in a subdirectory.
# The object file name does not affect the name of the '.d' file.
# pgcc 10.2 will output
# foo.o: sub/foo.c sub/foo.h
# and will wrap long lines using '\' :
# foo.o: sub/foo.c ... \
# sub/foo.h ... \
# ...
set_dir_from "$object"
# Use the source, not the object, to determine the base name, since
# that's sadly what pgcc will do too.
set_base_from "$source"
tmpdepfile=$base.d
# For projects that build the same source file twice into different object
# files, the pgcc approach of using the *source* file root name can cause
# problems in parallel builds. Use a locking strategy to avoid stomping on
# the same $tmpdepfile.
lockdir=$base.d-lock
trap "
echo '$0: caught signal, cleaning up...' >&2
rmdir '$lockdir'
exit 1
" 1 2 13 15
numtries=100
i=$numtries
while test $i -gt 0; do
# mkdir is a portable test-and-set.
if mkdir "$lockdir" 2>/dev/null; then
# This process acquired the lock.
"$@" -MD
stat=$?
# Release the lock.
rmdir "$lockdir"
break
else
# If the lock is being held by a different process, wait
# until the winning process is done or we timeout.
while test -d "$lockdir" && test $i -gt 0; do
sleep 1
i=`expr $i - 1`
done
fi
i=`expr $i - 1`
done
trap - 1 2 13 15
if test $i -le 0; then
echo "$0: failed to acquire lock after $numtries attempts" >&2
echo "$0: check lockdir '$lockdir'" >&2
exit 1
fi
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each line is of the form `foo.o: dependent.h',
# or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp2)
# The "hp" stanza above does not work with aCC (C++) and HP's ia64
# compilers, which have integrated preprocessors. The correct option
# to use with these is +Maked; it writes dependencies to a file named
# 'foo.d', which lands next to the object file, wherever that
# happens to be.
# Much of this is similar to the tru64 case; see comments there.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir.libs/$base.d
"$@" -Wc,+Maked
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
"$@" +Maked
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile"
# Add 'dependent.h:' lines.
sed -ne '2,${
s/^ *//
s/ \\*$//
s/$/:/
p
}' "$tmpdepfile" >> "$depfile"
else
make_dummy_depfile
fi
rm -f "$tmpdepfile" "$tmpdepfile2"
;;
tru64)
# The Tru64 compiler uses -MD to generate dependencies as a side
# effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'.
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
# dependencies in 'foo.d' instead, so we check for that too.
# Subdirectories are respected.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
# Libtool generates 2 separate objects for the 2 libraries. These
# two compilations output dependencies in $dir.libs/$base.o.d and
# in $dir$base.o.d. We have to check for both files, because
# one of the two compilations can be disabled. We should prefer
# $dir$base.o.d over $dir.libs/$base.o.d because the latter is
# automatically cleaned when .libs/ is deleted, while ignoring
# the former would cause a distcleancheck panic.
tmpdepfile1=$dir$base.o.d # libtool 1.5
tmpdepfile2=$dir.libs/$base.o.d # Likewise.
tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504
"$@" -Wc,-MD
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
tmpdepfile3=$dir$base.d
"$@" -MD
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
# Same post-processing that is required for AIX mode.
aix_post_process_depfile
;;
msvc7)
if test "$libtool" = yes; then
showIncludes=-Wc,-showIncludes
else
showIncludes=-showIncludes
fi
"$@" $showIncludes > "$tmpdepfile"
stat=$?
grep -v '^Note: including file: ' "$tmpdepfile"
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
# The first sed program below extracts the file names and escapes
# backslashes for cygpath. The second sed program outputs the file
# name when reading, but also accumulates all include files in the
# hold buffer in order to output them again at the end. This only
# works with sed implementations that can handle large buffers.
sed < "$tmpdepfile" -n '
/^Note: including file: *\(.*\)/ {
s//\1/
s/\\/\\\\/g
p
}' | $cygpath_u | sort -u | sed -n '
s/ /\\ /g
s/\(.*\)/'"$tab"'\1 \\/p
s/.\(.*\) \\/\1:/
H
$ {
s/.*/'"$tab"'/
G
p
}' >> "$depfile"
echo >> "$depfile" # make sure the fragment doesn't end with a backslash
rm -f "$tmpdepfile"
;;
msvc7msys)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
#nosideeffect)
# This comment above is used by automake to tell side-effect
# dependency tracking mechanisms from slower ones.
dashmstdout)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# Remove '-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
test -z "$dashmflag" && dashmflag=-M
# Require at least two characters before searching for ':'
# in the target name. This is to cope with DOS-style filenames:
# a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise.
"$@" $dashmflag |
sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this sed invocation
# correctly. Breaking it into two sed invocations is a workaround.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
dashXmstdout)
# This case only exists to satisfy depend.m4. It is never actually
# run, as this mode is specially recognized in the preamble.
exit 1
;;
makedepend)
"$@" || exit $?
# Remove any Libtool call
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# X makedepend
shift
cleared=no eat=no
for arg
do
case $cleared in
no)
set ""; shift
cleared=yes ;;
esac
if test $eat = yes; then
eat=no
continue
fi
case "$arg" in
-D*|-I*)
set fnord "$@" "$arg"; shift ;;
# Strip any option that makedepend may not understand. Remove
# the object too, otherwise makedepend will parse it as a source file.
-arch)
eat=yes ;;
-*|$object)
;;
*)
set fnord "$@" "$arg"; shift ;;
esac
done
obj_suffix=`echo "$object" | sed 's/^.*\././'`
touch "$tmpdepfile"
${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
rm -f "$depfile"
# makedepend may prepend the VPATH from the source file name to the object.
# No need to regex-escape $object, excess matching of '.' is harmless.
sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process the last invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed '1,2d' "$tmpdepfile" \
| tr ' ' "$nl" \
| sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile" "$tmpdepfile".bak
;;
cpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# Remove '-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
"$@" -E \
| sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
| sed '$ s: \\$::' > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
cat < "$tmpdepfile" >> "$depfile"
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvisualcpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
IFS=" "
for arg
do
case "$arg" in
-o)
shift
;;
$object)
shift
;;
"-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
set fnord "$@"
shift
shift
;;
*)
set fnord "$@" "$arg"
shift
shift
;;
esac
done
"$@" -E 2>/dev/null |
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile"
echo "$tab" >> "$depfile"
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvcmsys)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
none)
exec "$@"
;;
*)
echo "Unknown depmode $depmode" 1>&2
exit 1
;;
esac
exit 0
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
+541
View File
@@ -0,0 +1,541 @@
#!/bin/sh
# install - install a program, script, or datafile
scriptversion=2024-06-19.01; # UTC
# This originates from X11R5 (mit/util/scripts/install.sh), which was
# later released in X11R6 (xc/config/util/install.sh) with the
# following copyright and license.
#
# Copyright (C) 1994 X Consortium
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of the X Consortium shall not
# be used in advertising or otherwise to promote the sale, use or other deal-
# ings in this Software without prior written authorization from the X Consor-
# tium.
#
#
# FSF changes to this file are in the public domain.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# 'make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.
tab=' '
nl='
'
IFS=" $tab$nl"
# Set DOITPROG to "echo" to test this script.
doit=${DOITPROG-}
doit_exec=${doit:-exec}
# Put in absolute file names if you don't have them in your path;
# or use environment vars.
chgrpprog=${CHGRPPROG-chgrp}
chmodprog=${CHMODPROG-chmod}
chownprog=${CHOWNPROG-chown}
cmpprog=${CMPPROG-cmp}
cpprog=${CPPROG-cp}
mkdirprog=${MKDIRPROG-mkdir}
mvprog=${MVPROG-mv}
rmprog=${RMPROG-rm}
stripprog=${STRIPPROG-strip}
posix_mkdir=
# Desired mode of installed file.
mode=0755
# Create dirs (including intermediate dirs) using mode 755.
# This is like GNU 'install' as of coreutils 8.32 (2020).
mkdir_umask=22
backupsuffix=
chgrpcmd=
chmodcmd=$chmodprog
chowncmd=
mvcmd=$mvprog
rmcmd="$rmprog -f"
stripcmd=
src=
dst=
dir_arg=
dst_arg=
copy_on_change=false
is_target_a_directory=possibly
usage="\
Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
or: $0 [OPTION]... SRCFILES... DIRECTORY
or: $0 [OPTION]... -t DIRECTORY SRCFILES...
or: $0 [OPTION]... -d DIRECTORIES...
In the 1st form, copy SRCFILE to DSTFILE.
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
In the 4th, create DIRECTORIES.
Options:
--help display this help and exit.
--version display version info and exit.
-c (ignored)
-C install only if different (preserve data modification time)
-d create directories instead of installing files.
-g GROUP $chgrpprog installed files to GROUP.
-m MODE $chmodprog installed files to MODE.
-o USER $chownprog installed files to USER.
-p pass -p to $cpprog.
-s $stripprog installed files.
-S SUFFIX attempt to back up existing files, with suffix SUFFIX.
-t DIRECTORY install into DIRECTORY.
-T report an error if DSTFILE is a directory.
Environment variables override the default commands:
CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
RMPROG STRIPPROG
By default, rm is invoked with -f; when overridden with RMPROG,
it's up to you to specify -f if you want it.
If -S is not specified, no backups are attempted.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>."
while test $# -ne 0; do
case $1 in
-c) ;;
-C) copy_on_change=true;;
-d) dir_arg=true;;
-g) chgrpcmd="$chgrpprog $2"
shift;;
--help) echo "$usage"; exit $?;;
-m) mode=$2
case $mode in
*' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
echo "$0: invalid mode: $mode" >&2
exit 1;;
esac
shift;;
-o) chowncmd="$chownprog $2"
shift;;
-p) cpprog="$cpprog -p";;
-s) stripcmd=$stripprog;;
-S) backupsuffix="$2"
shift;;
-t)
is_target_a_directory=always
dst_arg=$2
# Protect names problematic for 'test' and other utilities.
case $dst_arg in
-* | [=\(\)!]) dst_arg=./$dst_arg;;
esac
shift;;
-T) is_target_a_directory=never;;
--version) echo "$0 (GNU Automake) $scriptversion"; exit $?;;
--) shift
break;;
-*) echo "$0: invalid option: $1" >&2
exit 1;;
*) break;;
esac
shift
done
# We allow the use of options -d and -T together, by making -d
# take the precedence; this is for compatibility with GNU install.
if test -n "$dir_arg"; then
if test -n "$dst_arg"; then
echo "$0: target directory not allowed when installing a directory." >&2
exit 1
fi
fi
if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
# When -d is used, all remaining arguments are directories to create.
# When -t is used, the destination is already specified.
# Otherwise, the last argument is the destination. Remove it from $@.
for arg
do
if test -n "$dst_arg"; then
# $@ is not empty: it contains at least $arg.
set fnord "$@" "$dst_arg"
shift # fnord
fi
shift # arg
dst_arg=$arg
# Protect names problematic for 'test' and other utilities.
case $dst_arg in
-* | [=\(\)!]) dst_arg=./$dst_arg;;
esac
done
fi
if test $# -eq 0; then
if test -z "$dir_arg"; then
echo "$0: no input file specified." >&2
exit 1
fi
# It's OK to call 'install-sh -d' without argument.
# This can happen when creating conditional directories.
exit 0
fi
if test -z "$dir_arg"; then
if test $# -gt 1 || test "$is_target_a_directory" = always; then
if test ! -d "$dst_arg"; then
echo "$0: $dst_arg: Is not a directory." >&2
exit 1
fi
fi
fi
if test -z "$dir_arg"; then
do_exit='(exit $ret); exit $ret'
trap "ret=129; $do_exit" 1
trap "ret=130; $do_exit" 2
trap "ret=141; $do_exit" 13
trap "ret=143; $do_exit" 15
# Set umask so as not to create temps with too-generous modes.
# However, 'strip' requires both read and write access to temps.
case $mode in
# Optimize common cases.
*644) cp_umask=133;;
*755) cp_umask=22;;
*[0-7])
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw='% 200'
fi
cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
*)
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw=,u+rw
fi
cp_umask=$mode$u_plus_rw;;
esac
fi
for src
do
# Protect names problematic for 'test' and other utilities.
case $src in
-* | [=\(\)!]) src=./$src;;
esac
if test -n "$dir_arg"; then
dst=$src
dstdir=$dst
test -d "$dstdir"
dstdir_status=$?
# Don't chown directories that already exist.
if test $dstdir_status = 0; then
chowncmd=""
fi
else
# Waiting for this to be detected by the "$cpprog $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if test ! -f "$src" && test ! -d "$src"; then
echo "$0: $src does not exist." >&2
exit 1
fi
if test -z "$dst_arg"; then
echo "$0: no destination specified." >&2
exit 1
fi
dst=$dst_arg
# If destination is a directory, append the input filename.
if test -d "$dst"; then
if test "$is_target_a_directory" = never; then
echo "$0: $dst_arg: Is a directory" >&2
exit 1
fi
dstdir=$dst
dstbase=`basename "$src"`
case $dst in
*/) dst=$dst$dstbase;;
*) dst=$dst/$dstbase;;
esac
dstdir_status=0
else
dstdir=`dirname "$dst"`
test -d "$dstdir"
dstdir_status=$?
fi
fi
case $dstdir in
*/) dstdirslash=$dstdir;;
*) dstdirslash=$dstdir/;;
esac
obsolete_mkdir_used=false
if test $dstdir_status != 0; then
case $posix_mkdir in
'')
# With -d, create the new directory with the user-specified mode.
# Otherwise, rely on $mkdir_umask.
if test -n "$dir_arg"; then
mkdir_mode=-m$mode
else
mkdir_mode=
fi
posix_mkdir=false
# The $RANDOM variable is not portable (e.g., dash). Use it
# here however when possible just to lower collision chance.
tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
trap '
ret=$?
rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
exit $ret
' 0
# Because "mkdir -p" follows existing symlinks and we likely work
# directly in world-writable /tmp, make sure that the '$tmpdir'
# directory is successfully created first before we actually test
# 'mkdir -p'.
if (umask $mkdir_umask &&
$mkdirprog $mkdir_mode "$tmpdir" &&
exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
then
if test -z "$dir_arg" || {
# Check for POSIX incompatibility with -m.
# HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
# other-writable bit of parent directory when it shouldn't.
# FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
test_tmpdir="$tmpdir/a"
ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
case $ls_ld_tmpdir in
d????-?r-*) different_mode=700;;
d????-?--*) different_mode=755;;
*) false;;
esac &&
$mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
}
}
then posix_mkdir=:
fi
rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
else
# Remove any dirs left behind by ancient mkdir implementations.
rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
fi
trap '' 0;;
esac
if
$posix_mkdir && (
umask $mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
)
then :
else
# mkdir does not conform to POSIX,
# or it failed possibly due to a race condition. Create the
# directory the slow way, step by step, checking for races as we go.
case $dstdir in
/*) prefix='/';;
[-=\(\)!]*) prefix='./';;
*) prefix='';;
esac
oIFS=$IFS
IFS=/
set -f
set fnord $dstdir
shift
set +f
IFS=$oIFS
prefixes=
for d
do
test X"$d" = X && continue
prefix=$prefix$d
if test -d "$prefix"; then
prefixes=
else
if $posix_mkdir; then
(umask $mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
# Don't fail if two instances are running concurrently.
test -d "$prefix" || exit 1
else
case $prefix in
*\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
*) qprefix=$prefix;;
esac
prefixes="$prefixes '$qprefix'"
fi
fi
prefix=$prefix/
done
if test -n "$prefixes"; then
# Don't fail if two instances are running concurrently.
(umask $mkdir_umask &&
eval "\$doit_exec \$mkdirprog $prefixes") ||
test -d "$dstdir" || exit 1
obsolete_mkdir_used=true
fi
fi
fi
if test -n "$dir_arg"; then
{ test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
{ test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
else
# Make a couple of temp file names in the proper directory.
dsttmp=${dstdirslash}_inst.$$_
rmtmp=${dstdirslash}_rm.$$_
# Trap to clean up those temp files at exit.
trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
# Copy the file name to the temp name.
(umask $cp_umask &&
{ test -z "$stripcmd" || {
# Create $dsttmp read-write so that cp doesn't create it read-only,
# which would cause strip to fail.
if test -z "$doit"; then
: >"$dsttmp" # No need to fork-exec 'touch'.
else
$doit touch "$dsttmp"
fi
}
} &&
$doit_exec $cpprog "$src" "$dsttmp") &&
# and set any options; do chmod last to preserve setuid bits.
#
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $cpprog $src $dsttmp" command.
#
{ test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
{ test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
{ test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
# If -C, don't bother to copy if it wouldn't change the file.
if $copy_on_change &&
old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` &&
new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
set -f &&
set X $old && old=:$2:$4:$5:$6 &&
set X $new && new=:$2:$4:$5:$6 &&
set +f &&
test "$old" = "$new" &&
$cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
then
rm -f "$dsttmp"
else
# If $backupsuffix is set, and the file being installed
# already exists, attempt a backup. Don't worry if it fails,
# e.g., if mv doesn't support -f.
if test -n "$backupsuffix" && test -f "$dst"; then
$doit $mvcmd -f "$dst" "$dst$backupsuffix" 2>/dev/null
fi
# Rename the file to the real destination.
$doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
# The rename failed, perhaps because mv can't rename something else
# to itself, or perhaps because mv is so ancient that it does not
# support -f.
{
# Now remove or move aside any old file at destination location.
# We try this two ways since rm can't unlink itself on some
# systems and the destination file might be busy for other
# reasons. In this case, the final cleanup might fail but the new
# file should still install successfully.
{
test ! -f "$dst" ||
$doit $rmcmd "$dst" 2>/dev/null ||
{ $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
{ $doit $rmcmd "$rmtmp" 2>/dev/null; :; }
} ||
{ echo "$0: cannot unlink or rename $dst" >&2
(exit 1); exit 1
}
} &&
# Now rename the file to the real destination.
$doit $mvcmd "$dsttmp" "$dst"
}
fi || exit 1
trap '' 0
fi
done
# Local variables:
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,467 @@
# Helper functions for option handling. -*- Autoconf -*-
#
# Copyright (C) 2004-2005, 2007-2009, 2011-2019, 2021-2024 Free
# Software Foundation, Inc.
# Written by Gary V. Vaughan, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 10 ltoptions.m4
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
# ------------------------------------------
m4_define([_LT_MANGLE_OPTION],
[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
# ---------------------------------------
# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
# matching handler defined, dispatch to it. Other OPTION-NAMEs are
# saved as a flag.
m4_define([_LT_SET_OPTION],
[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
_LT_MANGLE_DEFUN([$1], [$2]),
[m4_warning([Unknown $1 option '$2'])])[]dnl
])
# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
# ------------------------------------------------------------
# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
m4_define([_LT_IF_OPTION],
[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
# -------------------------------------------------------
# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
# are set.
m4_define([_LT_UNLESS_OPTIONS],
[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
[m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
[m4_define([$0_found])])])[]dnl
m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
])[]dnl
])
# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
# ----------------------------------------
# OPTION-LIST is a space-separated list of Libtool options associated
# with MACRO-NAME. If any OPTION has a matching handler declared with
# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
# the unknown option and exit.
m4_defun([_LT_SET_OPTIONS],
[# Set options
m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
[_LT_SET_OPTION([$1], _LT_Option)])
m4_if([$1],[LT_INIT],[
dnl
dnl Simply set some default values (i.e off) if boolean options were not
dnl specified:
_LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
])
_LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
])
dnl
dnl If no reference was made to various pairs of opposing options, then
dnl we run the default mode handler for the pair. For example, if neither
dnl 'shared' nor 'disable-shared' was passed, we enable building of shared
dnl archives by default:
_LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
_LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
_LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
_LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
[_LT_ENABLE_FAST_INSTALL])
_LT_UNLESS_OPTIONS([LT_INIT], [aix-soname=aix aix-soname=both aix-soname=svr4],
[_LT_WITH_AIX_SONAME([aix])])
])
])# _LT_SET_OPTIONS
## --------------------------------- ##
## Macros to handle LT_INIT options. ##
## --------------------------------- ##
# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
# -----------------------------------------
m4_define([_LT_MANGLE_DEFUN],
[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
# -----------------------------------------------
m4_define([LT_OPTION_DEFINE],
[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
])# LT_OPTION_DEFINE
# dlopen
# ------
LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
])
AU_DEFUN([AC_LIBTOOL_DLOPEN],
[_LT_SET_OPTION([LT_INIT], [dlopen])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the 'dlopen' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
# win32-dll
# ---------
# Declare package support for building win32 dll's.
LT_OPTION_DEFINE([LT_INIT], [win32-dll],
[enable_win32_dll=yes
case $host in
*-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-cegcc*)
AC_CHECK_TOOL(AS, as, false)
AC_CHECK_TOOL(DLLTOOL, dlltool, false)
AC_CHECK_TOOL(OBJDUMP, objdump, false)
;;
esac
test -z "$AS" && AS=as
_LT_DECL([], [AS], [1], [Assembler program])dnl
test -z "$DLLTOOL" && DLLTOOL=dlltool
_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
test -z "$OBJDUMP" && OBJDUMP=objdump
_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
])# win32-dll
AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
_LT_SET_OPTION([LT_INIT], [win32-dll])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the 'win32-dll' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
# _LT_ENABLE_SHARED([DEFAULT])
# ----------------------------
# implement the --enable-shared flag, and supports the 'shared' and
# 'disable-shared' LT_INIT options.
# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'.
m4_define([_LT_ENABLE_SHARED],
[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([shared],
[AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
[p=${PACKAGE-default}
case $enableval in
yes) enable_shared=yes ;;
no) enable_shared=no ;;
*)
enable_shared=no
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$pkg" = "X$p"; then
enable_shared=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
_LT_DECL([build_libtool_libs], [enable_shared], [0],
[Whether or not to build shared libraries])
])# _LT_ENABLE_SHARED
LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
# Old names:
AC_DEFUN([AC_ENABLE_SHARED],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
])
AC_DEFUN([AC_DISABLE_SHARED],
[_LT_SET_OPTION([LT_INIT], [disable-shared])
])
AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_ENABLE_SHARED], [])
dnl AC_DEFUN([AM_DISABLE_SHARED], [])
# _LT_ENABLE_STATIC([DEFAULT])
# ----------------------------
# implement the --enable-static flag, and support the 'static' and
# 'disable-static' LT_INIT options.
# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'.
m4_define([_LT_ENABLE_STATIC],
[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([static],
[AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
[p=${PACKAGE-default}
case $enableval in
yes) enable_static=yes ;;
no) enable_static=no ;;
*)
enable_static=no
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$pkg" = "X$p"; then
enable_static=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[enable_static=]_LT_ENABLE_STATIC_DEFAULT)
_LT_DECL([build_old_libs], [enable_static], [0],
[Whether or not to build static libraries])
])# _LT_ENABLE_STATIC
LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
# Old names:
AC_DEFUN([AC_ENABLE_STATIC],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
])
AC_DEFUN([AC_DISABLE_STATIC],
[_LT_SET_OPTION([LT_INIT], [disable-static])
])
AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_ENABLE_STATIC], [])
dnl AC_DEFUN([AM_DISABLE_STATIC], [])
# _LT_ENABLE_FAST_INSTALL([DEFAULT])
# ----------------------------------
# implement the --enable-fast-install flag, and support the 'fast-install'
# and 'disable-fast-install' LT_INIT options.
# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'.
m4_define([_LT_ENABLE_FAST_INSTALL],
[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([fast-install],
[AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
[optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
[p=${PACKAGE-default}
case $enableval in
yes) enable_fast_install=yes ;;
no) enable_fast_install=no ;;
*)
enable_fast_install=no
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$pkg" = "X$p"; then
enable_fast_install=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
_LT_DECL([fast_install], [enable_fast_install], [0],
[Whether or not to optimize for fast installation])dnl
])# _LT_ENABLE_FAST_INSTALL
LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
# Old names:
AU_DEFUN([AC_ENABLE_FAST_INSTALL],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you put
the 'fast-install' option into LT_INIT's first parameter.])
])
AU_DEFUN([AC_DISABLE_FAST_INSTALL],
[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you put
the 'disable-fast-install' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
# _LT_WITH_AIX_SONAME([DEFAULT])
# ----------------------------------
# implement the --enable-aix-soname configure option, and support the
# `aix-soname=aix' and `aix-soname=both' and `aix-soname=svr4' LT_INIT options.
# DEFAULT is either `aix', `both', or `svr4'. If omitted, it defaults to `aix'.
m4_define([_LT_WITH_AIX_SONAME],
[m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl
shared_archive_member_spec=
case $host,$enable_shared in
power*-*-aix[[5-9]]*,yes)
AC_MSG_CHECKING([which variant of shared library versioning to provide])
AC_ARG_ENABLE([aix-soname],
[AS_HELP_STRING([--enable-aix-soname=aix|svr4|both],
[shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])],
[case $enableval in
aix|svr4|both)
;;
*)
AC_MSG_ERROR([Unknown argument to --enable-aix-soname])
;;
esac
lt_cv_with_aix_soname=$enable_aix_soname],
[_AC_ENABLE_IF([with], [aix-soname],
[case $withval in
aix|svr4|both)
;;
*)
AC_MSG_ERROR([Unknown argument to --with-aix-soname])
;;
esac
lt_cv_with_aix_soname=$with_aix_soname],
[AC_CACHE_VAL([lt_cv_with_aix_soname],
[lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT)])
enable_aix_soname=$lt_cv_with_aix_soname])
with_aix_soname=$enable_aix_soname
AC_MSG_RESULT([$with_aix_soname])
if test aix != "$with_aix_soname"; then
# For the AIX way of multilib, we name the shared archive member
# based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o',
# and 'shr.imp' or 'shr_64.imp', respectively, for the Import File.
# Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag,
# the AIX toolchain works better with OBJECT_MODE set (default 32).
if test 64 = "${OBJECT_MODE-32}"; then
shared_archive_member_spec=shr_64
else
shared_archive_member_spec=shr
fi
fi
;;
*)
with_aix_soname=aix
;;
esac
_LT_DECL([], [shared_archive_member_spec], [0],
[Shared archive member basename, for filename based shared library versioning on AIX])dnl
])# _LT_WITH_AIX_SONAME
LT_OPTION_DEFINE([LT_INIT], [aix-soname=aix], [_LT_WITH_AIX_SONAME([aix])])
LT_OPTION_DEFINE([LT_INIT], [aix-soname=both], [_LT_WITH_AIX_SONAME([both])])
LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])])
# _LT_WITH_PIC([MODE])
# --------------------
# implement the --enable-pic flag, and support the 'pic-only' and 'no-pic'
# LT_INIT options.
# MODE is either 'yes' or 'no'. If omitted, it defaults to 'both'.
m4_define([_LT_WITH_PIC],
[AC_ARG_ENABLE([pic],
[AS_HELP_STRING([--enable-pic@<:@=PKGS@:>@],
[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
[lt_p=${PACKAGE-default}
case $enableval in
yes|no) pic_mode=$enableval ;;
*)
pic_mode=default
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for lt_pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$lt_pkg" = "X$lt_p"; then
pic_mode=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[dnl Continue to support --with-pic and --without-pic, for backward
dnl compatibility.
_AC_ENABLE_IF([with], [pic],
[lt_p=${PACKAGE-default}
case $withval in
yes|no) pic_mode=$withval ;;
*)
pic_mode=default
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for lt_pkg in $withval; do
IFS=$lt_save_ifs
if test "X$lt_pkg" = "X$lt_p"; then
pic_mode=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[pic_mode=m4_default([$1], [default])])]
)
_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
])# _LT_WITH_PIC
LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
# Old name:
AU_DEFUN([AC_LIBTOOL_PICMODE],
[_LT_SET_OPTION([LT_INIT], [pic-only])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the 'pic-only' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
## ----------------- ##
## LTDL_INIT Options ##
## ----------------- ##
m4_define([_LTDL_MODE], [])
LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
[m4_define([_LTDL_MODE], [nonrecursive])])
LT_OPTION_DEFINE([LTDL_INIT], [recursive],
[m4_define([_LTDL_MODE], [recursive])])
LT_OPTION_DEFINE([LTDL_INIT], [subproject],
[m4_define([_LTDL_MODE], [subproject])])
m4_define([_LTDL_TYPE], [])
LT_OPTION_DEFINE([LTDL_INIT], [installable],
[m4_define([_LTDL_TYPE], [installable])])
LT_OPTION_DEFINE([LTDL_INIT], [convenience],
[m4_define([_LTDL_TYPE], [convenience])])
@@ -0,0 +1,124 @@
# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*-
#
# Copyright (C) 2004-2005, 2007-2008, 2011-2019, 2021-2024 Free Software
# Foundation, Inc.
# Written by Gary V. Vaughan, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 6 ltsugar.m4
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
# lt_join(SEP, ARG1, [ARG2...])
# -----------------------------
# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
# associated separator.
# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
# versions in m4sugar had bugs.
m4_define([lt_join],
[m4_if([$#], [1], [],
[$#], [2], [[$2]],
[m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
m4_define([_lt_join],
[m4_if([$#$2], [2], [],
[m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
# lt_car(LIST)
# lt_cdr(LIST)
# ------------
# Manipulate m4 lists.
# These macros are necessary as long as will still need to support
# Autoconf-2.59, which quotes differently.
m4_define([lt_car], [[$1]])
m4_define([lt_cdr],
[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
[$#], 1, [],
[m4_dquote(m4_shift($@))])])
m4_define([lt_unquote], $1)
# lt_append(MACRO-NAME, STRING, [SEPARATOR])
# ------------------------------------------
# Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'.
# Note that neither SEPARATOR nor STRING are expanded; they are appended
# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
# No SEPARATOR is output if MACRO-NAME was previously undefined (different
# than defined and empty).
#
# This macro is needed until we can rely on Autoconf 2.62, since earlier
# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
m4_define([lt_append],
[m4_define([$1],
m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
# ----------------------------------------------------------
# Produce a SEP delimited list of all paired combinations of elements of
# PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list
# has the form PREFIXmINFIXSUFFIXn.
# Needed until we can rely on m4_combine added in Autoconf 2.62.
m4_define([lt_combine],
[m4_if(m4_eval([$# > 3]), [1],
[m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
[[m4_foreach([_Lt_prefix], [$2],
[m4_foreach([_Lt_suffix],
]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
# -----------------------------------------------------------------------
# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
m4_define([lt_if_append_uniq],
[m4_ifdef([$1],
[m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
[lt_append([$1], [$2], [$3])$4],
[$5])],
[lt_append([$1], [$2], [$3])$4])])
# lt_dict_add(DICT, KEY, VALUE)
# -----------------------------
m4_define([lt_dict_add],
[m4_define([$1($2)], [$3])])
# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
# --------------------------------------------
m4_define([lt_dict_add_subkey],
[m4_define([$1($2:$3)], [$4])])
# lt_dict_fetch(DICT, KEY, [SUBKEY])
# ----------------------------------
m4_define([lt_dict_fetch],
[m4_ifval([$3],
m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
# -----------------------------------------------------------------
m4_define([lt_if_dict_fetch],
[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
[$5],
[$6])])
# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
# --------------------------------------------------------------
m4_define([lt_dict_filter],
[m4_if([$5], [], [],
[lt_join(m4_quote(m4_default([$4], [[, ]])),
lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
[lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
])
@@ -0,0 +1,24 @@
# ltversion.m4 -- version numbers -*- Autoconf -*-
#
# Copyright (C) 2004, 2011-2019, 2021-2024 Free Software Foundation,
# Inc.
# Written by Scott James Remnant, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# @configure_input@
# serial 4441 ltversion.m4
# This file is part of GNU Libtool
m4_define([LT_PACKAGE_VERSION], [2.5.4])
m4_define([LT_PACKAGE_REVISION], [2.5.4])
AC_DEFUN([LTVERSION_VERSION],
[macro_version='2.5.4'
macro_revision='2.5.4'
_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
_LT_DECL(, macro_revision, 0)
])
@@ -0,0 +1,99 @@
# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*-
#
# Copyright (C) 2004-2005, 2007, 2009, 2011-2019, 2021-2024 Free
# Software Foundation, Inc.
# Written by Scott James Remnant, 2004.
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 5 lt~obsolete.m4
# These exist entirely to fool aclocal when bootstrapping libtool.
#
# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN),
# which have later been changed to m4_define as they aren't part of the
# exported API, or moved to Autoconf or Automake where they belong.
#
# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN
# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
# using a macro with the same name in our local m4/libtool.m4 it'll
# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
# and doesn't know about Autoconf macros at all.)
#
# So we provide this file, which has a silly filename so it's always
# included after everything else. This provides aclocal with the
# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
# because those macros already exist, or will be overwritten later.
# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6.
#
# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
# Yes, that means every name once taken will need to remain here until
# we give up compatibility with versions before 1.7, at which point
# we need to keep only those names which we still refer to.
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])])
m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])])
m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])])
m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])])
m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])])
m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])])
m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])])
m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])])
m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])])
m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])])
m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])])
m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])])
m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])])
m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])])
m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])])
m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])])
m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])])
m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])])
m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])])
m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])])
m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])])
m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])])
m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])])
m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])])
m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])])
m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])])
m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])])
@@ -0,0 +1,433 @@
/****************************************************
* PCRE maintainers' helper program: UTF-8 converter *
****************************************************/
/* This is a test program for converting character codepoints to UTF-8 and
vice versa. Note that this program conforms to the original definition of
UTF-8, which allows codepoints up to 7fffffff. The more recent definition
limits the validity of Unicode UTF-8 codepoints to a maximum of 10ffff, and
forbids the "surrogate" codepoints. This program now gives warnings for these
invalid codepoints.
The arguments are either single codepoint values written as U+hh.. or 0xhh..
for conversion to UTF-8, or sequences of hex values, written without a prefix
and optionally including spaces (but such arguments must be quoted), for
encoding from UTF-8 code units to Unicode codepoints. For example:
./utf8 0x1234
U+00001234 => e1 88 b4
./utf8 "e1 88 b4"
U+00001234 <= e1 88 b4
In the second case, a number of UTF-8 characters can be present in one
argument. In other words, each such argument is interpreted (after ignoring
spaces) as a string of UTF-8 bytes representing a string of characters:
./utf8 "65 e188b4 77"
0x00000065 <= 65
0x00001234 <= e1 88 b4
0x00000077 <= 77
If the option -s is given, the sequence of UTF-bytes is written out between
angle brackets at the end of the line, if valid. On a UTF-8 terminal, this
should show the appropriate graphic for the character or a question mark.
if the option -b is given, a file with the encoded bytes is written for use
with pcre2test in utf8_input format.
Errors provoke error messages, but the program carries on with the next
argument. The return code is always zero unless there was nothing to process
or an invalid option was provided and the "usage" was printed.
Philip Hazel
Original creation date: unknown
Code extended and tidied to avoid compiler warnings: 26 March 2020
Support for encoding utf8_input; 31 August 2025
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
/* The valid ranges for UTF-8 characters are:
0000 0000 to 0000 007f 1 byte (ascii)
0000 0080 to 0000 07ff 2 bytes
0000 0800 to 0000 ffff 3 bytes
0001 0000 to 001f ffff 4 bytes
0020 0000 to 03ff ffff 5 bytes
0400 0000 to 7fff ffff 6 bytes
*/
static const unsigned int utf8_table1[] = {
0x0000007f, 0x000007ff, 0x0000ffff, 0x001fffff, 0x03ffffff, 0x7fffffff};
static const unsigned char utf8_table2[] = {
0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc};
static const unsigned char utf8_table3[] = {
0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
/*************************************************
* Convert character value to UTF-8 *
*************************************************/
/* This function takes an unsigned long integer value in the range 0 -
0x7fffffff and encodes it as a UTF-8 character in 1 to 6 bytes.
Arguments:
cvalue the character value
buffer pointer to buffer for result - at least 6 bytes long
Returns: number of bytes placed in the buffer
0 if input codepoint is too big
*/
static size_t
ord2utf8(unsigned long int cvalue, unsigned char *buffer)
{
size_t i, j;
for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++)
if (cvalue <= utf8_table1[i]) break;
if (i >= sizeof(utf8_table1)/sizeof(int)) return 0;
buffer += i;
for (j = i; j > 0; j--)
{
*buffer-- = 0x80 | (cvalue & 0x3f);
cvalue >>= 6;
}
*buffer = (unsigned char)(utf8_table2[i] | cvalue);
return i + 1;
}
/*************************************************
* Convert UTF-8 string to value *
*************************************************/
/* This function takes one or more bytes that represent a UTF-8 character from
the start of a string of bytes. It returns the value of the character, or the
offset of a malformation. For an overlong encoding that works but is not the
correct (shortest) one, the error offset is just after the last byte.
Argument:
buffer a pointer to the byte vector
buffend a pointer to the end of the buffer
vptr a pointer to a variable to receive the value
lenptr a pointer to a variable to receive the offset when error detected
Returns: > 0 => the number of bytes consumed
0 => invalid UTF-8: first byte missing 0x40 bit
-1 => invalid UTF-8: first byte has too many high-order 1-bits
-2 => incomplete sequence at end of string
-3 => incomplete sequence within string
-4 => overlong code sequence
*/
static int
utf82ord(const unsigned char *buffer, const unsigned char *buffend,
long unsigned int *vptr, int *lenptr)
{
unsigned int c = *buffer++;
unsigned int d = c;
int i, j, s;
/* Check for an ASCII character, or find the number of additional bytes in a
multibyte character. */
for (i = -1; i < 6; i++)
{
if ((d & 0x80) == 0) break;
d <<= 1;
}
switch (i)
{
case -1: /* ASCII character; first byte does not have 0x80 bit */
*vptr = c;
return 1;
case 0: /* First byte has 0x80 but is missing 0x40 bit */
*lenptr = 0;
return 0;
case 6:
*lenptr = 0; /* Too many high bits */
return -1;
default:
break;
}
/* i now has a value in the range 1-5 */
s = 6 * i;
d = (c & utf8_table3[i]) << s;
for (j = 0; j < i; j++)
{
if (buffer >= buffend)
{
*lenptr = j + 1;
return -2;
}
c = *buffer++;
if ((c & 0xc0) != 0x80)
{
*lenptr = j + 1;
return -3;
}
s -= 6;
d |= (c & 0x3f) << s;
}
/* Valid UTF-8 syntax */
*vptr = d;
/* Check that encoding was the correct one, not overlong */
for (j = 0; j < (int)(sizeof(utf8_table1)/sizeof(int)); j++)
if (d <= utf8_table1[j]) break;
if (j != i)
{
*lenptr = i + 1;
return -4;
}
/* Valid value */
return i + 1;
}
/**********************************************
* Usage *
**********************************************/
static void
usage(const char *argv0)
{
printf("%s [option ..] argument ..\n\n", argv0);
puts("Encode/decode Unicode codepoints with UTF-8 code units\n");
puts("The arguments are either single codepoint values written as U+hh..");
puts("or 0xhh.. for conversion to UTF-8, or sequences of hex values,");
puts("written without a prefix and optionally including spaces (but such");
puts("arguments must be quoted), for encoding from UTF-8 code units to");
puts("Unicode codepoints.");
puts("For details on usage and examples read the comments in source code.\n");
puts("Options:\n");
puts(" -h|--help\tthis help");
puts(" -s\t\tprint character");
puts(" -b[=<file>]\twrite encoded data to file (default: testinput11)\n");
}
/*************************************************
* Main Program *
*************************************************/
int
main(int argc, char **argv)
{
int i = 1;
int show = 0;
unsigned char buffer[64];
const char *argv0 = "utf8";
FILE *f = NULL;
for (int c = argc; c-- > 1; i++)
{
const char *x = argv[i];
if (*x++ != '-') break;
if (*x == '-' && *++x == 0)
{
i++;
break;
}
switch (*x++)
{
case 's': show = 1; break;
case 'b':
{
const char *output = "testinput11";
if (*x++ == '=' && *x != 0) output = x;
f = fopen(output, "wb");
}
break;
default:
{
const char last_option = x[-1];
argv0 = argv[0];
usage(argv0);
return (last_option != 'h');
}
}
}
if (i >= argc)
{
usage(argv0);
return 1;
}
for (; i < argc; i++)
{
const char *x = argv[i];
if (strlen(x) >= 3 &&
(strncmp(x, "0x", 2) == 0 || strncmp(x, "U+", 2) == 0) &&
isxdigit(x[2]))
{
size_t rc;
unsigned long d;
char *endptr;
int utf8_input = 0;
errno = 0;
d = strtoul(x + 2, &endptr, 16);
if (errno != 0 || *endptr != 0)
{
printf("** Invalid hex number %s\n", x);
continue; /* With next argument */
}
if (d > 0xffffffff)
{
puts("** Code points must fit an uint32_t");
continue;
}
else if (f != NULL && d > 0x7fffffff)
{
buffer[0] = 0xff;
fwrite(buffer, 1, 1, f);
utf8_input = 1;
d &= 0x7fffffff;
}
rc = ord2utf8(d, buffer);
printf("U+%08lx => ", d);
if (rc == 0)
fputs("** -b needed for codepoints greater than 0x7fffffff", stdout);
else
{
size_t j;
for (j = 0; j < rc; j++) printf("%02x ", buffer[j]);
if (f != NULL) fwrite(buffer, rc, 1, f);
if (utf8_input)
fputs("** Not valid UTF-8, top bit set", stdout);
else if (d > 0x10ffff)
fputs("** Invalid Unicode (greater than U+10ffff)", stdout);
else if (0xd800 <= d && d <= 0xdfff)
fputs("** Invalid Unicode (UTF-16 surrogate)", stdout);
else if (show)
{
putchar('>');
for (j = 0; j < rc; j++) printf("%c", buffer[j]);
putchar('<');
}
}
putchar('\n');
}
else
{
unsigned char *bptr;
const unsigned char *buffend;
unsigned char y = 0;
int len = 0;
int z = 0;
for (;;)
{
while (*x == ' ') x++;
if (*x == 0 && !z) break;
if (!isxdigit(*x))
{
printf("** Malformed hex string: %s\n", argv[i]);
len = -1;
break;
}
y = y * 16 +
(unsigned char)(tolower(*x) - ((isdigit(*x))? '0' : 'a' - 10));
x++;
if (z)
{
buffer[len++] = y;
y = 0;
}
z ^= 1;
}
if (len < 0) continue; /* With next argument after malformation */
bptr = buffer;
buffend = buffer + len;
while (bptr < buffend)
{
unsigned long int d;
int j;
int offset;
int rc = utf82ord(bptr, buffend, &d, &offset);
if (rc > 0)
{
printf("U+%08lx <= ", d);
for (j = 0; j < rc; j++) printf("%02x ", bptr[j]);
if (d <= 0x10ffff && (d < 0xd800 || 0xdfff < d) && show)
{
putchar('>');
for (j = 0; j < rc; j++) printf("%c", bptr[j]);
putchar('<');
}
putchar('\n');
bptr += rc;
}
else if (rc == -4)
{
printf("U+%08lx <= ", d);
for (j = 0; j < offset; j++) printf("%02x ", bptr[j]);
puts("** Overlong UTF-8 sequence");
bptr += offset;
}
else
{
switch (rc)
{
case 0: fputs("** First byte missing 0x40 bit", stdout);
break;
case -1: fputs("** First byte has too many high-order bits", stdout);
break;
case -2: fputs("** Incomplete UTF-8 sequence at end of string",
stdout);
break;
case -3: fputs("** Incomplete UTF-8 sequence", stdout);
break;
default: printf("** Unexpected return %d from utf82ord()", rc);
break;
}
printf(" at offset %d in string ", offset);
while (bptr < buffend) printf("%02x ", *bptr++);
putchar('\n');
break;
}
}
}
}
if (f != NULL) fclose(f);
return 0;
}
/* End */
+236
View File
@@ -0,0 +1,236 @@
#! /bin/sh
# Common wrapper for a few potentially missing GNU and other programs.
scriptversion=2024-06-07.14; # UTC
# shellcheck disable=SC2006,SC2268 # we must support pre-POSIX shells
# Copyright (C) 1996-2024 Free Software Foundation, Inc.
# Originally written by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
if test $# -eq 0; then
echo 1>&2 "Try '$0 --help' for more information"
exit 1
fi
case $1 in
--is-lightweight)
# Used by our autoconf macros to check whether the available missing
# script is modern enough.
exit 0
;;
--run)
# Back-compat with the calling convention used by older automake.
shift
;;
-h|--h|--he|--hel|--help)
echo "\
$0 [OPTION]... PROGRAM [ARGUMENT]...
Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due
to PROGRAM being missing or too old.
Options:
-h, --help display this help and exit
-v, --version output version information and exit
Supported PROGRAM values:
aclocal autoconf autogen autoheader autom4te automake autoreconf
bison flex help2man lex makeinfo perl yacc
Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and
'g' are ignored when checking the name.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>."
exit $?
;;
-v|--v|--ve|--ver|--vers|--versi|--versio|--version)
echo "missing (GNU Automake) $scriptversion"
exit $?
;;
-*)
echo 1>&2 "$0: unknown '$1' option"
echo 1>&2 "Try '$0 --help' for more information"
exit 1
;;
esac
# Run the given program, remember its exit status.
"$@"; st=$?
# If it succeeded, we are done.
test $st -eq 0 && exit 0
# Also exit now if we it failed (or wasn't found), and '--version' was
# passed; such an option is passed most likely to detect whether the
# program is present and works.
case $2 in --version|--help) exit $st;; esac
# Exit code 63 means version mismatch. This often happens when the user
# tries to use an ancient version of a tool on a file that requires a
# minimum version.
if test $st -eq 63; then
msg="probably too old"
elif test $st -eq 127; then
# Program was missing.
msg="missing on your system"
else
# Program was found and executed, but failed. Give up.
exit $st
fi
perl_URL=https://www.perl.org/
flex_URL=https://github.com/westes/flex
gnu_software_URL=https://www.gnu.org/software
program_details ()
{
case $1 in
aclocal|automake|autoreconf)
echo "The '$1' program is part of the GNU Automake package:"
echo "<$gnu_software_URL/automake>"
echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:"
echo "<$gnu_software_URL/autoconf>"
echo "<$gnu_software_URL/m4/>"
echo "<$perl_URL>"
;;
autoconf|autom4te|autoheader)
echo "The '$1' program is part of the GNU Autoconf package:"
echo "<$gnu_software_URL/autoconf/>"
echo "It also requires GNU m4 and Perl in order to run:"
echo "<$gnu_software_URL/m4/>"
echo "<$perl_URL>"
;;
*)
:
;;
esac
}
give_advice ()
{
# Normalize program name to check for.
normalized_program=`echo "$1" | sed '
s/^gnu-//; t
s/^gnu//; t
s/^g//; t'`
printf '%s\n' "'$1' is $msg."
configure_deps="'configure.ac' or m4 files included by 'configure.ac'"
autoheader_deps="'acconfig.h'"
automake_deps="'Makefile.am'"
aclocal_deps="'acinclude.m4'"
case $normalized_program in
aclocal*)
echo "You should only need it if you modified $aclocal_deps or"
echo "$configure_deps."
;;
autoconf*)
echo "You should only need it if you modified $configure_deps."
;;
autogen*)
echo "You should only need it if you modified a '.def' or '.tpl' file."
echo "You may want to install the GNU AutoGen package:"
echo "<$gnu_software_URL/autogen/>"
;;
autoheader*)
echo "You should only need it if you modified $autoheader_deps or"
echo "$configure_deps."
;;
automake*)
echo "You should only need it if you modified $automake_deps or"
echo "$configure_deps."
;;
autom4te*)
echo "You might have modified some maintainer files that require"
echo "the 'autom4te' program to be rebuilt."
;;
autoreconf*)
echo "You should only need it if you modified $aclocal_deps or"
echo "$automake_deps or $autoheader_deps or $automake_deps or"
echo "$configure_deps."
;;
bison*|yacc*)
echo "You should only need it if you modified a '.y' file."
echo "You may want to install the GNU Bison package:"
echo "<$gnu_software_URL/bison/>"
;;
help2man*)
echo "You should only need it if you modified a dependency" \
"of a man page."
echo "You may want to install the GNU Help2man package:"
echo "<$gnu_software_URL/help2man/>"
;;
lex*|flex*)
echo "You should only need it if you modified a '.l' file."
echo "You may want to install the Fast Lexical Analyzer package:"
echo "<$flex_URL>"
;;
makeinfo*)
echo "You should only need it if you modified a '.texi' file, or"
echo "any other file indirectly affecting the aspect of the manual."
echo "You might want to install the Texinfo package:"
echo "<$gnu_software_URL/texinfo/>"
echo "The spurious makeinfo call might also be the consequence of"
echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might"
echo "want to install GNU make:"
echo "<$gnu_software_URL/make/>"
;;
perl*)
echo "You should only need it to run GNU Autoconf, GNU Automake, "
echo " assorted other tools, or if you modified a Perl source file."
echo "You may want to install the Perl 5 language interpreter:"
echo "<$perl_URL>"
;;
*)
echo "You might have modified some files without having the proper"
echo "tools for further handling them. Check the 'README' file, it"
echo "often tells you about the needed prerequisites for installing"
echo "this package. You may also peek at any GNU archive site, in"
echo "case some other package contains this missing '$1' program."
;;
esac
program_details "$normalized_program"
}
give_advice "$1" | sed -e '1s/^/WARNING: /' \
-e '2,$s/^/ /' >&2
# Propagate the correct exit status (expected to be 127 for a program
# not found, 63 for a program that failed due to version mismatch).
exit $st
# Local variables:
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
@@ -0,0 +1,482 @@
/* src/config.h.in. Generated from configure.ac by autoheader. */
/* PCRE2 is written in Standard C, but there are a few non-standard things it
can cope with, allowing it to run on SunOS4 and other "close to standard"
systems.
In environments that support the GNU autotools, config.h.in is converted into
config.h by the "configure" script. In environments that use CMake,
config-cmake.in is converted into config.h. If you are going to build PCRE2 "by
hand" without using "configure" or CMake, you should copy the distributed
config.h.generic to config.h, and edit the macro definitions to be the way you
need them. You must then add -DHAVE_CONFIG_H to all of your compile commands,
so that config.h is included at the start of every source.
Alternatively, you can avoid editing by using -D on the compiler command line
to set the macro values. In this case, you do not have to set -DHAVE_CONFIG_H,
but if you do, default values will be taken from config.h for non-boolean
macros that are not defined on the command line.
Boolean macros such as HAVE_STDLIB_H and SUPPORT_PCRE2_8 should either be
defined (conventionally to 1) for TRUE, and not defined at all for FALSE. All
such macros are listed as a commented #undef in config.h.generic. Macros such
as MATCH_LIMIT, whose actual value is relevant, have defaults defined, but are
surrounded by #ifndef/#endif lines so that the value can be overridden by -D. */
/* By default, the \R escape sequence matches any Unicode line ending
character or sequence of characters. If BSR_ANYCRLF is defined (to any
value), this is changed so that backslash-R matches only CR, LF, or CRLF.
The build-time default can be overridden by the user of PCRE2 at runtime.
*/
#undef BSR_ANYCRLF
/* Define to any value to disable the use of the z and t modifiers in
formatting settings such as %zu or %td (this is rarely needed). */
#undef DISABLE_PERCENT_ZT
/* If you are compiling for a system that uses EBCDIC instead of ASCII
character codes, define this macro to any value. When EBCDIC is set, PCRE2
assumes that all input strings are in EBCDIC. If you do not define this
macro, PCRE2 will assume input strings are ASCII or UTF-8/16/32 Unicode. It
is not possible to build a version of PCRE2 that supports both EBCDIC and
ASCII or UTF-8/16/32. */
#undef EBCDIC
/* To force an EBCDIC environment, define this macro to make the core PCRE2
library functions use EBCDIC codepage 1047, regardless of whether the
compiler supports it using C character literals. */
#undef EBCDIC_IGNORING_COMPILER
/* In an EBCDIC environment, define this macro to any value to arrange for the
NL character to be 0x25 instead of the default 0x15. NL plays the role that
LF does in an ASCII/Unicode environment. */
#undef EBCDIC_NL25
/* Define to 1 if you have the <assert.h> header file. */
#undef HAVE_ASSERT_H
/* Define this if your compiler supports __attribute__((uninitialized)) */
#undef HAVE_ATTRIBUTE_UNINITIALIZED
/* Define this if your compiler provides __assume() */
#undef HAVE_BUILTIN_ASSUME
/* Define this if your compiler provides __builtin_mul_overflow() */
#undef HAVE_BUILTIN_MUL_OVERFLOW
/* Define this if your compiler provides __builtin_unreachable() */
#undef HAVE_BUILTIN_UNREACHABLE
/* Define to 1 if you have the <bzlib.h> header file. */
#undef HAVE_BZLIB_H
/* Define to 1 if you have the <dirent.h> header file. */
#undef HAVE_DIRENT_H
/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H
/* Define to 1 if you have the <editline/readline.h> header file. */
#undef HAVE_EDITLINE_READLINE_H
/* Define to 1 if you have the <edit/readline/readline.h> header file. */
#undef HAVE_EDIT_READLINE_READLINE_H
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the <limits.h> header file. */
#undef HAVE_LIMITS_H
/* Define to 1 if you have the 'memfd_create' function. */
#undef HAVE_MEMFD_CREATE
/* Define to 1 if you have the <minix/config.h> header file. */
#undef HAVE_MINIX_CONFIG_H
/* Define to 1 if you have the 'mkostemp' function. */
#undef HAVE_MKOSTEMP
/* Define if you have POSIX threads libraries and header files. */
#undef HAVE_PTHREAD
/* Have PTHREAD_PRIO_INHERIT. */
#undef HAVE_PTHREAD_PRIO_INHERIT
/* Define to 1 if you have the <readline.h> header file. */
#undef HAVE_READLINE_H
/* Define to 1 if you have the <readline/history.h> header file. */
#undef HAVE_READLINE_HISTORY_H
/* Define to 1 if you have the <readline/readline.h> header file. */
#undef HAVE_READLINE_READLINE_H
/* Define to 1 if you have the `realpath' function. */
#undef HAVE_REALPATH
/* Define to 1 if you have the 'secure_getenv' function. */
#undef HAVE_SECURE_GETENV
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdio.h> header file. */
#undef HAVE_STDIO_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <sys/wait.h> header file. */
#undef HAVE_SYS_WAIT_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if the compiler supports GCC compatible visibility
declarations. */
#undef HAVE_VISIBILITY
/* Define to 1 if you have the <wchar.h> header file. */
#undef HAVE_WCHAR_H
/* Define to 1 if you have the <windows.h> header file. */
#undef HAVE_WINDOWS_H
/* Define to 1 if you have the <zlib.h> header file. */
#undef HAVE_ZLIB_H
/* This limits the amount of memory that may be used while matching a pattern.
It applies to both pcre2_match() and pcre2_dfa_match(). It does not apply
to JIT matching. The value is in kibibytes (units of 1024 bytes). */
#undef HEAP_LIMIT
/* The value of LINK_SIZE determines the number of bytes used to store links
as offsets within the compiled regex. The default is 2, which allows for
compiled patterns up to 65535 code units long. This covers the vast
majority of cases. However, PCRE2 can also be compiled to use 3 or 4 bytes
instead. This allows for longer patterns in extreme cases. */
#undef LINK_SIZE
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#undef LT_OBJDIR
/* The value of MATCH_LIMIT determines the default number of times the
pcre2_match() function can record a backtrack position during a single
matching attempt. The value is also used to limit a loop counter in
pcre2_dfa_match(). There is a runtime interface for setting a different
limit. The limit exists in order to catch runaway regular expressions that
take forever to determine that they do not match. The default is set very
large so that it does not accidentally catch legitimate cases. */
#undef MATCH_LIMIT
/* The above limit applies to all backtracks, whether or not they are nested.
In some environments it is desirable to limit the nesting of backtracking
(that is, the depth of tree that is searched) more strictly, in order to
restrict the maximum amount of heap memory that is used. The value of
MATCH_LIMIT_DEPTH provides this facility. To have any useful effect, it
must be less than the value of MATCH_LIMIT. The default is to use the same
value as MATCH_LIMIT. There is a runtime method for setting a different
limit. In the case of pcre2_dfa_match(), this limit controls the depth of
the internal nested function calls that are used for pattern recursions,
lookarounds, and atomic groups. */
#undef MATCH_LIMIT_DEPTH
/* This limit is parameterized just in case anybody ever wants to change it.
Care must be taken if it is increased, because it guards against integer
overflow caused by enormously large patterns. */
#undef MAX_NAME_COUNT
/* This limit is parameterized just in case anybody ever wants to change it.
Care must be taken if it is increased, because it guards against integer
overflow caused by enormously large patterns. */
#undef MAX_NAME_SIZE
/* The value of MAX_VARLOOKBEHIND specifies the default maximum length, in
characters, for a variable-length lookbehind assertion. */
#undef MAX_VARLOOKBEHIND
/* Defining NEVER_BACKSLASH_C locks out the use of \C in all patterns. */
#undef NEVER_BACKSLASH_C
/* The value of NEWLINE_DEFAULT determines the default newline character
sequence. PCRE2 client programs can override this by selecting other values
at run time. The valid values are 1 (CR), 2 (LF), 3 (CRLF), 4 (ANY), 5
(ANYCRLF), and 6 (NUL). */
#undef NEWLINE_DEFAULT
/* Name of package */
#undef PACKAGE
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* The value of PARENS_NEST_LIMIT specifies the maximum depth of nested
parentheses (of any kind) in a pattern. This limits the amount of system
stack that is used while compiling a pattern. */
#undef PARENS_NEST_LIMIT
/* The value of PCRE2GREP_BUFSIZE is the starting size of the buffer used by
pcre2grep to hold parts of the file it is searching. The buffer will be
expanded up to PCRE2GREP_MAX_BUFSIZE if necessary, for files containing
very long lines. The actual amount of memory used by pcre2grep is three
times this number, because it allows for the buffering of "before" and
"after" lines. */
#undef PCRE2GREP_BUFSIZE
/* The value of PCRE2GREP_MAX_BUFSIZE specifies the maximum size of the buffer
used by pcre2grep to hold parts of the file it is searching. The actual
amount of memory used by pcre2grep is three times this number, because it
allows for the buffering of "before" and "after" lines. */
#undef PCRE2GREP_MAX_BUFSIZE
/* See PCRE2_EXP_DEFN; but this is applied to functions in the libpcre2-posix
library. */
#undef PCRE2POSIX_EXP_DEFN
/* Define to any value if linking libpcre2-posix dynamically. Ideally, if both
static and shared libraries are being built, then PCRE2POSIX_SHARED would
be defined only for the shared build. Indeed, this is a requirement on
Windows. However, when building with Autoconf and libtool, we compile the
sources once only to create both the static and shared library, so in this
case, PCRE2POSIX_SHARED should only be defined if the shared library is
being built, regardless of whether or not the static library is also being
built. */
#undef PCRE2POSIX_SHARED
/* Define to any value to include debugging code. */
#undef PCRE2_DEBUG
/* Define to the annotation for making a symbol visible. */
#undef PCRE2_EXPORT
/* If you are compiling for a system other than a Unix-like system or
Win32, and it needs some magic to be inserted before the definition
of a function that is exported by the library, define this macro to
contain the relevant magic. If you do not define this macro, a suitable
__declspec value is used for Windows systems; in other environments
a compiler relevant "extern" is used with any "visibility" related
attributes from PCRE2_EXPORT included.
This macro apears at the start of every exported function that is part
of the external API. It does not appear on functions that are "external"
in the C sense, but which are internal to the library. */
#undef PCRE2_EXP_DEFN
/* Define to any value if linking statically. Ideally, if both static and
shared libraries are being built, then PCRE2_STATIC would be defined only
for the static build. Indeed, this is a requirement on Windows. With
Autoconf and libtool however, it is idiomatic to compile the sources once
to create both the static and shared library, so in this case, PCRE2_STATIC
should only be defined if no shared library is being built. */
#undef PCRE2_STATIC
/* Define to necessary symbol if this constant uses a non-standard name on
your system. */
#undef PTHREAD_CREATE_JOINABLE
/* Define to any non-zero number to enable support for SELinux compatible
executable memory allocator in JIT. Note that this will have no effect
unless SUPPORT_JIT is also defined. */
#undef SLJIT_PROT_EXECUTABLE_ALLOCATOR
/* Define to 1 if all of the C89 standard headers exist (not just the ones
required in a freestanding environment). This macro is provided for
backward compatibility; new code need not use it. */
#undef STDC_HEADERS
/* Define to any value to enable differential fuzzing support. */
#undef SUPPORT_DIFF_FUZZ
/* Define to any value to enable support for Just-In-Time compiling. */
#undef SUPPORT_JIT
/* Define to any value to allow pcre2grep to be linked with libbz2, so that it
is able to handle .bz2 files. */
#undef SUPPORT_LIBBZ2
/* Define to any value to allow pcre2test to be linked with libedit. */
#undef SUPPORT_LIBEDIT
/* Define to any value to allow pcre2test to be linked with libreadline. */
#undef SUPPORT_LIBREADLINE
/* Define to any value to allow pcre2grep to be linked with libz, so that it
is able to handle .gz files. */
#undef SUPPORT_LIBZ
/* Define to any value to enable callout script support in pcre2grep. */
#undef SUPPORT_PCRE2GREP_CALLOUT
/* Define to any value to enable fork support in pcre2grep callout scripts.
This will have no effect unless SUPPORT_PCRE2GREP_CALLOUT is also defined.
*/
#undef SUPPORT_PCRE2GREP_CALLOUT_FORK
/* Define to any value to enable JIT support in pcre2grep. Note that this will
have no effect unless SUPPORT_JIT is also defined. */
#undef SUPPORT_PCRE2GREP_JIT
/* Define to any value to enable the 16 bit PCRE2 library. */
#undef SUPPORT_PCRE2_16
/* Define to any value to enable the 32 bit PCRE2 library. */
#undef SUPPORT_PCRE2_32
/* Define to any value to enable the 8 bit PCRE2 library. */
#undef SUPPORT_PCRE2_8
/* Define to any value to enable support for Unicode and UTF encoding. This
will work even in an EBCDIC environment, but it is incompatible with the
EBCDIC macro. That is, PCRE2 can support *either* EBCDIC code *or*
ASCII/Unicode, but not both at once. */
#undef SUPPORT_UNICODE
/* Define to any value for valgrind support to find invalid memory reads. */
#undef SUPPORT_VALGRIND
/* Enable extensions on AIX, Interix, z/OS. */
#ifndef _ALL_SOURCE
# undef _ALL_SOURCE
#endif
/* Enable general extensions on macOS. */
#ifndef _DARWIN_C_SOURCE
# undef _DARWIN_C_SOURCE
#endif
/* Enable general extensions on Solaris. */
#ifndef __EXTENSIONS__
# undef __EXTENSIONS__
#endif
/* Enable GNU extensions on systems that have them. */
#ifndef _GNU_SOURCE
# undef _GNU_SOURCE
#endif
/* Enable X/Open compliant socket functions that do not require linking
with -lxnet on HP-UX 11.11. */
#ifndef _HPUX_ALT_XOPEN_SOCKET_API
# undef _HPUX_ALT_XOPEN_SOCKET_API
#endif
/* Identify the host operating system as Minix.
This macro does not affect the system headers' behavior.
A future release of Autoconf may stop defining this macro. */
#ifndef _MINIX
# undef _MINIX
#endif
/* Enable general extensions on NetBSD.
Enable NetBSD compatibility extensions on Minix. */
#ifndef _NETBSD_SOURCE
# undef _NETBSD_SOURCE
#endif
/* Enable OpenBSD compatibility extensions on NetBSD.
Oddly enough, this does nothing on OpenBSD. */
#ifndef _OPENBSD_SOURCE
# undef _OPENBSD_SOURCE
#endif
/* Define to 1 if needed for POSIX-compatible behavior. */
#ifndef _POSIX_SOURCE
# undef _POSIX_SOURCE
#endif
/* Define to 2 if needed for POSIX-compatible behavior. */
#ifndef _POSIX_1_SOURCE
# undef _POSIX_1_SOURCE
#endif
/* Enable POSIX-compatible threading on Solaris. */
#ifndef _POSIX_PTHREAD_SEMANTICS
# undef _POSIX_PTHREAD_SEMANTICS
#endif
/* Enable extensions specified by ISO/IEC TS 18661-5:2014. */
#ifndef __STDC_WANT_IEC_60559_ATTRIBS_EXT__
# undef __STDC_WANT_IEC_60559_ATTRIBS_EXT__
#endif
/* Enable extensions specified by ISO/IEC TS 18661-1:2014. */
#ifndef __STDC_WANT_IEC_60559_BFP_EXT__
# undef __STDC_WANT_IEC_60559_BFP_EXT__
#endif
/* Enable extensions specified by ISO/IEC TS 18661-2:2015. */
#ifndef __STDC_WANT_IEC_60559_DFP_EXT__
# undef __STDC_WANT_IEC_60559_DFP_EXT__
#endif
/* Enable extensions specified by C23 Annex F. */
#ifndef __STDC_WANT_IEC_60559_EXT__
# undef __STDC_WANT_IEC_60559_EXT__
#endif
/* Enable extensions specified by ISO/IEC TS 18661-4:2015. */
#ifndef __STDC_WANT_IEC_60559_FUNCS_EXT__
# undef __STDC_WANT_IEC_60559_FUNCS_EXT__
#endif
/* Enable extensions specified by C23 Annex H and ISO/IEC TS 18661-3:2015. */
#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__
# undef __STDC_WANT_IEC_60559_TYPES_EXT__
#endif
/* Enable extensions specified by ISO/IEC TR 24731-2:2010. */
#ifndef __STDC_WANT_LIB_EXT2__
# undef __STDC_WANT_LIB_EXT2__
#endif
/* Enable extensions specified by ISO/IEC 24747:2009. */
#ifndef __STDC_WANT_MATH_SPEC_FUNCS__
# undef __STDC_WANT_MATH_SPEC_FUNCS__
#endif
/* Enable extensions on HP NonStop. */
#ifndef _TANDEM_SOURCE
# undef _TANDEM_SOURCE
#endif
/* Enable X/Open extensions. Define to 500 only if necessary
to make mbstate_t available. */
#ifndef _XOPEN_SOURCE
# undef _XOPEN_SOURCE
#endif
/* Version number of package */
#undef VERSION
/* Number of bits in a file offset, on hosts where this is settable. */
#undef _FILE_OFFSET_BITS
/* Define to 1 on platforms where this makes off_t a 64-bit type. */
#undef _LARGE_FILES
/* Number of bits in time_t, on hosts where this is settable. */
#undef _TIME_BITS
/* Define to 1 on platforms where this makes time_t a 64-bit type. */
#undef __MINGW_USE_VC2005_COMPAT
/* Define to empty if 'const' does not conform to ANSI C. */
#undef const
/* Define to the type of a signed integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
#undef int64_t
/* Define as 'unsigned int' if <stddef.h> doesn't define. */
#undef size_t
@@ -0,0 +1,192 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* This file was automatically written by the pcre2_dftables auxiliary
program. It contains character tables that are used when no external
tables are passed to PCRE2 by the application that calls it. The tables
are used only for characters whose code values are less than 256, and
only relevant if not in UCP mode. */
/* This set of tables was written in the C locale. */
/* The pcre2_ftables program (which is distributed with PCRE2) can be used
to build alternative versions of this file. This is necessary if you are
running in an EBCDIC environment, or if you want to default to a different
encoding, for example ISO-8859-1. When pcre2_dftables is run, it creates
these tables in the "C" locale by default. This happens automatically if
PCRE2 is configured with --enable-rebuild-chartables. However, you can run
pcre2_dftables manually with the -L option to build tables using the LC_ALL
locale. */
#include "pcre2_internal.h"
const uint8_t PRIV(default_tables)[] = {
/* This table is a lower casing table. */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122, 91, 92, 93, 94, 95,
96, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,
152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,
168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255,
/* This table is a case flipping table. */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90,123,124,125,126,127,
128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,
152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,
168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255,
/* This table contains bit maps for various character classes. Each map is 32
bytes long and the bits run from the least significant end of each byte. The
classes that have their own maps are: space, xdigit, digit, upper, lower, word,
graph, print, punct, and cntrl. Other classes are built from combinations. */
0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00, /* space */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, /* xdigit */
0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, /* digit */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* upper */
0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* lower */
0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, /* word */
0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff, /* graph */
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, /* print */
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc, /* punct */
0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00, /* cntrl */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
/* This table identifies various classes of character by individual bits:
0x01 white space character
0x02 letter
0x04 lower case letter
0x08 decimal digit
0x10 word (alphanumeric or '_')
*/
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */
0x00,0x01,0x01,0x01,0x01,0x01,0x00,0x00, /* 8- 15 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */
0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */
0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18, /* 0 - 7 */
0x18,0x18,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */
0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* @ - G */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */
0x12,0x12,0x12,0x00,0x00,0x00,0x00,0x10, /* X - _ */
0x00,0x16,0x16,0x16,0x16,0x16,0x16,0x16, /* ` - g */
0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16, /* h - o */
0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16, /* p - w */
0x16,0x16,0x16,0x00,0x00,0x00,0x00,0x00, /* x -127 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */
/* End of pcre2_chartables.c */
+160
View File
@@ -0,0 +1,160 @@
#! /bin/sh
# test-driver - basic testsuite driver script.
scriptversion=2024-06-19.01; # UTC
# Copyright (C) 2011-2024 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
# Make unconditional expansion of undefined variables an error. This
# helps a lot in preventing typo-related bugs.
set -u
usage_error ()
{
echo "$0: $*" >&2
print_usage >&2
exit 2
}
print_usage ()
{
cat <<END
Usage:
test-driver --test-name NAME --log-file PATH --trs-file PATH
[--expect-failure {yes|no}] [--color-tests {yes|no}]
[--collect-skipped-logs {yes|no}]
[--enable-hard-errors {yes|no}] [--]
TEST-SCRIPT [TEST-SCRIPT-ARGUMENTS]
The '--test-name', '--log-file' and '--trs-file' options are mandatory.
See the GNU Automake documentation for information.
Report bugs to <bug-automake@gnu.org>.
GNU Automake home page: <https://www.gnu.org/software/automake/>.
General help using GNU software: <https://www.gnu.org/gethelp/>.
END
}
test_name= # Used for reporting.
log_file= # Where to save the output of the test script.
trs_file= # Where to save the metadata of the test run.
expect_failure=no
color_tests=no
collect_skipped_logs=yes
enable_hard_errors=yes
while test $# -gt 0; do
case $1 in
--help) print_usage; exit $?;;
--version) echo "test-driver (GNU Automake) $scriptversion"; exit $?;;
--test-name) test_name=$2; shift;;
--log-file) log_file=$2; shift;;
--trs-file) trs_file=$2; shift;;
--color-tests) color_tests=$2; shift;;
--collect-skipped-logs) collect_skipped_logs=$2; shift;;
--expect-failure) expect_failure=$2; shift;;
--enable-hard-errors) enable_hard_errors=$2; shift;;
--) shift; break;;
-*) usage_error "invalid option: '$1'";;
*) break;;
esac
shift
done
missing_opts=
test x"$test_name" = x && missing_opts="$missing_opts --test-name"
test x"$log_file" = x && missing_opts="$missing_opts --log-file"
test x"$trs_file" = x && missing_opts="$missing_opts --trs-file"
if test x"$missing_opts" != x; then
usage_error "the following mandatory options are missing:$missing_opts"
fi
if test $# -eq 0; then
usage_error "missing argument"
fi
if test $color_tests = yes; then
# Keep this in sync with 'lib/am/check.am:$(am__tty_colors)'.
red='' # Red.
grn='' # Green.
lgn='' # Light green.
blu='' # Blue.
mgn='' # Magenta.
std='' # No color.
else
red= grn= lgn= blu= mgn= std=
fi
do_exit='rm -f $log_file $trs_file; (exit $st); exit $st'
trap "st=129; $do_exit" 1
trap "st=130; $do_exit" 2
trap "st=141; $do_exit" 13
trap "st=143; $do_exit" 15
# Test script is run here. We create the file first, then append to it,
# to ameliorate tests themselves also writing to the log file. Our tests
# don't, but others can (automake bug#35762).
: >"$log_file"
"$@" >>"$log_file" 2>&1
estatus=$?
if test $enable_hard_errors = no && test $estatus -eq 99; then
tweaked_estatus=1
else
tweaked_estatus=$estatus
fi
case $tweaked_estatus:$expect_failure in
0:yes) col=$red res=XPASS recheck=yes gcopy=yes;;
0:*) col=$grn res=PASS recheck=no gcopy=no;;
77:*) col=$blu res=SKIP recheck=no gcopy=$collect_skipped_logs;;
99:*) col=$mgn res=ERROR recheck=yes gcopy=yes;;
*:yes) col=$lgn res=XFAIL recheck=no gcopy=yes;;
*:*) col=$red res=FAIL recheck=yes gcopy=yes;;
esac
# Report the test outcome and exit status in the logs, so that one can
# know whether the test passed or failed simply by looking at the '.log'
# file, without the need of also peaking into the corresponding '.trs'
# file (automake bug#11814).
echo "$res $test_name (exit status: $estatus)" >>"$log_file"
# Report outcome to console.
echo "${col}${res}${std}: $test_name"
# Register the test result, and other relevant metadata.
echo ":test-result: $res" > $trs_file
echo ":global-test-result: $res" >> $trs_file
echo ":recheck: $recheck" >> $trs_file
echo ":copy-in-global-log: $gcopy" >> $trs_file
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
@@ -0,0 +1,18 @@
# This test is run only when JIT support is not available. It checks that an
# attempt to use it has the expected behaviour. It also tests things that
# are different without JIT.
/abc/I,jit,jitverify
JIT compilation was not successful (bad JIT option)
Capture group count = 0
First code unit = 'a'
Last code unit = 'c'
Subject length lower bound = 3
JIT support is not available in this version of PCRE2
/a*/I
Capture group count = 0
May match empty string
Subject length lower bound = 0
# End of testinput16
@@ -0,0 +1,493 @@
/* pnglibconf.h - library build configuration */
/* libpng version 1.6.55 */
/* Copyright (c) 2018-2026 Cosmin Truta */
/* Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson */
/* This code is released under the libpng license. */
/* For conditions of distribution and use, see the disclaimer */
/* and license in png.h */
/* pnglibconf.h */
/* Machine generated file: DO NOT EDIT */
/* Derived from: scripts/pnglibconf.dfa */
#ifndef PNGLCONF_H
#define PNGLCONF_H
/* options */
#define PNG_16BIT_SUPPORTED
#define PNG_ALIGNED_MEMORY_SUPPORTED
/*#undef PNG_ARM_NEON_API_SUPPORTED*/
/*#undef PNG_ARM_NEON_CHECK_SUPPORTED*/
#define PNG_BENIGN_ERRORS_SUPPORTED
#define PNG_BENIGN_READ_ERRORS_SUPPORTED
/*#undef PNG_BENIGN_WRITE_ERRORS_SUPPORTED*/
#define PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
#define PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
#define PNG_COLORSPACE_SUPPORTED
#define PNG_CONSOLE_IO_SUPPORTED
#define PNG_CONVERT_tIME_SUPPORTED
/*#undef PNG_DISABLE_ADLER32_CHECK_SUPPORTED*/
#define PNG_EASY_ACCESS_SUPPORTED
/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/
#define PNG_ERROR_TEXT_SUPPORTED
#define PNG_FIXED_POINT_SUPPORTED
#define PNG_FLOATING_ARITHMETIC_SUPPORTED
#define PNG_FLOATING_POINT_SUPPORTED
#define PNG_FORMAT_AFIRST_SUPPORTED
#define PNG_FORMAT_BGR_SUPPORTED
#define PNG_GAMMA_SUPPORTED
#define PNG_GET_PALETTE_MAX_SUPPORTED
#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
#define PNG_INCH_CONVERSIONS_SUPPORTED
#define PNG_INFO_IMAGE_SUPPORTED
#define PNG_IO_STATE_SUPPORTED
/*#undef PNG_MIPS_MMI_API_SUPPORTED*/
/*#undef PNG_MIPS_MMI_CHECK_SUPPORTED*/
/*#undef PNG_MIPS_MSA_API_SUPPORTED*/
/*#undef PNG_MIPS_MSA_CHECK_SUPPORTED*/
#define PNG_MNG_FEATURES_SUPPORTED
#define PNG_POINTER_INDEXING_SUPPORTED
/*#undef PNG_POWERPC_VSX_API_SUPPORTED*/
/*#undef PNG_POWERPC_VSX_CHECK_SUPPORTED*/
#define PNG_PROGRESSIVE_READ_SUPPORTED
#define PNG_READ_16BIT_SUPPORTED
#define PNG_READ_ALPHA_MODE_SUPPORTED
#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
#define PNG_READ_BACKGROUND_SUPPORTED
#define PNG_READ_BGR_SUPPORTED
#define PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
#define PNG_READ_COMPOSITE_NODIV_SUPPORTED
#define PNG_READ_COMPRESSED_TEXT_SUPPORTED
#define PNG_READ_EXPAND_16_SUPPORTED
#define PNG_READ_EXPAND_SUPPORTED
#define PNG_READ_FILLER_SUPPORTED
#define PNG_READ_GAMMA_SUPPORTED
#define PNG_READ_GET_PALETTE_MAX_SUPPORTED
#define PNG_READ_GRAY_TO_RGB_SUPPORTED
#define PNG_READ_INTERLACING_SUPPORTED
#define PNG_READ_INT_FUNCTIONS_SUPPORTED
#define PNG_READ_INVERT_ALPHA_SUPPORTED
#define PNG_READ_INVERT_SUPPORTED
#define PNG_READ_OPT_PLTE_SUPPORTED
#define PNG_READ_PACKSWAP_SUPPORTED
#define PNG_READ_PACK_SUPPORTED
#define PNG_READ_QUANTIZE_SUPPORTED
#define PNG_READ_RGB_TO_GRAY_SUPPORTED
#define PNG_READ_SCALE_16_TO_8_SUPPORTED
#define PNG_READ_SHIFT_SUPPORTED
#define PNG_READ_STRIP_16_TO_8_SUPPORTED
#define PNG_READ_STRIP_ALPHA_SUPPORTED
#define PNG_READ_SUPPORTED
#define PNG_READ_SWAP_ALPHA_SUPPORTED
#define PNG_READ_SWAP_SUPPORTED
#define PNG_READ_TEXT_SUPPORTED
#define PNG_READ_TRANSFORMS_SUPPORTED
#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_READ_USER_CHUNKS_SUPPORTED
#define PNG_READ_USER_TRANSFORM_SUPPORTED
#define PNG_READ_bKGD_SUPPORTED
#define PNG_READ_cHRM_SUPPORTED
#define PNG_READ_cICP_SUPPORTED
#define PNG_READ_cLLI_SUPPORTED
#define PNG_READ_eXIf_SUPPORTED
#define PNG_READ_gAMA_SUPPORTED
#define PNG_READ_hIST_SUPPORTED
#define PNG_READ_iCCP_SUPPORTED
#define PNG_READ_iTXt_SUPPORTED
#define PNG_READ_mDCV_SUPPORTED
#define PNG_READ_oFFs_SUPPORTED
#define PNG_READ_pCAL_SUPPORTED
#define PNG_READ_pHYs_SUPPORTED
#define PNG_READ_sBIT_SUPPORTED
#define PNG_READ_sCAL_SUPPORTED
#define PNG_READ_sPLT_SUPPORTED
#define PNG_READ_sRGB_SUPPORTED
#define PNG_READ_tEXt_SUPPORTED
#define PNG_READ_tIME_SUPPORTED
#define PNG_READ_tRNS_SUPPORTED
#define PNG_READ_zTXt_SUPPORTED
#define PNG_SAVE_INT_32_SUPPORTED
#define PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_SEQUENTIAL_READ_SUPPORTED
#define PNG_SETJMP_SUPPORTED
#define PNG_SET_OPTION_SUPPORTED
#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_SET_USER_LIMITS_SUPPORTED
#define PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
#define PNG_SIMPLIFIED_READ_BGR_SUPPORTED
#define PNG_SIMPLIFIED_READ_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_SUPPORTED
#define PNG_STDIO_SUPPORTED
#define PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_TEXT_SUPPORTED
#define PNG_TIME_RFC1123_SUPPORTED
#define PNG_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_USER_CHUNKS_SUPPORTED
#define PNG_USER_LIMITS_SUPPORTED
#define PNG_USER_MEM_SUPPORTED
#define PNG_USER_TRANSFORM_INFO_SUPPORTED
#define PNG_USER_TRANSFORM_PTR_SUPPORTED
#define PNG_WARNINGS_SUPPORTED
#define PNG_WRITE_16BIT_SUPPORTED
#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
#define PNG_WRITE_BGR_SUPPORTED
#define PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
#define PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
#define PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
#define PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
#define PNG_WRITE_FILLER_SUPPORTED
#define PNG_WRITE_FILTER_SUPPORTED
#define PNG_WRITE_FLUSH_SUPPORTED
#define PNG_WRITE_GET_PALETTE_MAX_SUPPORTED
#define PNG_WRITE_INTERLACING_SUPPORTED
#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED
#define PNG_WRITE_INVERT_ALPHA_SUPPORTED
#define PNG_WRITE_INVERT_SUPPORTED
#define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
#define PNG_WRITE_PACKSWAP_SUPPORTED
#define PNG_WRITE_PACK_SUPPORTED
#define PNG_WRITE_SHIFT_SUPPORTED
#define PNG_WRITE_SUPPORTED
#define PNG_WRITE_SWAP_ALPHA_SUPPORTED
#define PNG_WRITE_SWAP_SUPPORTED
#define PNG_WRITE_TEXT_SUPPORTED
#define PNG_WRITE_TRANSFORMS_SUPPORTED
#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_WRITE_USER_TRANSFORM_SUPPORTED
#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
#define PNG_WRITE_bKGD_SUPPORTED
#define PNG_WRITE_cHRM_SUPPORTED
#define PNG_WRITE_cICP_SUPPORTED
#define PNG_WRITE_cLLI_SUPPORTED
#define PNG_WRITE_eXIf_SUPPORTED
#define PNG_WRITE_gAMA_SUPPORTED
#define PNG_WRITE_hIST_SUPPORTED
#define PNG_WRITE_iCCP_SUPPORTED
#define PNG_WRITE_iTXt_SUPPORTED
#define PNG_WRITE_mDCV_SUPPORTED
#define PNG_WRITE_oFFs_SUPPORTED
#define PNG_WRITE_pCAL_SUPPORTED
#define PNG_WRITE_pHYs_SUPPORTED
#define PNG_WRITE_sBIT_SUPPORTED
#define PNG_WRITE_sCAL_SUPPORTED
#define PNG_WRITE_sPLT_SUPPORTED
#define PNG_WRITE_sRGB_SUPPORTED
#define PNG_WRITE_tEXt_SUPPORTED
#define PNG_WRITE_tIME_SUPPORTED
#define PNG_WRITE_tRNS_SUPPORTED
#define PNG_WRITE_zTXt_SUPPORTED
#define PNG_bKGD_SUPPORTED
#define PNG_cHRM_SUPPORTED
#define PNG_cICP_SUPPORTED
#define PNG_cLLI_SUPPORTED
#define PNG_eXIf_SUPPORTED
#define PNG_gAMA_SUPPORTED
#define PNG_hIST_SUPPORTED
#define PNG_iCCP_SUPPORTED
#define PNG_iTXt_SUPPORTED
#define PNG_mDCV_SUPPORTED
#define PNG_oFFs_SUPPORTED
#define PNG_pCAL_SUPPORTED
#define PNG_pHYs_SUPPORTED
#define PNG_sBIT_SUPPORTED
#define PNG_sCAL_SUPPORTED
#define PNG_sPLT_SUPPORTED
#define PNG_sRGB_SUPPORTED
#define PNG_tEXt_SUPPORTED
#define PNG_tIME_SUPPORTED
#define PNG_tRNS_SUPPORTED
#define PNG_zTXt_SUPPORTED
/* end of options */
/* settings */
#define PNG_API_RULE 0
#define PNG_DEFAULT_READ_MACROS 1
#define PNG_GAMMA_THRESHOLD_FIXED 5000
#define PNG_IDAT_READ_SIZE PNG_ZBUF_SIZE
#define PNG_INFLATE_BUF_SIZE 1024
#define PNG_LINKAGE_API extern
#define PNG_LINKAGE_CALLBACK extern
#define PNG_LINKAGE_DATA extern
#define PNG_LINKAGE_FUNCTION extern
#define PNG_MAX_GAMMA_8 11
#define PNG_PREFIX wx_
#define PNG_QUANTIZE_BLUE_BITS 5
#define PNG_QUANTIZE_GREEN_BITS 5
#define PNG_QUANTIZE_RED_BITS 5
#define PNG_TEXT_Z_DEFAULT_COMPRESSION (-1)
#define PNG_TEXT_Z_DEFAULT_STRATEGY 0
#define PNG_USER_CHUNK_CACHE_MAX 1000
#define PNG_USER_CHUNK_MALLOC_MAX 8000000
#define PNG_USER_HEIGHT_MAX 1000000
#define PNG_USER_WIDTH_MAX 1000000
#define PNG_ZBUF_SIZE 8192
#define PNG_ZLIB_VERNUM 0
#define PNG_Z_DEFAULT_COMPRESSION (-1)
#define PNG_Z_DEFAULT_NOFILTER_STRATEGY 0
#define PNG_Z_DEFAULT_STRATEGY 1
#define PNG_sCAL_PRECISION 5
#define PNG_sRGB_PROFILE_CHECKS 2
/* end of settings */
#define png_access_version_number wx_png_access_version_number
#define png_benign_error wx_png_benign_error
#define png_build_grayscale_palette wx_png_build_grayscale_palette
#define png_calloc wx_png_calloc
#define png_chunk_benign_error wx_png_chunk_benign_error
#define png_chunk_error wx_png_chunk_error
#define png_chunk_warning wx_png_chunk_warning
#define png_convert_from_struct_tm wx_png_convert_from_struct_tm
#define png_convert_from_time_t wx_png_convert_from_time_t
#define png_convert_to_rfc1123 wx_png_convert_to_rfc1123
#define png_convert_to_rfc1123_buffer wx_png_convert_to_rfc1123_buffer
#define png_create_info_struct wx_png_create_info_struct
#define png_create_read_struct wx_png_create_read_struct
#define png_create_read_struct_2 wx_png_create_read_struct_2
#define png_create_write_struct wx_png_create_write_struct
#define png_create_write_struct_2 wx_png_create_write_struct_2
#define png_data_freer wx_png_data_freer
#define png_destroy_info_struct wx_png_destroy_info_struct
#define png_destroy_read_struct wx_png_destroy_read_struct
#define png_destroy_write_struct wx_png_destroy_write_struct
#define png_error wx_png_error
#define png_free wx_png_free
#define png_free_data wx_png_free_data
#define png_free_default wx_png_free_default
#define png_get_IHDR wx_png_get_IHDR
#define png_get_PLTE wx_png_get_PLTE
#define png_get_bKGD wx_png_get_bKGD
#define png_get_bit_depth wx_png_get_bit_depth
#define png_get_cHRM wx_png_get_cHRM
#define png_get_cHRM_XYZ wx_png_get_cHRM_XYZ
#define png_get_cHRM_XYZ_fixed wx_png_get_cHRM_XYZ_fixed
#define png_get_cHRM_fixed wx_png_get_cHRM_fixed
#define png_get_cICP wx_png_get_cICP
#define png_get_cLLI wx_png_get_cLLI
#define png_get_cLLI_fixed wx_png_get_cLLI_fixed
#define png_get_channels wx_png_get_channels
#define png_get_chunk_cache_max wx_png_get_chunk_cache_max
#define png_get_chunk_malloc_max wx_png_get_chunk_malloc_max
#define png_get_color_type wx_png_get_color_type
#define png_get_compression_buffer_size wx_png_get_compression_buffer_size
#define png_get_compression_type wx_png_get_compression_type
#define png_get_copyright wx_png_get_copyright
#define png_get_current_pass_number wx_png_get_current_pass_number
#define png_get_current_row_number wx_png_get_current_row_number
#define png_get_eXIf wx_png_get_eXIf
#define png_get_eXIf_1 wx_png_get_eXIf_1
#define png_get_error_ptr wx_png_get_error_ptr
#define png_get_filter_type wx_png_get_filter_type
#define png_get_gAMA wx_png_get_gAMA
#define png_get_gAMA_fixed wx_png_get_gAMA_fixed
#define png_get_hIST wx_png_get_hIST
#define png_get_header_ver wx_png_get_header_ver
#define png_get_header_version wx_png_get_header_version
#define png_get_iCCP wx_png_get_iCCP
#define png_get_image_height wx_png_get_image_height
#define png_get_image_width wx_png_get_image_width
#define png_get_int_32 wx_png_get_int_32
#define png_get_interlace_type wx_png_get_interlace_type
#define png_get_io_chunk_type wx_png_get_io_chunk_type
#define png_get_io_ptr wx_png_get_io_ptr
#define png_get_io_state wx_png_get_io_state
#define png_get_libpng_ver wx_png_get_libpng_ver
#define png_get_mDCV wx_png_get_mDCV
#define png_get_mDCV_fixed wx_png_get_mDCV_fixed
#define png_get_mem_ptr wx_png_get_mem_ptr
#define png_get_oFFs wx_png_get_oFFs
#define png_get_pCAL wx_png_get_pCAL
#define png_get_pHYs wx_png_get_pHYs
#define png_get_pHYs_dpi wx_png_get_pHYs_dpi
#define png_get_palette_max wx_png_get_palette_max
#define png_get_pixel_aspect_ratio wx_png_get_pixel_aspect_ratio
#define png_get_pixel_aspect_ratio_fixed wx_png_get_pixel_aspect_ratio_fixed
#define png_get_pixels_per_inch wx_png_get_pixels_per_inch
#define png_get_pixels_per_meter wx_png_get_pixels_per_meter
#define png_get_progressive_ptr wx_png_get_progressive_ptr
#define png_get_rgb_to_gray_status wx_png_get_rgb_to_gray_status
#define png_get_rowbytes wx_png_get_rowbytes
#define png_get_rows wx_png_get_rows
#define png_get_sBIT wx_png_get_sBIT
#define png_get_sCAL wx_png_get_sCAL
#define png_get_sCAL_fixed wx_png_get_sCAL_fixed
#define png_get_sCAL_s wx_png_get_sCAL_s
#define png_get_sPLT wx_png_get_sPLT
#define png_get_sRGB wx_png_get_sRGB
#define png_get_signature wx_png_get_signature
#define png_get_tIME wx_png_get_tIME
#define png_get_tRNS wx_png_get_tRNS
#define png_get_text wx_png_get_text
#define png_get_uint_16 wx_png_get_uint_16
#define png_get_uint_31 wx_png_get_uint_31
#define png_get_uint_32 wx_png_get_uint_32
#define png_get_unknown_chunks wx_png_get_unknown_chunks
#define png_get_user_chunk_ptr wx_png_get_user_chunk_ptr
#define png_get_user_height_max wx_png_get_user_height_max
#define png_get_user_transform_ptr wx_png_get_user_transform_ptr
#define png_get_user_width_max wx_png_get_user_width_max
#define png_get_valid wx_png_get_valid
#define png_get_x_offset_inches wx_png_get_x_offset_inches
#define png_get_x_offset_inches_fixed wx_png_get_x_offset_inches_fixed
#define png_get_x_offset_microns wx_png_get_x_offset_microns
#define png_get_x_offset_pixels wx_png_get_x_offset_pixels
#define png_get_x_pixels_per_inch wx_png_get_x_pixels_per_inch
#define png_get_x_pixels_per_meter wx_png_get_x_pixels_per_meter
#define png_get_y_offset_inches wx_png_get_y_offset_inches
#define png_get_y_offset_inches_fixed wx_png_get_y_offset_inches_fixed
#define png_get_y_offset_microns wx_png_get_y_offset_microns
#define png_get_y_offset_pixels wx_png_get_y_offset_pixels
#define png_get_y_pixels_per_inch wx_png_get_y_pixels_per_inch
#define png_get_y_pixels_per_meter wx_png_get_y_pixels_per_meter
#define png_handle_as_unknown wx_png_handle_as_unknown
#define png_image_begin_read_from_file wx_png_image_begin_read_from_file
#define png_image_begin_read_from_memory wx_png_image_begin_read_from_memory
#define png_image_begin_read_from_stdio wx_png_image_begin_read_from_stdio
#define png_image_finish_read wx_png_image_finish_read
#define png_image_free wx_png_image_free
#define png_image_write_to_file wx_png_image_write_to_file
#define png_image_write_to_memory wx_png_image_write_to_memory
#define png_image_write_to_stdio wx_png_image_write_to_stdio
#define png_info_init_3 wx_png_info_init_3
#define png_init_io wx_png_init_io
#define png_longjmp wx_png_longjmp
#define png_malloc wx_png_malloc
#define png_malloc_default wx_png_malloc_default
#define png_malloc_warn wx_png_malloc_warn
#define png_permit_mng_features wx_png_permit_mng_features
#define png_process_data wx_png_process_data
#define png_process_data_pause wx_png_process_data_pause
#define png_process_data_skip wx_png_process_data_skip
#define png_progressive_combine_row wx_png_progressive_combine_row
#define png_read_end wx_png_read_end
#define png_read_image wx_png_read_image
#define png_read_info wx_png_read_info
#define png_read_png wx_png_read_png
#define png_read_row wx_png_read_row
#define png_read_rows wx_png_read_rows
#define png_read_update_info wx_png_read_update_info
#define png_reset_zstream wx_png_reset_zstream
#define png_save_int_32 wx_png_save_int_32
#define png_save_uint_16 wx_png_save_uint_16
#define png_save_uint_32 wx_png_save_uint_32
#define png_set_IHDR wx_png_set_IHDR
#define png_set_PLTE wx_png_set_PLTE
#define png_set_add_alpha wx_png_set_add_alpha
#define png_set_alpha_mode wx_png_set_alpha_mode
#define png_set_alpha_mode_fixed wx_png_set_alpha_mode_fixed
#define png_set_bKGD wx_png_set_bKGD
#define png_set_background wx_png_set_background
#define png_set_background_fixed wx_png_set_background_fixed
#define png_set_benign_errors wx_png_set_benign_errors
#define png_set_bgr wx_png_set_bgr
#define png_set_cHRM wx_png_set_cHRM
#define png_set_cHRM_XYZ wx_png_set_cHRM_XYZ
#define png_set_cHRM_XYZ_fixed wx_png_set_cHRM_XYZ_fixed
#define png_set_cHRM_fixed wx_png_set_cHRM_fixed
#define png_set_cICP wx_png_set_cICP
#define png_set_cLLI wx_png_set_cLLI
#define png_set_cLLI_fixed wx_png_set_cLLI_fixed
#define png_set_check_for_invalid_index wx_png_set_check_for_invalid_index
#define png_set_chunk_cache_max wx_png_set_chunk_cache_max
#define png_set_chunk_malloc_max wx_png_set_chunk_malloc_max
#define png_set_compression_buffer_size wx_png_set_compression_buffer_size
#define png_set_compression_level wx_png_set_compression_level
#define png_set_compression_mem_level wx_png_set_compression_mem_level
#define png_set_compression_method wx_png_set_compression_method
#define png_set_compression_strategy wx_png_set_compression_strategy
#define png_set_compression_window_bits wx_png_set_compression_window_bits
#define png_set_crc_action wx_png_set_crc_action
#define png_set_eXIf wx_png_set_eXIf
#define png_set_eXIf_1 wx_png_set_eXIf_1
#define png_set_error_fn wx_png_set_error_fn
#define png_set_expand wx_png_set_expand
#define png_set_expand_16 wx_png_set_expand_16
#define png_set_expand_gray_1_2_4_to_8 wx_png_set_expand_gray_1_2_4_to_8
#define png_set_filler wx_png_set_filler
#define png_set_filter wx_png_set_filter
#define png_set_filter_heuristics wx_png_set_filter_heuristics
#define png_set_filter_heuristics_fixed wx_png_set_filter_heuristics_fixed
#define png_set_flush wx_png_set_flush
#define png_set_gAMA wx_png_set_gAMA
#define png_set_gAMA_fixed wx_png_set_gAMA_fixed
#define png_set_gamma wx_png_set_gamma
#define png_set_gamma_fixed wx_png_set_gamma_fixed
#define png_set_gray_to_rgb wx_png_set_gray_to_rgb
#define png_set_hIST wx_png_set_hIST
#define png_set_iCCP wx_png_set_iCCP
#define png_set_interlace_handling wx_png_set_interlace_handling
#define png_set_invalid wx_png_set_invalid
#define png_set_invert_alpha wx_png_set_invert_alpha
#define png_set_invert_mono wx_png_set_invert_mono
#define png_set_keep_unknown_chunks wx_png_set_keep_unknown_chunks
#define png_set_longjmp_fn wx_png_set_longjmp_fn
#define png_set_mDCV wx_png_set_mDCV
#define png_set_mDCV_fixed wx_png_set_mDCV_fixed
#define png_set_mem_fn wx_png_set_mem_fn
#define png_set_oFFs wx_png_set_oFFs
#define png_set_option wx_png_set_option
#define png_set_pCAL wx_png_set_pCAL
#define png_set_pHYs wx_png_set_pHYs
#define png_set_packing wx_png_set_packing
#define png_set_packswap wx_png_set_packswap
#define png_set_palette_to_rgb wx_png_set_palette_to_rgb
#define png_set_progressive_read_fn wx_png_set_progressive_read_fn
#define png_set_quantize wx_png_set_quantize
#define png_set_read_fn wx_png_set_read_fn
#define png_set_read_status_fn wx_png_set_read_status_fn
#define png_set_read_user_chunk_fn wx_png_set_read_user_chunk_fn
#define png_set_read_user_transform_fn wx_png_set_read_user_transform_fn
#define png_set_rgb_to_gray wx_png_set_rgb_to_gray
#define png_set_rgb_to_gray_fixed wx_png_set_rgb_to_gray_fixed
#define png_set_rows wx_png_set_rows
#define png_set_sBIT wx_png_set_sBIT
#define png_set_sCAL wx_png_set_sCAL
#define png_set_sCAL_fixed wx_png_set_sCAL_fixed
#define png_set_sCAL_s wx_png_set_sCAL_s
#define png_set_sPLT wx_png_set_sPLT
#define png_set_sRGB wx_png_set_sRGB
#define png_set_sRGB_gAMA_and_cHRM wx_png_set_sRGB_gAMA_and_cHRM
#define png_set_scale_16 wx_png_set_scale_16
#define png_set_shift wx_png_set_shift
#define png_set_sig_bytes wx_png_set_sig_bytes
#define png_set_strip_16 wx_png_set_strip_16
#define png_set_strip_alpha wx_png_set_strip_alpha
#define png_set_swap wx_png_set_swap
#define png_set_swap_alpha wx_png_set_swap_alpha
#define png_set_tIME wx_png_set_tIME
#define png_set_tRNS wx_png_set_tRNS
#define png_set_tRNS_to_alpha wx_png_set_tRNS_to_alpha
#define png_set_text wx_png_set_text
#define png_set_text_compression_level wx_png_set_text_compression_level
#define png_set_text_compression_mem_level wx_png_set_text_compression_mem_level
#define png_set_text_compression_method wx_png_set_text_compression_method
#define png_set_text_compression_strategy wx_png_set_text_compression_strategy
#define png_set_text_compression_window_bits wx_png_set_text_compression_window_bits
#define png_set_unknown_chunk_location wx_png_set_unknown_chunk_location
#define png_set_unknown_chunks wx_png_set_unknown_chunks
#define png_set_user_limits wx_png_set_user_limits
#define png_set_user_transform_info wx_png_set_user_transform_info
#define png_set_write_fn wx_png_set_write_fn
#define png_set_write_status_fn wx_png_set_write_status_fn
#define png_set_write_user_transform_fn wx_png_set_write_user_transform_fn
#define png_sig_cmp wx_png_sig_cmp
#define png_start_read_image wx_png_start_read_image
#define png_warning wx_png_warning
#define png_write_chunk wx_png_write_chunk
#define png_write_chunk_data wx_png_write_chunk_data
#define png_write_chunk_end wx_png_write_chunk_end
#define png_write_chunk_start wx_png_write_chunk_start
#define png_write_end wx_png_write_end
#define png_write_flush wx_png_write_flush
#define png_write_image wx_png_write_image
#define png_write_info wx_png_write_info
#define png_write_info_before_PLTE wx_png_write_info_before_PLTE
#define png_write_png wx_png_write_png
#define png_write_row wx_png_write_row
#define png_write_rows wx_png_write_rows
#define png_write_sig wx_png_write_sig
#define wx_png_get_uint_32(buf) PNG_get_uint_32(buf)
#define wx_png_get_uint_16(buf) PNG_get_uint_16(buf)
#define wx_png_get_int_32(buf) PNG_get_int_32(buf)
#endif /* PNGLCONF_H */

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