Files
alkane-toolkit/thirdparty/wx-rs/wx-rs-0.2.0-patched/build.rs
T
noahandClaude Opus 4.8 82492231bc gui: right-click install/uninstall of alkane-os via the self-contained engine
Wire the GUI to the toolkit's own compiled-in, network-only stock<->alkane engine
(alkane-flash::stock) and the .afw fetch/verify (alkane-artifacts), so a scanned
control board can be right-clicked to:

  - Install alkane OS (from stock): scans alkane-os releases on Gitea, picks one
    (newest first; pre-releases marked), downloads+verifies the .afw, and installs
    it onto each selected board over the network. Optional board password and an
    allow-unsigned (bench) toggle; typed FLASH confirmation.
  - Uninstall alkane OS (restore to stock): restores each selected board to
    genuine stock over the network, with the board's alkane root credential and a
    typed FLASH confirmation.

Both run on a background thread (stock_ops.rs), streaming progress/results to the
status bar, and share the exclusivity guards so they never race a scan/flash/
restore. These use the same engine the CLI drives; the GUI's older asic-rs
firmware-upload path stays disabled.

alkane-artifacts: add list_releases + fetch_afw_url for the release picker, and an
optional build-time embedded read-only token (option_env!("ALKANE_EMBEDDED_TOKEN"))
so a distributed GUI can scan the private alkane-os releases with no setup; the
env token still wins, and no secret is in the source tree.

wx-rs (vendored, patched): build on system wxWidgets 3.2 - guard the 3.3-only
wxApp::SetAppearance/Appearance behind wxCHECK_VERSION(3,3,0), and emit GTK's own
shared libs (pkg-config --libs gtk+-3.0) at link time since the widget bridge
calls GTK directly. Enables the Linux GUI release build.

docs/install.md: document the GUI actions and that the stock-assets repo is now
public (no token for install/restore; only release scanning needs one).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 14:18:24 -06:00

457 lines
17 KiB
Rust

use std::env;
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use bzip2::read::BzDecoder;
use cc;
use embed_resource;
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 {
target_os() == "windows"
}
fn is_msvc() -> bool {
is_windows() && target_env() == "msvc"
}
fn is_osx() -> bool {
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 {
target_os() == "linux"
}
// alkane-toolkit patch: Linux (wxGTK), macOS (wxOSX/Cocoa, universal static
// build) and Windows/GNU (wxMSW built with mingw-w64, natively or cross from
// Linux) all build against a wx prefix described by its wx-config script, so
// they share one code path. Upstream's MSVC/nmake path is left as it was.
fn uses_wx_config() -> bool {
is_linux() || is_osx() || (is_windows() && !is_msvc())
}
fn is_stub() -> bool {
cfg!(feature = "stub_lib") || (!is_windows() && !is_osx() && !is_linux())
}
fn main() -> Result<(), Box<dyn Error>> {
let wx_path = download_dist()?;
build_bridge_lib(&wx_path)?;
if is_stub() {
return Ok(());
}
if uses_wx_config() {
return Ok(()); // libs are linked inside build_with_wx_config()
}
let wx_libs = get_libs(&wx_path)?;
let mut iter = wx_libs.split_whitespace();
while let Some(flag) = iter.next() {
if flag.starts_with("-l") {
println!("cargo:rustc-link-lib={}", &flag[2..]);
} else if flag.starts_with("-L") {
println!("cargo:rustc-link-search={}", &flag[2..]);
} else if flag == "-framework" {
println!("cargo:rustc-link-lib=framework={}", iter.next().unwrap());
}
}
if is_msvc() {
println!("cargo:rustc-link-lib=static=wxbase32u");
println!("cargo:rustc-link-lib=static=wxmsw32u_core");
println!("cargo:rustc-link-lib=static=wxpng");
println!("cargo:rustc-link-lib=static=wxjpeg");
println!("cargo:rustc-link-lib=static=wxtiff");
println!("cargo:rustc-link-lib=static=wxregexu");
println!("cargo:rustc-link-lib=static=wxzlib");
let include_path = wx_path.join("include");
let resource_file = include_path.join("wx/msw/wx.rc");
env::set_var("INCLUDE", include_path.to_str().unwrap());
embed_resource::compile(resource_file);
} else if is_windows() {
println!("cargo:rustc-link-search=C://msys64/mingw64/lib");
println!("cargo:rustc-link-search=C://msys64/usr/lib/w32api");
println!("cargo:rustc-link-lib=static=wx_mswu_gl-3.2");
println!("cargo:rustc-link-lib=static=wx_mswu_core-3.2");
println!("cargo:rustc-link-lib=static=wx_baseu-3.2");
println!("cargo:rustc-link-lib=static=wxpng-3.2");
println!("cargo:rustc-link-lib=static=wxjpeg-3.2");
println!("cargo:rustc-link-lib=static=wxtiff-3.2");
println!("cargo:rustc-link-lib=static=wxregexu-3.2");
embed_resource_file(&wx_path);
}
Ok(())
}
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() || uses_wx_config() {
return Ok(wx_path);
}
println!("cargo:warning=wx-rs: Downloading source to './dist/");
fs::create_dir_all(dist_path)?;
let source_response = reqwest::blocking::get(WX_SOURCE)?;
let decoder = BzDecoder::new(source_response);
let mut archive = tar::Archive::new(decoder);
for file in archive.entries()? {
let mut file = file?;
file.unpack_in(dist_path)?;
}
return Ok(wx_path);
}
fn build_bridge_lib(wx_path: &Path) -> Result<(), Box<dyn Error>> {
if is_stub() {
println!("cargo:warning=wx-rs: Platform unsupported. Building a stub library.");
println!("cargo:rerun-if-changed=cpp_src/wxstub.cpp");
cc::Build::new()
.cpp(true)
.file("cpp_src/wxstub.cpp")
.compile("libwxbridge.a");
return Ok(());
}
println!("cargo:rerun-if-changed=cpp_src/wxbridge.cpp");
println!("cargo:rerun-if-changed=cpp_src/widgets_bridge.cpp");
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
if uses_wx_config() {
return build_with_wx_config();
}
if is_windows() {
build_msvc(wx_path)?;
} else {
panic!("Not supported")
};
let wx_flags = if is_msvc() {
format!(
"-I{}/lib/vc_x64_lib/mswu -I{}/include -D_WIN64 -D_FILE_OFFSET_BITS=64 -D__WXMSW__ -D_UNICODE -DNDEBUG -DNOPCH /GR /EHsc",
wx_path.display(),
wx_path.display(),
)
} else if is_windows() {
format!("-I{}/msw64-release-build/lib/wx/include/msw-unicode-static-3.1 -I{}/include -D_FILE_OFFSET_BITS=64 -D__WXMSW__", wx_path.display(), wx_path.display())
} else if is_osx() {
String::from_utf8(
Command::new(format!("{}/osx-release-build/wx-config", wx_path.display()))
.arg("--cxxflags")
.output()?
.stdout,
)?
} else {
panic!("Unsupported platform")
};
env::set_var("CXXFLAGS", wx_flags);
cc::Build::new()
.cpp(true)
.file("cpp_src/wxbridge.cpp")
.shared_flag(false)
.compile("libwxbridge.a");
Ok(())
}
fn build_msvc(wx_path: &Path) -> Result<(), Box<dyn Error>> {
if wx_path
.join("lib")
.join("vc_x64_lib")
.join("wxmsw32u_core.lib")
.exists()
{
println!("cargo:warning=wx-rs: Already built wxWidgets. Skipping a re-build.");
return Ok(());
}
println!("cargo:warning=wx-rs: Building wxWidgets. This can take a few minutes.");
let status = Command::new("nmake")
.current_dir(wx_path.join("build").join("msw"))
.args([
"-f",
"makefile.vc",
"-a",
"BUILD=release",
"TARGET_CPU=X64",
"USE_STC=0",
"USE_OPENGL=0",
"USE_HTML=0",
"USE_AUI=0",
"USE_MEDIA=0",
"USE_PROPGRID=0",
"USE_QA=0",
"USE_RIBBON=0",
"USE_WEBVIEW=0",
"USE_XRC=0",
])
.output()?;
let stdout = std::str::from_utf8(&status.stdout)?.to_string();
let stderr = std::str::from_utf8(&status.stderr)?.to_string();
println!("Building: {}", stdout);
assert!(status.status.success(), "{}", stderr);
Ok(())
}
fn get_libs(wx_path: &PathBuf) -> Result<String, Box<dyn Error>> {
if is_msvc() {
msvc_libs(wx_path)
} else if is_windows() {
windows_libs(wx_path)
} else if is_osx() {
osx_libs(wx_path)
} else {
panic!("Unsupported platform")
}
}
fn msvc_libs(wx_path: &Path) -> Result<String, Box<dyn Error>> {
Ok(format!(
"-L{} -lrpcrt4 -loleaut32 -lole32 -luuid -lwinspool -lwinmm -lshell32 -lcomctl32 -lcomdlg32 -ladvapi32 -lwsock32 -lgdi32 -loleacc -lversion -luxtheme -lshlwapi -luser32",
&wx_path.join("lib").join("vc_x64_lib").canonicalize()?.to_str().unwrap()[4..],
))
}
fn windows_libs(wx_path: &Path) -> Result<String, Box<dyn Error>> {
Ok(format!("-L{}/msw64-release-build/lib -lopengl32 -lwxtiff-3.1 -lwxjpeg-3.1 -lwxpng-3.1 -lwxregexu-3.1 -lwxscintilla-3.1 -lrpcrt4 -loleaut32 -lole32 -luuid -lwinspool -lwinmm -lshell32 -lcomctl32 -lcomdlg32 -ladvapi32 -lwsock32 -lgdi32 -lexpat -lz -loleacc -lversion -luxtheme -lshlwapi -luser32", &wx_path.canonicalize()?.to_str().unwrap()[4..]))
}
fn osx_libs(wx_path: &Path) -> Result<String, Box<dyn Error>> {
Ok(String::from_utf8(
Command::new(format!("{}/osx-release-build/wx-config", wx_path.display()))
.arg("--libs")
.arg("core,base,gl")
.output()?
.stdout,
)?)
}
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 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)
.file("cpp_src/wxbridge.cpp")
.file("cpp_src/widgets_bridge.cpp");
if is_osx() {
// Cocoa calls wx does not wrap (native alternating rows, self-test
// snapshot); clang compiles .mm as Objective-C++.
println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
build.file("cpp_src/osx_native.mm");
}
let mut flags = cxxflags.split_whitespace();
while let Some(f) = flags.next() {
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
// one target at a time and cc adds that target's own -arch.
if is_osx() && f == "-arch" {
flags.next();
continue;
}
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);
}
// ...and GTK's own shared libraries at link time. `wx-config --libs`
// lists only the wx libraries, not the GTK libraries the widget bridge
// calls directly (gtk_*, g_*), so without this the final link fails with
// undefined GTK symbols. Best-effort: empty if pkg-config/gtk3-dev is
// missing, in which case the GTK-only bridge code was also compiled out.
let gtk_libs = Command::new("pkg-config")
.args(["--libs", "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_libs.split_whitespace() {
if let Some(lib) = f.strip_prefix("-l") {
println!("cargo:rustc-link-lib={}", lib);
} else if let Some(path) = f.strip_prefix("-L") {
println!("cargo:rustc-link-search=native={}", path);
}
}
}
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");
if is_osx() {
// wxOSX's Objective-C uses @available, which calls
// ___isPlatformVersionAtLeast from clang's compiler runtime. clang
// links that runtime itself, but rustc drives the link without it.
let resource_dir = Command::new("clang")
.arg("-print-resource-dir")
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.ok_or("wx-rs: cannot ask clang for its resource directory")?;
let rt = Path::new(&resource_dir).join("lib").join("darwin");
if !rt.join("libclang_rt.osx.a").exists() {
return Err(format!("wx-rs: no libclang_rt.osx.a in {}", rt.display()).into());
}
println!("cargo:rustc-link-search=native={}", rt.display());
println!("cargo:rustc-link-lib=static=clang_rt.osx");
}
let mut lib_flags = libs.split_whitespace();
while let Some(flag) = lib_flags.next() {
if is_osx() {
match flag {
"-arch" => {
lib_flags.next();
continue;
}
"-framework" => {
if let Some(name) = lib_flags.next() {
println!("cargo:rustc-link-lib=framework={}", name);
}
continue;
}
"-weak_framework" => {
if let Some(name) = lib_flags.next() {
println!("cargo:rustc-link-arg=-Wl,-weak_framework,{}", name);
}
continue;
}
_ if flag.starts_with("-Wl,") => {
println!("cargo:rustc-link-arg={}", flag);
continue;
}
_ => {}
}
}
if flag.ends_with(".a") && Path::new(flag).is_absolute() {
// static wx builds: wx-config emits the archive as a full path
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)
.strip_suffix(".a")
.unwrap_or(file);
println!("cargo:rustc-link-lib=static={}", stem);
} else if let Some(lib) = flag.strip_prefix("-l") {
println!("cargo:rustc-link-lib={}", lib);
} else if let Some(path) = flag.strip_prefix("-L") {
println!("cargo:rustc-link-search=native={}", path);
} 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(())
}
fn embed_resource_file(wx_path: &PathBuf) {
/*
This was cribbed from https://github.com/nabijaczleweli/rust-embed-resource
but extended to support the `--include-dir` argument to windres
*/
let include_path = wx_path.join("include");
let resource_file = include_path.join("wx/msw/wx.rc");
let prefix = &resource_file
.file_stem()
.expect("resource_file has no stem")
.to_str()
.expect("resource_file's stem not UTF-8");
let out_dir = env::var("OUT_DIR").expect("No OUT_DIR env var");
let resource = resource_file.to_str().unwrap();
let out_file = format!("{}/lib{}.a", out_dir, prefix);
// https://sourceware.org/binutils/docs/binutils/windres.html
match Command::new("windres")
.args(&[
"--include-dir",
include_path.to_str().unwrap(),
"--input",
resource,
"--output-format=coff",
"--output",
&out_file,
])
.status()
{
Ok(stat) if stat.success() => {}
Ok(stat) => panic!(
"windres failed to compile \"{}\" into \"{}\" with {}",
resource, out_file, stat
),
Err(e) => panic!(
"Couldn't execute windres to compile \"{}\" into \"{}\": {}",
resource, out_file, e
),
}
println!("cargo:rustc-link-search=native={}", out_dir);
println!("cargo:rustc-link-lib=dylib={}", prefix);
}