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>
This commit is contained in:
@@ -81,7 +81,7 @@ impl SshTarget {
|
||||
}
|
||||
|
||||
fn command(&self, probe: Probe) -> Command {
|
||||
let mut command = Command::new("ssh");
|
||||
let mut command = alkane_core::platform::quiet_command("ssh");
|
||||
command
|
||||
.arg("-F")
|
||||
.arg("none")
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
// alkane-core
|
||||
|
||||
pub mod platform;
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! The few places the toolkit's behaviour depends on the operating system,
|
||||
//! kept together so the rest of the code stays platform-neutral.
|
||||
//!
|
||||
//! - where per-user settings live ([`config_dir`]),
|
||||
//! - how a secret file is written so only its owner can read it
|
||||
//! ([`write_private`]),
|
||||
//! - the null device for tools that insist on an output path ([`NULL_DEVICE`]),
|
||||
//! - how helper programs (`ssh`, `curl`) are started from the GUI without a
|
||||
//! console window popping up on Windows ([`quiet_command`]).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// Directory name of the toolkit's settings under the per-user config root.
|
||||
pub const APP_DIR: &str = "alkane-toolkit";
|
||||
|
||||
/// Environment variable whose value is the per-user config root on this
|
||||
/// platform: `HOME` (settings in `$HOME/.config/alkane-toolkit`) on Unix,
|
||||
/// `APPDATA` (settings in `%APPDATA%\alkane-toolkit`) on Windows. Tests point it
|
||||
/// at a scratch directory.
|
||||
#[cfg(not(windows))]
|
||||
pub const CONFIG_ROOT_VAR: &str = "HOME";
|
||||
#[cfg(windows)]
|
||||
pub const CONFIG_ROOT_VAR: &str = "APPDATA";
|
||||
|
||||
/// The per-user settings directory (not created here).
|
||||
///
|
||||
/// Unix keeps the long-standing `$HOME/.config/alkane-toolkit`. Windows uses
|
||||
/// the roaming application-data folder, `%APPDATA%\alkane-toolkit`, which is
|
||||
/// where Windows applications keep per-user settings and which the user
|
||||
/// profile's ACL already restricts to its owner. A missing variable falls back
|
||||
/// to the working directory, as before.
|
||||
pub fn config_dir() -> PathBuf {
|
||||
let root = std::env::var_os(CONFIG_ROOT_VAR).unwrap_or_else(|| ".".into());
|
||||
if cfg!(windows) {
|
||||
PathBuf::from(root).join(APP_DIR)
|
||||
} else {
|
||||
PathBuf::from(root).join(".config").join(APP_DIR)
|
||||
}
|
||||
}
|
||||
|
||||
/// `config_dir()/file`.
|
||||
pub fn config_path(file: &str) -> PathBuf {
|
||||
config_dir().join(file)
|
||||
}
|
||||
|
||||
/// The null device, for tools that want an output path (`curl -o`,
|
||||
/// `ssh -o UserKnownHostsFile=`).
|
||||
#[cfg(not(windows))]
|
||||
pub const NULL_DEVICE: &str = "/dev/null";
|
||||
#[cfg(windows)]
|
||||
pub const NULL_DEVICE: &str = "NUL";
|
||||
|
||||
/// Write `data` to `path` so only the owner can read it.
|
||||
///
|
||||
/// On Unix the file is created 0600 (so a secret is never momentarily
|
||||
/// world-readable between write and chmod), and a pre-existing file is
|
||||
/// re-tightened while it is still empty, before the plaintext is written. On
|
||||
/// Windows the settings directory inherits the user profile's owner-only ACL,
|
||||
/// so a plain write already has the equivalent protection.
|
||||
pub fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)?;
|
||||
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
|
||||
f.write_all(data)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
std::fs::write(path, data)
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Command`] for a helper program run in the background of the GUI.
|
||||
///
|
||||
/// On Windows a console program (`ssh.exe`, `curl.exe`) started from a GUI
|
||||
/// process gets a new console window by default, so every probe would flash a
|
||||
/// black window; `CREATE_NO_WINDOW` suppresses that while keeping its piped
|
||||
/// stdin/stdout/stderr. Elsewhere this is `Command::new`.
|
||||
pub fn quiet_command(program: &str) -> Command {
|
||||
#[allow(unused_mut)]
|
||||
let mut command = Command::new(program);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn config_dir_is_under_the_platform_root() {
|
||||
let dir = config_dir();
|
||||
assert!(dir.ends_with(APP_DIR), "{dir:?}");
|
||||
if cfg!(windows) {
|
||||
assert!(!dir.to_string_lossy().contains(".config"), "{dir:?}");
|
||||
} else {
|
||||
assert!(dir.parent().unwrap().ends_with(".config"), "{dir:?}");
|
||||
}
|
||||
assert_eq!(config_path("x.txt"), dir.join("x.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_private_round_trips_and_restricts() {
|
||||
let dir = std::env::temp_dir().join(format!("alkane-private-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("secret.txt");
|
||||
write_private(&path, b"one").unwrap();
|
||||
write_private(&path, b"two").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"two");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_command_runs_with_piped_output() {
|
||||
// `cmd /C echo` and `sh -c echo` are the platform's own shells.
|
||||
let mut command = if cfg!(windows) {
|
||||
let mut c = quiet_command("cmd");
|
||||
c.args(["/C", "echo alkane"]);
|
||||
c
|
||||
} else {
|
||||
let mut c = quiet_command("sh");
|
||||
c.args(["-c", "echo alkane"]);
|
||||
c
|
||||
};
|
||||
let out = command.output().unwrap();
|
||||
assert!(out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("alkane"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Build script for the alkane-toolkit binary. On Windows targets it compiles
|
||||
//! windows/alkane-toolkit.rc (application manifest, icon, version info, and
|
||||
//! wxMSW's stock resources) and links the result into the GUI executable only.
|
||||
//! Other targets need nothing here.
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
for f in [
|
||||
"alkane-toolkit.rc",
|
||||
"alkane-toolkit.exe.manifest",
|
||||
"alkane-toolkit.ico",
|
||||
] {
|
||||
println!("cargo:rerun-if-changed=windows/{f}");
|
||||
}
|
||||
println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
|
||||
if let Err(e) = compile_resources() {
|
||||
panic!("alkane-gui: Windows resources: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_resources() -> Result<(), String> {
|
||||
// The resource compiler and wx's resource include path come from the same
|
||||
// wx-config the wx-rs bridge builds against, so they always match the
|
||||
// linked wxMSW (and the mingw cross windres when cross-compiling).
|
||||
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| "wx-config".into());
|
||||
let run = |arg: &str| -> Result<String, String> {
|
||||
let out = Command::new(&wxconfig)
|
||||
.arg(arg)
|
||||
.output()
|
||||
.map_err(|e| format!("cannot run {wxconfig} {arg}: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("{wxconfig} {arg} failed"));
|
||||
}
|
||||
String::from_utf8(out.stdout).map_err(|e| e.to_string())
|
||||
};
|
||||
let rescomp = run("--rescomp")?;
|
||||
let mut words = rescomp.split_whitespace();
|
||||
let windres = words.next().ok_or("wx-config --rescomp printed nothing")?;
|
||||
let mut args: Vec<String> = words.map(str::to_owned).collect();
|
||||
// rcdefs.h lives in the build-specific setup directory, which --rescomp
|
||||
// omits; it is the -I entry of --cxxflags.
|
||||
for flag in run("--cxxflags")?.split_whitespace() {
|
||||
if let Some(dir) = flag.strip_prefix("-I") {
|
||||
args.push("--include-dir".into());
|
||||
args.push(dir.into());
|
||||
}
|
||||
}
|
||||
|
||||
let version = env::var("CARGO_PKG_VERSION").unwrap_or_default();
|
||||
let mut parts = version
|
||||
.split(['.', '-', '+'])
|
||||
.map(|p| p.parse::<u16>().unwrap_or(0));
|
||||
let (major, minor, patch) = (
|
||||
parts.next().unwrap_or(0),
|
||||
parts.next().unwrap_or(0),
|
||||
parts.next().unwrap_or(0),
|
||||
);
|
||||
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(|e| e.to_string())?);
|
||||
let out =
|
||||
PathBuf::from(env::var("OUT_DIR").map_err(|e| e.to_string())?).join("alkane-toolkit-res.o");
|
||||
let status = Command::new(windres)
|
||||
.args(&args)
|
||||
.arg("--include-dir")
|
||||
.arg(manifest_dir.join("windows"))
|
||||
.arg(format!("--define=ALKANE_VER_MAJOR={major}"))
|
||||
.arg(format!("--define=ALKANE_VER_MINOR={minor}"))
|
||||
.arg(format!("--define=ALKANE_VER_PATCH={patch}"))
|
||||
.arg(format!("--define=ALKANE_VER_STR=\\\"{version}\\\""))
|
||||
.arg("--input")
|
||||
.arg(manifest_dir.join("windows/alkane-toolkit.rc"))
|
||||
.arg("--output-format=coff")
|
||||
.arg("--output")
|
||||
.arg(&out)
|
||||
.status()
|
||||
.map_err(|e| format!("cannot run {windres}: {e}"))?;
|
||||
if !status.success() {
|
||||
return Err(format!("{windres} failed ({status})"));
|
||||
}
|
||||
// Only the GUI binary carries the manifest/icon; miner_probe stays a plain
|
||||
// console tool. A linked object (not an archive member) is never dropped by
|
||||
// the linker, which is what keeps the resource section in the .exe.
|
||||
println!("cargo:rustc-link-arg-bin=alkane-toolkit={}", out.display());
|
||||
Ok(())
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,7 @@ fn load_creds() -> Option<(String, String)> {
|
||||
) {
|
||||
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();
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
//! 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 alkane_core::platform::write_private;
|
||||
|
||||
use asic_rs::core::traits::miner::MinerAuth;
|
||||
use asic_rs::MinerFactory;
|
||||
@@ -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.
|
||||
@@ -218,6 +201,20 @@ 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
|
||||
@@ -226,11 +223,12 @@ mod tests {
|
||||
let _home = crate::model::HOME_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let prev = std::env::var_os("HOME");
|
||||
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");
|
||||
|
||||
@@ -240,11 +238,9 @@ mod tests {
|
||||
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:
|
||||
@@ -255,13 +251,15 @@ 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_eq!(
|
||||
meta.permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"save over a pre-existing 0644 file must re-tighten to 0600"
|
||||
assert_owner_only(
|
||||
&path,
|
||||
"save over a pre-existing 0644 file must re-tighten to 0600",
|
||||
);
|
||||
assert_eq!(
|
||||
load_credentials(),
|
||||
@@ -290,11 +288,7 @@ mod tests {
|
||||
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"),
|
||||
@@ -322,8 +316,8 @@ mod tests {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -71,10 +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).
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
//! 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;
|
||||
@@ -17,6 +22,15 @@ 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).
|
||||
@@ -60,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();
|
||||
@@ -92,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() {}
|
||||
|
||||
@@ -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 {
|
||||
@@ -72,8 +70,7 @@ 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).
|
||||
@@ -106,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
|
||||
|
||||
@@ -249,21 +249,24 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
||||
);
|
||||
}
|
||||
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",
|
||||
&known_hosts,
|
||||
"-o",
|
||||
"ConnectTimeout=8",
|
||||
&target,
|
||||
@@ -375,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() {
|
||||
|
||||
@@ -40,7 +40,6 @@ pub enum ScanMsg {
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
pub const CONFIG_DIR: &str = ".config/alkane-toolkit";
|
||||
pub const RANGES_FILE: &str = "scan-ranges.txt";
|
||||
pub const AUTO_FILE: &str = "auto-rescan-secs.txt";
|
||||
pub const SCAN_TIMEOUT_FILE: &str = "scan-timeout-secs.txt";
|
||||
@@ -128,9 +127,10 @@ pub fn save_scan_timeout(secs: u64) -> std::io::Result<()> {
|
||||
std::fs::write(p, secs.max(1).to_string())
|
||||
}
|
||||
|
||||
/// `file` inside the per-user settings directory (`~/.config/alkane-toolkit`,
|
||||
/// or `%APPDATA%\alkane-toolkit` on Windows; see `alkane_core::platform`).
|
||||
pub 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)
|
||||
}
|
||||
|
||||
pub fn load_ranges() -> Vec<String> {
|
||||
@@ -2368,17 +2368,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn auto_secs_round_trip_and_defaults() {
|
||||
// config_path() reads $HOME; point it at a private temp dir. HOME is
|
||||
// process-global, so serialise against other HOME-mutating tests and
|
||||
// restore HOME afterward (round 18 #12).
|
||||
// config_path() reads the platform's config root ($HOME, or %APPDATA%
|
||||
// on Windows); point it at a private temp dir. It is process-global, so
|
||||
// serialise against other such tests and restore it 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 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-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_auto_secs(),
|
||||
@@ -2393,8 +2394,8 @@ mod tests {
|
||||
assert_eq!(load_auto_secs(), 42, "whitespace tolerated");
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
# Regenerate alkane-toolkit.ico (the Windows executable/taskbar icon) from the
|
||||
# in-repo microchip glyph: a white chip on a rounded amber tile, at the sizes
|
||||
# Windows asks for (16-256 px). Needs rsvg-convert and ImageMagick; the .ico is
|
||||
# committed, so a normal build never runs this.
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
GLYPH=../assets/icons/microchip-solid-full.svg
|
||||
TMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP"' 0
|
||||
sed 's/currentColor/#ffffff/g; s/<svg /<svg fill="#ffffff" /' "$GLYPH" > "$TMP/glyph.svg"
|
||||
for s in 16 20 24 32 40 48 64 256; do
|
||||
r=$((s * 22 / 100)); g=$((s * 64 / 100)); o=$(((s - g) / 2))
|
||||
rsvg-convert -w "$g" -h "$g" "$TMP/glyph.svg" -o "$TMP/g$s.png"
|
||||
convert -size "${s}x${s}" xc:none -fill '#d9822b' \
|
||||
-draw "roundrectangle 0,0 $((s - 1)),$((s - 1)) $r,$r" \
|
||||
"$TMP/g$s.png" -geometry "+$o+$o" -composite "PNG32:$TMP/i$s.png"
|
||||
done
|
||||
convert "$TMP"/i16.png "$TMP"/i20.png "$TMP"/i24.png "$TMP"/i32.png "$TMP"/i40.png \
|
||||
"$TMP"/i48.png "$TMP"/i64.png "$TMP"/i256.png alkane-toolkit.ico
|
||||
echo "wrote $(pwd)/alkane-toolkit.ico"
|
||||
@@ -1,22 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Build the alkane-toolkit GUI for Windows (x86_64) from Linux, via mingw-w64.
|
||||
# wx-rs upstream supports MSW (it downloads and builds wx 3.2.2.1 with MSVC
|
||||
# via nmake, or links an msys2 mingw64 wx). Two supported routes:
|
||||
# Build the alkane-toolkit GUI for Windows (x86_64) on Linux by cross-compiling
|
||||
# with mingw-w64 against the vendored wxWidgets 3.3.3 (wxMSW), the same way CI
|
||||
# builds the release .exe. The result is one self-contained executable: the C++
|
||||
# runtime is linked statically and it imports only DLLs Windows itself ships.
|
||||
#
|
||||
# A) On Windows: install msys2/mingw64 wx + rust-gnu, run `cargo build
|
||||
# --release -p alkane-gui` there (wx-rs build.rs handles msys2 paths).
|
||||
# B) Cross from Linux: not automated yet - wxMSW needs the MSVC or msys2
|
||||
# toolchain; tracked as follow-up. The Rust side cross-compiles fine;
|
||||
# only the C++ bridge + wx need the Windows toolchain.
|
||||
#
|
||||
# This script documents route A and fails here if run on Linux.
|
||||
# Usage: scripts/build-gui-windows.sh [cargo build args...]
|
||||
# defaults to `--release`; e.g. `scripts/build-gui-windows.sh` or
|
||||
# `scripts/build-gui-windows.sh --profile dev`.
|
||||
# Needs: mingw-w64 (posix-threads variant), the rustup target
|
||||
# x86_64-pc-windows-gnu, and the wxMSW prefix from build-wx-windows.sh
|
||||
# (built on first use).
|
||||
set -e
|
||||
if [ "$(uname -s)" = "Linux" ]; then
|
||||
echo "Route B (Linux cross to MSW) is not automated yet."
|
||||
echo "Run scripts/build-gui-windows.sh on Windows (msys2 mingw64 + rust),"
|
||||
echo "or use CI with a Windows runner."
|
||||
exit 1
|
||||
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$REPO"
|
||||
. "$REPO/scripts/windows-cross-env.sh"
|
||||
if [ ! -x "$WX_RS_WXCONFIG" ]; then
|
||||
sh "$REPO/scripts/build-wx-windows.sh"
|
||||
fi
|
||||
cd "$(dirname -- "$0")/.."
|
||||
cargo build --release -p alkane-gui
|
||||
echo "binary: target/release/alkane-toolkit.exe"
|
||||
rustup target list --installed 2>/dev/null | grep -qx "$ALKANE_WIN_TARGET" ||
|
||||
rustup target add "$ALKANE_WIN_TARGET"
|
||||
[ "$#" -gt 0 ] || set -- --release
|
||||
cargo build --offline --target "$ALKANE_WIN_TARGET" -p alkane-gui "$@"
|
||||
TDIR=$(cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \
|
||||
| tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
echo "binary: ${TDIR:-$REPO/target}/$ALKANE_WIN_TARGET/<profile>/alkane-toolkit.exe"
|
||||
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
# Cross-build the vendored wxWidgets 3.3.3 for Windows (wxMSW, x86_64, static,
|
||||
# monolithic) from Linux with mingw-w64. Mirrors build-wx-linux.sh: the repo
|
||||
# tree stays pristine, the build lives in ~/.cache/wxbuild, and the result is a
|
||||
# prefix whose bin/wx-config the wx-rs build script reads (WX_RS_WXCONFIG).
|
||||
#
|
||||
# Every third-party library wx needs is the copy bundled in the wx source tree
|
||||
# ("builtin"), so the prefix needs nothing from the build host and the final
|
||||
# .exe needs no DLLs beyond the ones Windows itself ships. TIFF and WebP are
|
||||
# off: the app never loads either format.
|
||||
#
|
||||
# Needs: mingw-w64 (the posix-threads g++ variant), make.
|
||||
set -e
|
||||
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3"
|
||||
HOST=x86_64-w64-mingw32
|
||||
BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3-mingw"
|
||||
PREFIX="${WX_WINDOWS_PREFIX:-$HOME/.cache/wx-3.3.3-mingw}"
|
||||
# std::thread/std::mutex need the posix thread model; Debian's default
|
||||
# x86_64-w64-mingw32-g++ alternative is the win32 model.
|
||||
CC="${WX_WINDOWS_CC:-$HOST-gcc-posix}"
|
||||
CXX="${WX_WINDOWS_CXX:-$HOST-g++-posix}"
|
||||
command -v "$CXX" >/dev/null || { echo "$CXX not found (apt install mingw-w64)"; exit 1; }
|
||||
|
||||
cleanup_wx_build() {
|
||||
python3 - "$BUILD" "$HOME/.cache/wxbuild" <<'PY'
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
build, parent = map(Path, sys.argv[1:])
|
||||
if (build.name != "wxWidgets-3.3.3-mingw" or build.parent != parent
|
||||
or build.is_symlink() or parent.is_symlink()):
|
||||
raise SystemExit("refusing unsafe wxWidgets build cleanup path")
|
||||
if build.is_dir():
|
||||
shutil.rmtree(build)
|
||||
PY
|
||||
}
|
||||
trap cleanup_wx_build 0
|
||||
[ -d "$SRC" ] || { echo "thirdparty wxWidgets tree missing"; exit 1; }
|
||||
[ -d "$BUILD" ] || { mkdir -p "$HOME/.cache/wxbuild"; cp -r "$SRC" "$BUILD"; }
|
||||
chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true
|
||||
mkdir -p "$BUILD/build-msw"
|
||||
cd "$BUILD/build-msw"
|
||||
# --enable-unicode is the 3.3 default. wxUSE_RC_MANIFEST/DPI awareness are
|
||||
# handled by the application's own resource script (crates/alkane-gui/build.rs),
|
||||
# not here, so the library stays policy-free.
|
||||
sh ../configure --host="$HOST" --build="$(sh ../config.guess)" \
|
||||
--prefix="$PREFIX" CC="$CC" CXX="$CXX" \
|
||||
--disable-shared --enable-monolithic --with-msw \
|
||||
--with-opengl=no --disable-stc --disable-tests --disable-webview \
|
||||
--with-libpng=builtin --with-libjpeg=builtin --with-regex=builtin \
|
||||
--with-zlib=builtin --with-expat=builtin \
|
||||
--without-libtiff --without-libwebp --without-liblzma
|
||||
make -j"${WX_BUILD_JOBS:-$(nproc)}"
|
||||
make install
|
||||
ls "$PREFIX"/lib/libwx_mswu-3.3-"$HOST".a >/dev/null
|
||||
echo "installed: $PREFIX ($("$PREFIX/bin/wx-config" --version) $("$PREFIX/bin/wx-config" --selected-config))"
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Headless UI workflow self-test of the WINDOWS build, under Wine on a private
|
||||
# Xvfb display: the same ALKANE_SELFTEST check as scripts/ui-selftest.sh (bench
|
||||
# fixtures rendered through the real wxMSW widgets, read back, and compared),
|
||||
# run against alkane-toolkit.exe. CI runs this on every build; the native
|
||||
# Windows smoke job (.gitea/workflows/windows-native.yml) repeats it on real
|
||||
# Windows.
|
||||
#
|
||||
# Usage: scripts/ui-selftest-windows.sh [alkane-toolkit.exe]
|
||||
# defaults to the cross-built release binary in the cargo target dir.
|
||||
set -u
|
||||
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
EXE="${1:-}"
|
||||
if [ -z "$EXE" ]; then
|
||||
sh "$REPO/scripts/build-gui-windows.sh" || exit 3
|
||||
TDIR=$(cd "$REPO" && cargo metadata --no-deps --format-version 1 --offline 2>/dev/null \
|
||||
| tr ',' '\n' | grep -o '"target_directory":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
EXE="${TDIR:-$REPO/target}/x86_64-pc-windows-gnu/release/alkane-toolkit.exe"
|
||||
fi
|
||||
[ -f "$EXE" ] || { echo "executable not found: $EXE" >&2; exit 3; }
|
||||
# xvfb-run picks a free display and cleans it up; Wine needs an X server for
|
||||
# the window even though the self-test never shows it to anyone.
|
||||
xvfb-run -a -s '-screen 0 1280x850x24' \
|
||||
env ALKANE_SELFTEST=1 sh "$REPO/scripts/wine-run.sh" "$EXE"
|
||||
RC=$?
|
||||
echo "== ui-selftest-windows exit=$RC =="
|
||||
exit "$RC"
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
# shellcheck shell=sh
|
||||
# Toolchain environment for cross-building the toolkit for Windows
|
||||
# (x86_64-pc-windows-gnu) on Linux. One definition, used by
|
||||
# scripts/build-gui-windows.sh locally and by the CI Windows job:
|
||||
#
|
||||
# . scripts/windows-cross-env.sh # export into this shell
|
||||
# sh scripts/windows-cross-env.sh --github-env # append to $GITHUB_ENV
|
||||
#
|
||||
# WX_WINDOWS_PREFIX selects the wxMSW prefix built by build-wx-windows.sh.
|
||||
# `cargo test --target x86_64-pc-windows-gnu` runs the test .exe files through
|
||||
# scripts/wine-run.sh, so the Windows build is unit-tested on every Linux host.
|
||||
# The posix-threads mingw variants are required: libstdc++'s std::thread and
|
||||
# the wx build both use them, and mixing in the win32-thread variant at link
|
||||
# time fails on missing pthread symbols.
|
||||
WX_WINDOWS_PREFIX="${WX_WINDOWS_PREFIX:-$HOME/.cache/wx-3.3.3-mingw}"
|
||||
ALKANE_WIN_TARGET=x86_64-pc-windows-gnu
|
||||
# Sourced scripts cannot rely on $0, so locate the checkout through git.
|
||||
ALKANE_REPO="${ALKANE_REPO:-$(git rev-parse --show-toplevel)}"
|
||||
|
||||
_alkane_win_env() {
|
||||
cat <<EOF
|
||||
WX_WINDOWS_PREFIX=$WX_WINDOWS_PREFIX
|
||||
WX_RS_WXCONFIG=$WX_WINDOWS_PREFIX/bin/wx-config
|
||||
ALKANE_WIN_TARGET=$ALKANE_WIN_TARGET
|
||||
CC_x86_64_pc_windows_gnu=x86_64-w64-mingw32-gcc-posix
|
||||
CXX_x86_64_pc_windows_gnu=x86_64-w64-mingw32-g++-posix
|
||||
AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar
|
||||
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc-posix
|
||||
WINDRES=x86_64-w64-mingw32-windres
|
||||
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=$ALKANE_REPO/scripts/wine-run.sh
|
||||
EOF
|
||||
}
|
||||
|
||||
if [ "${1:-}" = "--github-env" ]; then
|
||||
_alkane_win_env >> "${GITHUB_ENV:?GITHUB_ENV is required}"
|
||||
else
|
||||
eval "$(_alkane_win_env | sed 's/^/export /')"
|
||||
fi
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Cargo target runner for x86_64-pc-windows-gnu: run a Windows .exe under Wine.
|
||||
# Set via CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER (scripts/windows-cross-env.sh).
|
||||
# A private, reusable Wine prefix keeps runs isolated from any desktop Wine
|
||||
# setup and avoids re-creating the prefix (~10 s) for every test binary.
|
||||
set -e
|
||||
export WINEPREFIX="${ALKANE_WINEPREFIX:-$HOME/.cache/alkane-wine}"
|
||||
export WINEDEBUG="${WINEDEBUG:--all}"
|
||||
# No Wine menu entries/file associations, no Gecko/Mono install prompts.
|
||||
export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-winemenubuilder.exe=d;mscoree=d;mshtml=d}"
|
||||
WINE="${WINE:-$(command -v wine64 || command -v wine)}"
|
||||
if [ ! -f "$WINEPREFIX/system.reg" ]; then
|
||||
mkdir -p "$WINEPREFIX"
|
||||
# The registry (system.reg, the "prefix is ready" marker) is only written
|
||||
# when the wine server shuts down, so finish the boot explicitly.
|
||||
"$WINE" wineboot --init >/dev/null 2>&1 || true
|
||||
"$WINE" wineboot --shutdown >/dev/null 2>&1 || true
|
||||
wineserver -w 2>/dev/null || true
|
||||
fi
|
||||
exec "$WINE" "$@"
|
||||
Vendored
+4
-2
@@ -4,5 +4,7 @@ source_url: https://static.crates.io/crates/wx-rs/wx-rs-0.2.0.crate
|
||||
sha256: b70620dba2997db6640794ef43fa130d19b9a2ec1ab93925450a5b8334d99e33
|
||||
state: patched tree is the used crate (path dep from crates/alkane-gui).
|
||||
Upstream stubs non-Windows/macOS and has no widget surface; patches add
|
||||
the Linux/GTK3 wx-config build path and the widget bridge (see patches/).
|
||||
Update flow: unpack new upstream here, re-apply patches/, resolve, commit.
|
||||
the wx-config build path (Linux/GTK3 and Windows/mingw wxMSW) and the
|
||||
widget bridge (see patches/README.md). upstream/ holds the pristine crate.
|
||||
Update flow: replace upstream/, re-apply patches/ (scripts/wx_rs_patches.py
|
||||
check shows what no longer applies), resolve, capture, commit.
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
Subject: [PATCH 0006] build.rs: pick the platform from the target, not the build host; build Windows/GNU (mingw wxMSW) through wx-config like GTK
|
||||
|
||||
--- a/build.rs
|
||||
+++ b/build.rs
|
||||
@@ -12,22 +12,42 @@
|
||||
const WX_SOURCE: &str =
|
||||
"https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.2.1/wxWidgets-3.2.2.1.tar.bz2";
|
||||
|
||||
+// alkane-toolkit patch: decide the platform from the TARGET. A build script is
|
||||
+// compiled for and runs on the build host, so `cfg!(windows)` etc. here describe
|
||||
+// the host -- which made a Linux -> Windows cross build take the GTK path.
|
||||
+// Cargo exposes the real target through CARGO_CFG_TARGET_* instead.
|
||||
+fn target_os() -> String {
|
||||
+ env::var("CARGO_CFG_TARGET_OS").unwrap_or_default()
|
||||
+}
|
||||
+
|
||||
+fn target_env() -> String {
|
||||
+ env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default()
|
||||
+}
|
||||
+
|
||||
fn is_windows() -> bool {
|
||||
- cfg!(windows)
|
||||
+ target_os() == "windows"
|
||||
}
|
||||
|
||||
fn is_msvc() -> bool {
|
||||
- cfg!(target_env = "msvc")
|
||||
+ is_windows() && target_env() == "msvc"
|
||||
}
|
||||
|
||||
fn is_osx() -> bool {
|
||||
- cfg!(target_os = "macos")
|
||||
+ target_os() == "macos"
|
||||
}
|
||||
|
||||
// alkane-toolkit patch: real wxGTK3 support on Linux via wx-config
|
||||
// (upstream stubbed every non-Windows/macOS target).
|
||||
fn is_linux() -> bool {
|
||||
- cfg!(target_os = "linux")
|
||||
+ target_os() == "linux"
|
||||
+}
|
||||
+
|
||||
+// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
|
||||
+// mingw-w64, natively or cross from Linux) both build against a wx prefix
|
||||
+// described by its wx-config script, so they share one code path. Upstream's
|
||||
+// MSVC/nmake and macOS download-and-build paths are left as they were.
|
||||
+fn uses_wx_config() -> bool {
|
||||
+ is_linux() || (is_windows() && !is_msvc())
|
||||
}
|
||||
|
||||
fn is_stub() -> bool {
|
||||
@@ -41,8 +61,8 @@
|
||||
if is_stub() {
|
||||
return Ok(());
|
||||
}
|
||||
- if is_linux() {
|
||||
- return Ok(()); // libs are linked inside build_linux()
|
||||
+ if uses_wx_config() {
|
||||
+ return Ok(()); // libs are linked inside build_with_wx_config()
|
||||
}
|
||||
|
||||
let wx_libs = get_libs(&wx_path)?;
|
||||
@@ -89,7 +109,7 @@
|
||||
fn download_dist() -> Result<PathBuf, Box<dyn Error>> {
|
||||
let dist_path = Path::new("./dist/");
|
||||
let wx_path = PathBuf::from(format!("./dist/{}", WX_PATH));
|
||||
- if wx_path.exists() || is_stub() || is_linux() {
|
||||
+ if wx_path.exists() || is_stub() || uses_wx_config() {
|
||||
return Ok(wx_path);
|
||||
}
|
||||
println!("cargo:warning=wx-rs: Downloading source to './dist/");
|
||||
@@ -120,8 +140,8 @@
|
||||
|
||||
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
|
||||
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
|
||||
- if is_linux() {
|
||||
- return build_linux();
|
||||
+ if uses_wx_config() {
|
||||
+ return build_with_wx_config();
|
||||
}
|
||||
|
||||
if is_windows() {
|
||||
@@ -232,25 +252,27 @@
|
||||
)?)
|
||||
}
|
||||
|
||||
-fn build_linux() -> Result<(), Box<dyn Error>> {
|
||||
- // alkane-toolkit patch: GTK3 build driven entirely by wx-config, so the
|
||||
- // same code builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG
|
||||
- // pointing at its prefix) or any system wxGTK3.
|
||||
+fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
|
||||
+ // alkane-toolkit patch: build driven entirely by wx-config, so the same code
|
||||
+ // builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG pointing at its
|
||||
+ // GTK or mingw prefix) or any system wx. wx-config is a POSIX shell script;
|
||||
+ // cross builds run it on the Linux host, native mingw builds under MSYS2.
|
||||
+ println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
|
||||
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| String::from("wx-config"));
|
||||
- let cxxflags = String::from_utf8(
|
||||
- Command::new(&wxconfig).arg("--cxxflags").output()?.stdout,
|
||||
- )?;
|
||||
- let libs = String::from_utf8(Command::new(&wxconfig).arg("--libs").output()?.stdout)?;
|
||||
- // The widget bridge uses GTK directly (zebra-striping CSS), so add GTK's own
|
||||
- // include paths. Best-effort: if pkg-config or gtk3-dev is missing the flags
|
||||
- // are simply empty and the GTK-only code stays disabled.
|
||||
- let gtk_cflags = Command::new("pkg-config")
|
||||
- .args(["--cflags", "gtk+-3.0"])
|
||||
- .output()
|
||||
- .ok()
|
||||
- .filter(|o| o.status.success())
|
||||
- .and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
- .unwrap_or_default();
|
||||
+ let wx_config = |arg: &str| -> Result<String, Box<dyn Error>> {
|
||||
+ let out = Command::new(&wxconfig).arg(arg).output().map_err(|e| {
|
||||
+ format!("wx-rs: cannot run {wxconfig} {arg} (set WX_RS_WXCONFIG): {e}")
|
||||
+ })?;
|
||||
+ if !out.status.success() {
|
||||
+ return Err(format!("wx-rs: {wxconfig} {arg} failed").into());
|
||||
+ }
|
||||
+ Ok(String::from_utf8(out.stdout)?)
|
||||
+ };
|
||||
+ let cxxflags = wx_config("--cxxflags")?;
|
||||
+ let libs = wx_config("--libs")?;
|
||||
+ if is_windows() && !cxxflags.contains("__WXMSW__") {
|
||||
+ return Err(format!("wx-rs: {wxconfig} is not a wxMSW build").into());
|
||||
+ }
|
||||
|
||||
let mut build = cc::Build::new();
|
||||
build.cpp(true)
|
||||
@@ -259,15 +281,37 @@
|
||||
for f in cxxflags.split_whitespace() {
|
||||
build.flag(f);
|
||||
}
|
||||
- for f in gtk_cflags.split_whitespace() {
|
||||
- build.flag(f);
|
||||
+ if is_linux() {
|
||||
+ // The widget bridge uses GTK directly (native rubber-band selection,
|
||||
+ // tooltips, themed colours), so add GTK's own include paths.
|
||||
+ // Best-effort: if pkg-config or gtk3-dev is missing the flags are simply
|
||||
+ // empty and the GTK-only code stays disabled.
|
||||
+ let gtk_cflags = Command::new("pkg-config")
|
||||
+ .args(["--cflags", "gtk+-3.0"])
|
||||
+ .output()
|
||||
+ .ok()
|
||||
+ .filter(|o| o.status.success())
|
||||
+ .and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
+ .unwrap_or_default();
|
||||
+ for f in gtk_cflags.split_whitespace() {
|
||||
+ build.flag(f);
|
||||
+ }
|
||||
+ }
|
||||
+ if is_windows() {
|
||||
+ // Ship one self-contained .exe: link the C++ runtime statically rather
|
||||
+ // than depending on the toolchain's libstdc++-6.dll/libgcc_s_seh-1.dll/
|
||||
+ // libwinpthread-1.dll, which no Windows machine has. `-bundle` hands the
|
||||
+ // archives to the final link instead of copying them into this rlib.
|
||||
+ build.cpp_link_stdlib(None);
|
||||
+ println!("cargo:rustc-link-lib=static:-bundle=stdc++");
|
||||
+ println!("cargo:rustc-link-lib=static:-bundle=winpthread");
|
||||
}
|
||||
build.compile("wxbridge");
|
||||
|
||||
for flag in libs.split_whitespace() {
|
||||
- if flag.starts_with('/') && flag.ends_with(".a") {
|
||||
+ if flag.ends_with(".a") && Path::new(flag).is_absolute() {
|
||||
// static wx builds: wx-config emits the archive as a full path
|
||||
- let file = flag.rsplit('/').next().unwrap_or(flag);
|
||||
+ let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
|
||||
let stem = file
|
||||
.strip_prefix("lib")
|
||||
.unwrap_or(file)
|
||||
@@ -281,6 +325,9 @@
|
||||
} else if flag == "-pthread" {
|
||||
println!("cargo:rustc-link-arg=-pthread");
|
||||
}
|
||||
+ // `-mwindows` / `-Wl,--subsystem,windows` are deliberately dropped: the
|
||||
+ // console-vs-GUI subsystem is the application's decision
|
||||
+ // (`#![windows_subsystem]`), not the GUI library's.
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
Subject: [PATCH 0007] wxbridge: make the upstream frame usable on wxMSW (no input-swallowing overlay, appearance before the first window, work-area sizing, exe icon, UTF-8 menu fix)
|
||||
|
||||
--- a/cpp_src/wxbridge.cpp
|
||||
+++ b/cpp_src/wxbridge.cpp
|
||||
@@ -1,5 +1,7 @@
|
||||
#include <wx/wx.h>
|
||||
#include "wx/clipbrd.h"
|
||||
+#include "wx/display.h"
|
||||
+#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(WIN64) || defined(WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
|
||||
@@ -34,6 +36,21 @@
|
||||
void setDPIAware() {}
|
||||
#endif
|
||||
|
||||
+#ifdef __WXMSW__
|
||||
+#include <wx/msw/darkmode.h>
|
||||
+// alkane-toolkit patch: wx's dark palette leaves wxSYS_COLOUR_3DLIGHT at its
|
||||
+// light value, and the generic wxDataViewCtrl (the table on MSW) draws its row
|
||||
+// and column rules in that colour -- bright grid lines across a dark table.
|
||||
+// Give it a dark-grey rule colour; everything else stays wx's default palette.
|
||||
+class DarkModeSettings : public wxDarkModeSettings {
|
||||
+ public:
|
||||
+ wxColour GetColour(wxSystemColour index) override {
|
||||
+ if (index == wxSYS_COLOUR_3DLIGHT) return wxColour(0x3a, 0x3a, 0x3a);
|
||||
+ return wxDarkModeSettings::GetColour(index);
|
||||
+ }
|
||||
+};
|
||||
+#endif
|
||||
+
|
||||
enum cursor {
|
||||
NO_CURSOR,
|
||||
ARROW_CURSOR,
|
||||
@@ -129,10 +146,19 @@
|
||||
render = NULL;
|
||||
handle_events = NULL;
|
||||
// Needed to get App to catch key events on OSX
|
||||
+ // alkane-toolkit patch: not on MSW. There this invisible child ends up above
|
||||
+ // the application's own widgets in the sibling z-order, and a
|
||||
+ // wxTRANSPARENT_WINDOW (WS_EX_TRANSPARENT) is transparent to painting only,
|
||||
+ // not to hit-testing, so it silently swallowed every click and key press
|
||||
+ // aimed at the real UI. On GTK later siblings stack above it, so it is kept.
|
||||
+#ifdef __WXMSW__
|
||||
+ inputWin = NULL;
|
||||
+#else
|
||||
inputWin = new wxWindow(this, wxID_ANY,
|
||||
wxDefaultPosition,
|
||||
wxSize(-1, -1),
|
||||
wxBORDER_NONE | wxTRANSPARENT_WINDOW);
|
||||
+#endif
|
||||
|
||||
InitCursors();
|
||||
Show(true);
|
||||
@@ -344,12 +370,43 @@
|
||||
int fake_argc = 0;
|
||||
char *fake_argv[1] = {NULL};
|
||||
wxEntryStart(fake_argc, fake_argv);
|
||||
+ // alkane-toolkit patch: light/dark appearance, decided before the first
|
||||
+ // window exists because wxMSW cannot switch it afterwards (SetAppearance
|
||||
+ // then returns CannotChange). System follows the desktop: the GTK theme's
|
||||
+ // colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
|
||||
+ // otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
|
||||
+ {
|
||||
+ wxString pref;
|
||||
+ wxGetEnv("ALKANE_APPEARANCE", &pref);
|
||||
+ pref.MakeLower();
|
||||
+ wxApp::Appearance appearance = wxApp::Appearance::System;
|
||||
+ if (pref == "dark") appearance = wxApp::Appearance::Dark;
|
||||
+ else if (pref == "light") appearance = wxApp::Appearance::Light;
|
||||
+#ifdef __WXMSW__
|
||||
+ // Same as SetAppearance(), but with our dark palette tweak (below).
|
||||
+ if (appearance != wxApp::Appearance::Light) {
|
||||
+ wxTheApp->MSWEnableDarkMode(appearance == wxApp::Appearance::Dark
|
||||
+ ? wxApp::DarkMode_Always
|
||||
+ : wxApp::DarkMode_Auto,
|
||||
+ new DarkModeSettings()); // wx takes ownership
|
||||
+ }
|
||||
+#else
|
||||
+ wxTheApp->SetAppearance(appearance);
|
||||
+#endif
|
||||
+ }
|
||||
wxTheApp->OnInit();
|
||||
|
||||
#ifdef __WINDOWS__
|
||||
// Adjust the window according to the display scale factor
|
||||
double scale = wxGetApp().frame->GetDPIScaleFactor();
|
||||
wxGetApp().frame->SetSize(width * scale, height * scale);
|
||||
+ // alkane-toolkit patch: title-bar/Alt-Tab icon from the executable's own
|
||||
+ // icon resource. By wx convention the application icon group is named
|
||||
+ // "aaaa" (first alphabetically, so Explorer shows it too); an executable
|
||||
+ // without one keeps the default rather than showing a load-error dialog.
|
||||
+ if (::FindResourceW(::GetModuleHandleW(NULL), L"aaaa", MAKEINTRESOURCEW(14) /* RT_GROUP_ICON */)) {
|
||||
+ wxGetApp().frame->SetIcons(wxIconBundle(wxS("aaaa"), ::GetModuleHandleW(NULL)));
|
||||
+ }
|
||||
#else
|
||||
// OSX
|
||||
double scale = wxGetApp().frame->GetDPIScaleFactor();
|
||||
@@ -358,6 +415,24 @@
|
||||
wxGetApp().frame->Move(0.0, 20.0);
|
||||
}
|
||||
#endif
|
||||
+ // alkane-toolkit patch: never open larger than the monitor's work area
|
||||
+ // (the screen minus taskbar/panels). A 1280x800 request on a 1280x800 or
|
||||
+ // 1366x768 laptop otherwise put the bottom of the window, with the status
|
||||
+ // bar, behind the Windows taskbar.
|
||||
+ {
|
||||
+ wxFrame* frame = wxGetApp().frame;
|
||||
+ int index = wxDisplay::GetFromWindow(frame);
|
||||
+ wxRect work = wxDisplay(index == wxNOT_FOUND ? 0u : (unsigned)index).GetClientArea();
|
||||
+ wxRect rect = frame->GetRect();
|
||||
+ if (rect.width > work.width || rect.height > work.height) {
|
||||
+ rect.SetSize(wxSize(std::min(rect.width, work.width), std::min(rect.height, work.height)));
|
||||
+ frame->SetSize(rect.GetSize());
|
||||
+ }
|
||||
+ if (!work.Contains(frame->GetRect())) {
|
||||
+ frame->Move(work.x + (work.width - rect.width) / 2,
|
||||
+ work.y + (work.height - rect.height) / 2);
|
||||
+ }
|
||||
+ }
|
||||
}
|
||||
|
||||
void set_render(void (*render)()) {
|
||||
@@ -602,15 +677,21 @@
|
||||
}
|
||||
}
|
||||
|
||||
+ // alkane-toolkit patch: Rust hands UTF-8; upstream cast `help` to wxChar*,
|
||||
+ // which is wchar_t* on MSW (garbage text), and fell off the end of a
|
||||
+ // non-void function when `i` was out of range (undefined behaviour).
|
||||
int insert_to_menu(wxMenu* menu, size_t i, char* str, char* help) {
|
||||
if (i <= menu->GetMenuItemCount()) {
|
||||
- return menu->Insert(i, wxID_ANY, str, (help != NULL) ? (const wxChar *) help : wxEmptyString)->GetId();
|
||||
+ return menu->Insert(i, wxID_ANY, wxString::FromUTF8(str),
|
||||
+ help ? wxString::FromUTF8(help) : wxString())->GetId();
|
||||
}
|
||||
+ return -1;
|
||||
}
|
||||
|
||||
void insert_submenu(wxMenu* menu, size_t i, wxMenu* subMenu, char* str, char* help) {
|
||||
if (i <= menu->GetMenuItemCount()) {
|
||||
- menu->Insert(i, wxID_ANY, str, subMenu, (help != NULL) ? (const wxChar *) help : wxEmptyString);
|
||||
+ menu->Insert(i, wxID_ANY, wxString::FromUTF8(str), subMenu,
|
||||
+ help ? wxString::FromUTF8(help) : wxString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
Subject: [PATCH 0008] widget bridge: wxMSW support (generic data-view input and tooltips, DIP size boundary, anti-aliased shapes, themed selection colours)
|
||||
|
||||
--- a/cpp_src/widgets_bridge.cpp
|
||||
+++ b/cpp_src/widgets_bridge.cpp
|
||||
@@ -36,7 +36,13 @@
|
||||
#include <cstdio>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
+#include <memory>
|
||||
#include <vector>
|
||||
+#ifdef __WXMSW__
|
||||
+// Themed list-view colours, to draw selected rows the way the native renderer does.
|
||||
+#include <wx/msw/uxtheme.h>
|
||||
+#include <vssym32.h>
|
||||
+#endif
|
||||
#ifdef __WXGTK__
|
||||
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
|
||||
// enable and which cannot be done via wx mouse events on GTK (the native widget
|
||||
@@ -48,8 +54,9 @@
|
||||
static WxWidgetEventFn g_widget_event = nullptr;
|
||||
|
||||
#ifndef __WXGTK__
|
||||
-// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
|
||||
-// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
|
||||
+// Anchor row per data-view control for the wx-mouse-event rubber-band selection
|
||||
+// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
|
||||
+// uses native GtkTreeView rubber-banding instead).
|
||||
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
|
||||
#endif
|
||||
|
||||
@@ -72,6 +79,26 @@
|
||||
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
|
||||
};
|
||||
|
||||
+// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
|
||||
+// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
|
||||
+// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
|
||||
+// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
|
||||
+// aware wxMSW works in physical pixels, where a 180 px column must become
|
||||
+// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
|
||||
+// like) pass through untouched.
|
||||
+static wxWindow* DipWindow(wxWindow* win) {
|
||||
+ if (win) return win;
|
||||
+ return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
|
||||
+}
|
||||
+static int PxFromDip(wxWindow* win, int dip) {
|
||||
+ wxWindow* w = DipWindow(win);
|
||||
+ return (w && dip > 0) ? w->FromDIP(dip) : dip;
|
||||
+}
|
||||
+static int DipFromPx(wxWindow* win, int px) {
|
||||
+ wxWindow* w = DipWindow(win);
|
||||
+ return (w && px > 0) ? w->ToDIP(px) : px;
|
||||
+}
|
||||
+
|
||||
// A list store that carries an optional per-row foreground colour plus an
|
||||
// alternating-row (zebra) background, surfaced to the native control via
|
||||
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
|
||||
@@ -196,6 +223,20 @@
|
||||
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
|
||||
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
|
||||
|
||||
+// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
|
||||
+// in DPI-independent logical pixels, so FromDIP() is the identity there and
|
||||
+// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
|
||||
+// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
|
||||
+// size as the (already scaled) text beside it.
|
||||
+static double DipFactor() {
|
||||
+ return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
|
||||
+}
|
||||
+static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
|
||||
+// Space one vector shape occupies, at the current display density.
|
||||
+static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
|
||||
+// Icon size factor: the table zoom (round 14 #3) times the display density.
|
||||
+static double ShapeScale() { return g_table_zoom * DipFactor(); }
|
||||
+
|
||||
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
|
||||
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
|
||||
// the timer can invalidate exactly it.
|
||||
@@ -313,7 +354,7 @@
|
||||
// health icons are square, so the advance is (h - 3) just like a real one.
|
||||
if (shape == SHAPE_GAP) {
|
||||
int h = cell.height - 1;
|
||||
- int cap = (int)(28 * g_table_zoom + 0.5);
|
||||
+ int cap = (int)(28 * ShapeScale() + 0.5);
|
||||
if (cap < 8) cap = 8;
|
||||
if (h > cap) h = cap;
|
||||
if (h < 8) h = 8;
|
||||
@@ -329,7 +370,7 @@
|
||||
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
|
||||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
|
||||
int h = cell.height - (health ? 1 : 4);
|
||||
- int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5);
|
||||
+ int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
|
||||
if (cap < 8) cap = 8;
|
||||
if (h > cap) h = cap;
|
||||
if (h < 8) h = 8;
|
||||
@@ -362,25 +403,37 @@
|
||||
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
|
||||
return adv;
|
||||
}
|
||||
- int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
|
||||
+ int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
|
||||
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
- int cx = x + SHAPE_ADVANCE / 2;
|
||||
+#ifdef __WXMSW__
|
||||
+ // GDI does not anti-alias, so the dots and the padlock came out jagged next
|
||||
+ // to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
|
||||
+ // Cairo already does on GTK; the context inherits the DC's origin, scale and
|
||||
+ // clip (the same approach wx's own generic markup renderer takes).
|
||||
+ std::unique_ptr<wxGCDC> smooth;
|
||||
+ if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
|
||||
+ smooth.reset(new wxGCDC(gc));
|
||||
+ dc = smooth.get();
|
||||
+ }
|
||||
+#endif
|
||||
+ const int adv = ShapeAdvance();
|
||||
+ int cx = x + adv / 2;
|
||||
if (shape == SHAPE_LIGHT_BEACON) {
|
||||
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
|
||||
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
|
||||
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
|
||||
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
|
||||
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
|
||||
- int r = 3;
|
||||
+ int r = Dip(3);
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(green));
|
||||
dc->DrawCircle(cx, cy - (r + 1), r);
|
||||
dc->SetBrush(wxBrush(red));
|
||||
dc->DrawCircle(cx, cy + (r + 1), r);
|
||||
- return SHAPE_ADVANCE;
|
||||
+ return adv;
|
||||
}
|
||||
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
|
||||
wxColour fill = colour;
|
||||
@@ -391,21 +444,21 @@
|
||||
}
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(fill));
|
||||
- dc->DrawCircle(cx, cy, 4);
|
||||
- return SHAPE_ADVANCE;
|
||||
+ dc->DrawCircle(cx, cy, Dip(4));
|
||||
+ return adv;
|
||||
}
|
||||
// Padlock: a filled body with a staple shackle above. The colour carries the
|
||||
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
|
||||
bool open = (shape == SHAPE_UNLOCK);
|
||||
- int bw = 9, bh = 7;
|
||||
+ int bw = Dip(9), bh = Dip(7);
|
||||
int bx = cx - bw / 2;
|
||||
int by = cy - bh / 2 + 1;
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(colour));
|
||||
- dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5);
|
||||
+ dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
|
||||
dc->SetBrush(*wxTRANSPARENT_BRUSH);
|
||||
- dc->SetPen(wxPen(colour, 2));
|
||||
- int sr = 3;
|
||||
+ dc->SetPen(wxPen(colour, Dip(2)));
|
||||
+ int sr = Dip(3);
|
||||
int legTop = by - sr - 1;
|
||||
int lx = cx - sr, rx = cx + sr;
|
||||
dc->DrawLine(lx, by, lx, legTop); // left leg
|
||||
@@ -414,11 +467,45 @@
|
||||
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
|
||||
else
|
||||
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
|
||||
- return SHAPE_ADVANCE;
|
||||
+ return adv;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
+// True when selected rows keep their own background under a light, translucent
|
||||
+// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
|
||||
+// rather than a solid highlight colour.
|
||||
+static bool SelectionIsTranslucent(wxWindow* win) {
|
||||
+#ifdef __WXMSW__
|
||||
+ if (win && wxUxThemeIsActive()) {
|
||||
+ wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
|
||||
+ return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
|
||||
+ }
|
||||
+#else
|
||||
+ (void)win;
|
||||
+#endif
|
||||
+ return false;
|
||||
+}
|
||||
+
|
||||
+// Text colour for a selected row, matching the platform's native data-view text
|
||||
+// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
|
||||
+// selection: a light translucent highlight under the normal dark text, taken
|
||||
+// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
|
||||
+// styles off / high contrast -- the selection is a solid highlight, so the text
|
||||
+// switches to the system highlight-text colour.
|
||||
+static wxColour SelectedTextColour(wxWindow* win) {
|
||||
+#ifdef __WXMSW__
|
||||
+ if (SelectionIsTranslucent(win)) {
|
||||
+ wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
|
||||
+ wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
|
||||
+ if (c.IsOk()) return c;
|
||||
+ }
|
||||
+#else
|
||||
+ (void)win;
|
||||
+#endif
|
||||
+ return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
|
||||
+}
|
||||
+
|
||||
class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
public:
|
||||
SegmentRenderer()
|
||||
@@ -467,7 +554,9 @@
|
||||
bg.height += 80;
|
||||
dc->DrawRectangle(bg);
|
||||
}
|
||||
- wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
|
||||
+ wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
|
||||
+ wxColour highlight =
|
||||
+ SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
|
||||
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
|
||||
// firmware family, etc. -- must dim exactly like the native columns when the
|
||||
// top-level window is backdropped. wxGTK dims a native cell's text via the
|
||||
@@ -503,7 +592,7 @@
|
||||
if (IsShapeSentinel(seg.text, shape)) {
|
||||
// Background the shape sits on, so the pulsing locate dot fades toward it.
|
||||
wxColour cellbg;
|
||||
- if (selected) {
|
||||
+ if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
@@ -530,11 +619,11 @@
|
||||
if (IsShapeSentinel(seg.text, shape)) {
|
||||
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
|
||||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
|
||||
- int adv = SHAPE_ADVANCE;
|
||||
+ int adv = ShapeAdvance();
|
||||
// Health icons measure bigger and pack tighter, and report a taller
|
||||
// content height so the row grows to fit them (round 14 #1). Sizes scale
|
||||
// with the table zoom (round 14 #3).
|
||||
- int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5);
|
||||
+ int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
|
||||
if (hh < 8) hh = 8;
|
||||
// The alignment gap is one health-icon-width slot that draws nothing
|
||||
// (round 15 #5); health icons are square, so its advance is hh - 3.
|
||||
@@ -646,7 +735,7 @@
|
||||
if (flags & 16) f |= wxBOTTOM;
|
||||
if (flags & 32) f |= wxLEFT;
|
||||
if (flags & 64) f |= wxRIGHT;
|
||||
- ((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, border);
|
||||
+ ((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
|
||||
}
|
||||
|
||||
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
|
||||
@@ -658,11 +747,12 @@
|
||||
if (flags & 16) f |= wxBOTTOM;
|
||||
if (flags & 32) f |= wxLEFT;
|
||||
if (flags & 64) f |= wxRIGHT;
|
||||
- ((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f, border);
|
||||
+ ((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
|
||||
+ PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
|
||||
}
|
||||
|
||||
void wxbr_sizer_add_spacer(void* sizer, int px) {
|
||||
- ((wxSizer*)sizer)->AddSpacer(px);
|
||||
+ ((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
|
||||
}
|
||||
|
||||
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
|
||||
@@ -694,9 +784,11 @@
|
||||
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
|
||||
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
|
||||
void wxbr_bind_size(void* win) {
|
||||
- ((wxWindow*)win)->Bind(wxEVT_SIZE, [](wxSizeEvent& e) {
|
||||
- if (g_widget_event) g_widget_event(WxEV_SIZE, (long)e.GetSize().GetWidth(),
|
||||
- (long)e.GetSize().GetHeight());
|
||||
+ wxWindow* w = (wxWindow*)win;
|
||||
+ w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
|
||||
+ if (g_widget_event)
|
||||
+ g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
|
||||
+ (long)DipFromPx(w, e.GetSize().GetHeight()));
|
||||
e.Skip();
|
||||
});
|
||||
}
|
||||
@@ -704,7 +796,8 @@
|
||||
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
|
||||
|
||||
void wxbr_set_min_size(void* win, int w, int h) {
|
||||
- ((wxWindow*)win)->SetMinSize(wxSize(w, h));
|
||||
+ wxWindow* window = (wxWindow*)win;
|
||||
+ window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
|
||||
}
|
||||
|
||||
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
|
||||
@@ -902,7 +995,8 @@
|
||||
void* wxbr_dialog(void* parent, const char* title) {
|
||||
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
|
||||
wxString::FromUTF8(title), wxDefaultPosition,
|
||||
- wxSize(360, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
|
||||
+ DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
|
||||
+ wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
|
||||
}
|
||||
|
||||
int wxbr_dialog_show_modal(void* win) {
|
||||
@@ -957,6 +1051,96 @@
|
||||
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
|
||||
}
|
||||
|
||||
+// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
|
||||
+// the GTK and generic tooltip paths so both pick the same icon. The slot advance
|
||||
+// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
|
||||
+// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
|
||||
+// column (round 19 #21) draws the icon block flush to the cell's right edge, so
|
||||
+// slots are measured from the block's left, not the cell's left.
|
||||
+struct IconSlots {
|
||||
+ int left; // x of the first slot, in the same coordinates as the cell
|
||||
+ int adv; // width of one slot
|
||||
+};
|
||||
+
|
||||
+static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
|
||||
+ bool right_aligned) {
|
||||
+ int h = cell_h - 1;
|
||||
+ int cap = (int)(28 * ShapeScale() + 0.5);
|
||||
+ if (cap < 8) cap = 8;
|
||||
+ if (h > cap) h = cap;
|
||||
+ if (h < 8) h = 8;
|
||||
+ int adv = h - 3;
|
||||
+ if (adv < 1) adv = 1;
|
||||
+ int left = cell_x;
|
||||
+ if (right_aligned) {
|
||||
+ int content_w = n * adv;
|
||||
+ if (content_w < cell_w) left = cell_x + (cell_w - content_w);
|
||||
+ }
|
||||
+ return IconSlots{left, adv};
|
||||
+}
|
||||
+
|
||||
+static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
|
||||
+ int off = x - slots.left;
|
||||
+ if (off < 0) off = 0;
|
||||
+ int slot = off / slots.adv;
|
||||
+ if (slot >= n) slot = n - 1;
|
||||
+ return slot < 0 ? 0 : slot;
|
||||
+}
|
||||
+
|
||||
+#ifndef __WXGTK__
|
||||
+// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
|
||||
+// The control draws its rows in an inner main window, which is where mouse
|
||||
+// events arrive, so the tooltip lives on that window. Windows only re-shows a
|
||||
+// tooltip when its text is re-set, so the handler tracks the (row, column,
|
||||
+// icon slot) under the pointer and replaces the tooltip only when it changes;
|
||||
+// moving from one Health icon to the next therefore pops the right text.
|
||||
+struct DvTipKey {
|
||||
+ int row = -1;
|
||||
+ unsigned col = (unsigned)-1;
|
||||
+ int slot = -1;
|
||||
+ bool operator==(const DvTipKey& o) const {
|
||||
+ return row == o.row && col == o.col && slot == o.slot;
|
||||
+ }
|
||||
+};
|
||||
+static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
|
||||
+
|
||||
+// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
|
||||
+// in src/generic/datavgen.cpp); custom renderers draw inside it.
|
||||
+static const int GENERIC_CELL_PADDING = 3;
|
||||
+
|
||||
+static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
|
||||
+ const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
|
||||
+ wxDataViewItem item;
|
||||
+ wxDataViewColumn* col = nullptr;
|
||||
+ dv->HitTest(p, item, col);
|
||||
+ DvTipKey key;
|
||||
+ wxString tip;
|
||||
+ if (item.IsOk() && col) {
|
||||
+ AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
|
||||
+ key.row = (int)store->GetRow(item);
|
||||
+ key.col = col->GetModelColumn();
|
||||
+ auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
|
||||
+ if (iit != store->icon_tip.end() && !iit->second.empty()) {
|
||||
+ wxRect r = dv->GetItemRect(item, col);
|
||||
+ int pad = dv->FromDIP(GENERIC_CELL_PADDING);
|
||||
+ int n = (int)iit->second.size();
|
||||
+ IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
|
||||
+ col->GetAlignment() == wxALIGN_RIGHT);
|
||||
+ key.slot = HealthIconSlotAt(slots, p.x, n);
|
||||
+ tip = iit->second[(size_t)key.slot];
|
||||
+ } else {
|
||||
+ auto it = store->cell_tip.find({(unsigned)key.row, key.col});
|
||||
+ if (it != store->cell_tip.end()) tip = it->second;
|
||||
+ }
|
||||
+ }
|
||||
+ DvTipKey& last = g_tip_key[dv];
|
||||
+ if (last == key) return;
|
||||
+ last = key;
|
||||
+ area->UnsetToolTip();
|
||||
+ if (!tip.IsEmpty()) area->SetToolTip(tip);
|
||||
+}
|
||||
+#endif
|
||||
+
|
||||
#ifdef __WXGTK__
|
||||
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
|
||||
// (row, model column) under the pointer (used by the Errors column). wx does
|
||||
@@ -987,31 +1171,12 @@
|
||||
GdkRectangle crect;
|
||||
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
|
||||
gtk_tree_path_free(path);
|
||||
- // Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
|
||||
- // (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
|
||||
- // earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
|
||||
- // the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
|
||||
- int h = crect.height - 1;
|
||||
- int cap = (int)(28 * g_table_zoom + 0.5);
|
||||
- if (cap < 8) cap = 8;
|
||||
- if (h > cap) h = cap;
|
||||
- if (h < 8) h = 8;
|
||||
- int adv = h - 3;
|
||||
- if (adv < 1) adv = 1;
|
||||
int n = (int)iit->second.size();
|
||||
- // A right-aligned column (round 19 #21) draws the icon block flush to the
|
||||
- // cell's right edge, so measure the pointer from the block's left, not the
|
||||
- // cell's left.
|
||||
- int block_left = crect.x;
|
||||
- if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
|
||||
- int content_w = n * adv;
|
||||
- if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
|
||||
- }
|
||||
- int off = bx - block_left;
|
||||
- if (off < 0) off = 0;
|
||||
- int slot = off / adv;
|
||||
- if (slot < 0) slot = 0;
|
||||
- if (slot >= n) slot = n - 1;
|
||||
+ IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
|
||||
+ wxcol->GetAlignment() == wxALIGN_RIGHT);
|
||||
+ int slot = HealthIconSlotAt(slots, bx, n);
|
||||
+ int adv = slots.adv;
|
||||
+ int block_left = slots.left;
|
||||
const wxString& tip = iit->second[(size_t)slot];
|
||||
if (tip.IsEmpty()) return FALSE;
|
||||
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
|
||||
@@ -1103,49 +1268,61 @@
|
||||
}
|
||||
}
|
||||
#else
|
||||
- // Non-GTK fallback: track a drag anchor and extend the selection to the row
|
||||
- // under the cursor. LEFT_DOWN records the anchor (and lets the native handler
|
||||
- // select it); dragging with the button down selects the inclusive range.
|
||||
- dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
|
||||
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||
- if (!dv) { e.Skip(); return; }
|
||||
- // Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
|
||||
- if (e.ControlDown() || e.ShiftDown()) { g_drag_anchor.erase(dv); e.Skip(); return; }
|
||||
- wxDataViewItem item;
|
||||
- wxDataViewColumn* col = nullptr;
|
||||
- dv->HitTest(e.GetPosition(), item, col);
|
||||
- if (item.IsOk()) {
|
||||
- g_drag_anchor[dv] =
|
||||
- (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
|
||||
- } else {
|
||||
+ // Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
|
||||
+ // anchor and extend the selection to the row under the cursor. The generic
|
||||
+ // control draws and receives mouse input in an inner "main window", not in
|
||||
+ // the wxDataViewCtrl itself (mouse events do not propagate to parents), so
|
||||
+ // the handlers bind there; HitTest wants control coordinates.
|
||||
+ {
|
||||
+ wxWindow* area = dv->GetMainWindow();
|
||||
+ auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
|
||||
+ wxDataViewItem item;
|
||||
+ wxDataViewColumn* col = nullptr;
|
||||
+ dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
|
||||
+ if (!item.IsOk()) return false;
|
||||
+ row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
|
||||
+ return true;
|
||||
+ };
|
||||
+ area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
|
||||
+ // Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
|
||||
+ int row = -1;
|
||||
+ if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
|
||||
+ g_drag_anchor[dv] = row;
|
||||
+ } else {
|
||||
+ g_drag_anchor.erase(dv);
|
||||
+ }
|
||||
+ e.Skip(); // let the control select the anchor row
|
||||
+ });
|
||||
+ area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
|
||||
+ e.Skip();
|
||||
+ dvlc_update_tooltip(dv, area, e.GetPosition());
|
||||
+ auto it = g_drag_anchor.find(dv);
|
||||
+ int cur = -1;
|
||||
+ if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
|
||||
+ return;
|
||||
+ int lo = it->second < cur ? it->second : cur;
|
||||
+ int hi = it->second < cur ? cur : it->second;
|
||||
+ wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
+ wxDataViewItemArray sel;
|
||||
+ for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
|
||||
+ dv->SetSelections(sel);
|
||||
+ // Selecting programmatically does not emit SELECTION_CHANGED, so notify.
|
||||
+ if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
|
||||
+ });
|
||||
+ area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
|
||||
g_drag_anchor.erase(dv);
|
||||
- }
|
||||
- e.Skip(); // let the native handler select the anchor row
|
||||
- });
|
||||
- dv->Bind(wxEVT_MOTION, [](wxMouseEvent& e) {
|
||||
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||
- if (!dv || !e.LeftIsDown()) { e.Skip(); return; }
|
||||
- auto it = g_drag_anchor.find(dv);
|
||||
- if (it == g_drag_anchor.end()) { e.Skip(); return; }
|
||||
- wxDataViewItem item;
|
||||
- wxDataViewColumn* col = nullptr;
|
||||
- dv->HitTest(e.GetPosition(), item, col);
|
||||
- if (!item.IsOk()) { e.Skip(); return; }
|
||||
- wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
- int cur = (int)model->GetRow(item);
|
||||
- int lo = it->second < cur ? it->second : cur;
|
||||
- int hi = it->second < cur ? cur : it->second;
|
||||
- dv->UnselectAll();
|
||||
- for (int r = lo; r <= hi; ++r) dv->Select(model->GetItem((unsigned)r));
|
||||
- // Selecting programmatically does not emit SELECTION_CHANGED, so notify.
|
||||
- if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
|
||||
- e.Skip();
|
||||
- });
|
||||
- dv->Bind(wxEVT_LEFT_UP, [](wxMouseEvent& e) {
|
||||
- wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||
- if (dv) g_drag_anchor.erase(dv);
|
||||
- e.Skip();
|
||||
- });
|
||||
+ e.Skip();
|
||||
+ });
|
||||
+ area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
|
||||
+ g_tip_key.erase(dv);
|
||||
+ e.Skip();
|
||||
+ });
|
||||
+ dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
|
||||
+ g_drag_anchor.erase(dv);
|
||||
+ g_tip_key.erase(dv);
|
||||
+ e.Skip();
|
||||
+ });
|
||||
+ }
|
||||
#endif
|
||||
// Row activation (double-click / Enter): report the row + column so the app
|
||||
// can, e.g., open the miner's IP in a browser.
|
||||
@@ -1177,6 +1354,7 @@
|
||||
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
|
||||
unsigned col = dv->GetColumnCount(); // next model column index
|
||||
dvlc_store(win)->AppendColumn("string");
|
||||
+ width = PxFromDip(dv, width);
|
||||
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
|
||||
width, dvlc_wx_align(align), flags);
|
||||
// Record the 100% column width for the zoom (round 14 #3); the first column of
|
||||
@@ -1196,6 +1374,7 @@
|
||||
unsigned col = dv->GetColumnCount(); // next model column index
|
||||
dvlc_store(win)->AppendColumn("string");
|
||||
SegmentRenderer* renderer = new SegmentRenderer();
|
||||
+ width = PxFromDip(dv, width);
|
||||
wxAlignment al = dvlc_wx_align(align);
|
||||
renderer->SetAlignment(al);
|
||||
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
|
||||
@@ -1211,7 +1390,7 @@
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
unsigned col = dv->GetColumnCount();
|
||||
dvlc_store(win)->AppendColumn("bool");
|
||||
- dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
|
||||
+ dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
|
||||
wxALIGN_CENTRE, 0);
|
||||
}
|
||||
|
||||
@@ -1356,7 +1535,8 @@
|
||||
if (!c) return;
|
||||
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
|
||||
int w = c->GetWidth();
|
||||
- const int floor_px = 24;
|
||||
+ cap_px = PxFromDip(dv, cap_px);
|
||||
+ const int floor_px = PxFromDip(dv, 24);
|
||||
if (w < floor_px) w = floor_px;
|
||||
if (cap_px > 0 && w > cap_px) w = cap_px;
|
||||
c->SetWidth(w);
|
||||
@@ -1483,7 +1663,7 @@
|
||||
|
||||
void* wxbr_gauge(void* parent, int range) {
|
||||
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
|
||||
- wxDefaultPosition, wxSize(-1, 6),
|
||||
+ wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
|
||||
wxGA_HORIZONTAL | wxGA_SMOOTH);
|
||||
return (void*)g;
|
||||
}
|
||||
@@ -1510,11 +1690,10 @@
|
||||
|
||||
// ---- appearance / dark mode -------------------------------------------------
|
||||
|
||||
-void wxbr_set_appearance_system() {
|
||||
-#if wxCHECK_VERSION(3, 3, 0)
|
||||
- if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System);
|
||||
-#endif
|
||||
-}
|
||||
+// init_app() now sets the appearance before the frame exists (the only point
|
||||
+// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
|
||||
+// kept for API compatibility and does nothing further.
|
||||
+void wxbr_set_appearance_system() {}
|
||||
|
||||
int wxbr_is_dark() {
|
||||
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
|
||||
@@ -1658,7 +1837,8 @@
|
||||
|
||||
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
|
||||
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
|
||||
- wxSize(-1, 240), wxLC_REPORT | wxLC_NO_HEADER);
|
||||
+ wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
|
||||
+ wxLC_REPORT | wxLC_NO_HEADER);
|
||||
lc->EnableCheckBoxes(true);
|
||||
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
|
||||
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
|
||||
@@ -1874,7 +2054,9 @@
|
||||
// given colour on a transparent bitmap so it reads as a coloured glyph on the
|
||||
// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
|
||||
void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
|
||||
- const int sz = 20;
|
||||
+ // The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
|
||||
+ const int sz = PxFromDip((wxWindow*)parent, 20);
|
||||
+ const double scale = sz / 20.0;
|
||||
wxImage img(sz, sz);
|
||||
img.InitAlpha();
|
||||
unsigned char* a = img.GetAlpha();
|
||||
@@ -1885,6 +2067,7 @@
|
||||
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
|
||||
if (gc) {
|
||||
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
|
||||
+ gc->Scale(scale, scale);
|
||||
wxColour col(r, g, b);
|
||||
gc->SetBrush(wxBrush(col));
|
||||
gc->SetPen(wxPen(col, 1.0));
|
||||
@@ -1915,9 +2098,10 @@
|
||||
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
|
||||
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
|
||||
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
|
||||
+ // A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
|
||||
+ // rasterised for the window's actual display scale.
|
||||
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
|
||||
- wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
|
||||
- return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
|
||||
+ return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
|
||||
}
|
||||
|
||||
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
|
||||
@@ -1990,7 +2174,7 @@
|
||||
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
|
||||
wxRect r;
|
||||
if (sb->GetFieldRect(fld, r)) {
|
||||
- int ew = 52;
|
||||
+ int ew = PxFromDip(sb, 52);
|
||||
int eh = g_zoom_entry->GetBestSize().GetHeight();
|
||||
if (eh > r.height - 2) eh = r.height - 2;
|
||||
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
|
||||
@@ -2039,7 +2223,7 @@
|
||||
wxFrame* frame = (wxFrame*)frame_ptr;
|
||||
wxStatusBar* sb = frame->GetStatusBar();
|
||||
if (!sb) sb = frame->CreateStatusBar();
|
||||
- int widths[2] = { -1, 340 };
|
||||
+ int widths[2] = { -1, PxFromDip(frame, 340) };
|
||||
sb->SetFieldsCount(2);
|
||||
sb->SetStatusWidths(2, widths);
|
||||
if (!g_status_indicator) {
|
||||
@@ -2072,12 +2256,12 @@
|
||||
wxFrame* frame = (wxFrame*)frame_ptr;
|
||||
wxStatusBar* sb = frame->GetStatusBar();
|
||||
if (!sb) sb = frame->CreateStatusBar();
|
||||
- int widths[3] = { -1, 240, 190 };
|
||||
+ int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
|
||||
sb->SetFieldsCount(3);
|
||||
sb->SetStatusWidths(3, widths);
|
||||
// A native slider needs more vertical room than a default status bar gives, so
|
||||
// grow the bar to fit it (round 14 #3).
|
||||
- sb->SetMinHeight(30);
|
||||
+ sb->SetMinHeight(PxFromDip(frame, 30));
|
||||
if (!g_zoom_slider) {
|
||||
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
|
||||
g_zoom_slider->SetToolTip(wxT("Table zoom"));
|
||||
--- a/src/widgets.rs
|
||||
+++ b/src/widgets.rs
|
||||
@@ -260,7 +260,8 @@
|
||||
unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 }
|
||||
}
|
||||
|
||||
-/// Ask wx to follow the system light/dark appearance (no-op before 3.3).
|
||||
+/// Kept for API compatibility: `init_app` already follows the system light/dark
|
||||
+/// appearance (or `ALKANE_APPEARANCE=light|dark`), before any window exists.
|
||||
pub fn set_appearance_system() {
|
||||
unsafe { notsafe::wxbr_set_appearance_system() }
|
||||
}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# wx-rs patch queue
|
||||
|
||||
`../wx-rs-0.2.0-patched/` is the tree cargo builds. These patches, applied in
|
||||
order to the pristine crate in `../upstream/` (digest pinned in `../VERSION`),
|
||||
must reproduce it byte for byte; CI checks this with
|
||||
`scripts/wx_rs_patches.py check`.
|
||||
|
||||
To change the bridge: edit the patched tree, build and test, then record the
|
||||
change as the next patch and commit both:
|
||||
|
||||
```sh
|
||||
python3 scripts/wx_rs_patches.py capture short-name "One-line subject" [PATH ...]
|
||||
```
|
||||
|
||||
`capture` limits the patch to the given paths (default: everything that
|
||||
differs) and re-runs the check. `0002` and `0003` create the widget bridge
|
||||
files outright, so they carry those files as of the queue's re-baselining;
|
||||
later changes go in new patches.
|
||||
|
||||
| Patch | What |
|
||||
|-------|------|
|
||||
| 0001 | Linux/GTK3 build through `wx-config` |
|
||||
| 0002 | Widget/event bridge, Rust side (`src/widgets.rs`) |
|
||||
| 0003 | Widget/event bridge, C++ side (`cpp_src/widgets_bridge.cpp`) |
|
||||
| 0004 | Upstream fixes for wx 3.3 (uninitialised callbacks) |
|
||||
| 0005 | Packaging: build-only `reqwest` note; drop the case-duplicate `readme.md` |
|
||||
| 0006 | Build: platform from the target, not the host; Windows/GNU via `wx-config` |
|
||||
| 0007 | `wxbridge.cpp` on wxMSW: no input-swallowing overlay, appearance before the first window, work-area sizing, executable icon, UTF-8 menu fix |
|
||||
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
|
||||
|
||||
History: the round 19 health-tooltip fix (GTK tip area converted from
|
||||
bin-window to widget coordinates) used to be a separate patch on top of an
|
||||
older 0003; it is part of 0003 since the re-baselining.
|
||||
+78
-31
@@ -12,22 +12,42 @@ const WX_PATH: &str = "wxWidgets-3.2.2.1";
|
||||
const WX_SOURCE: &str =
|
||||
"https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.2.1/wxWidgets-3.2.2.1.tar.bz2";
|
||||
|
||||
// alkane-toolkit patch: decide the platform from the TARGET. A build script is
|
||||
// compiled for and runs on the build host, so `cfg!(windows)` etc. here describe
|
||||
// the host -- which made a Linux -> Windows cross build take the GTK path.
|
||||
// Cargo exposes the real target through CARGO_CFG_TARGET_* instead.
|
||||
fn target_os() -> String {
|
||||
env::var("CARGO_CFG_TARGET_OS").unwrap_or_default()
|
||||
}
|
||||
|
||||
fn target_env() -> String {
|
||||
env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default()
|
||||
}
|
||||
|
||||
fn is_windows() -> bool {
|
||||
cfg!(windows)
|
||||
target_os() == "windows"
|
||||
}
|
||||
|
||||
fn is_msvc() -> bool {
|
||||
cfg!(target_env = "msvc")
|
||||
is_windows() && target_env() == "msvc"
|
||||
}
|
||||
|
||||
fn is_osx() -> bool {
|
||||
cfg!(target_os = "macos")
|
||||
target_os() == "macos"
|
||||
}
|
||||
|
||||
// alkane-toolkit patch: real wxGTK3 support on Linux via wx-config
|
||||
// (upstream stubbed every non-Windows/macOS target).
|
||||
fn is_linux() -> bool {
|
||||
cfg!(target_os = "linux")
|
||||
target_os() == "linux"
|
||||
}
|
||||
|
||||
// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
|
||||
// mingw-w64, natively or cross from Linux) both build against a wx prefix
|
||||
// described by its wx-config script, so they share one code path. Upstream's
|
||||
// MSVC/nmake and macOS download-and-build paths are left as they were.
|
||||
fn uses_wx_config() -> bool {
|
||||
is_linux() || (is_windows() && !is_msvc())
|
||||
}
|
||||
|
||||
fn is_stub() -> bool {
|
||||
@@ -41,8 +61,8 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
if is_stub() {
|
||||
return Ok(());
|
||||
}
|
||||
if is_linux() {
|
||||
return Ok(()); // libs are linked inside build_linux()
|
||||
if uses_wx_config() {
|
||||
return Ok(()); // libs are linked inside build_with_wx_config()
|
||||
}
|
||||
|
||||
let wx_libs = get_libs(&wx_path)?;
|
||||
@@ -89,7 +109,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
fn download_dist() -> Result<PathBuf, Box<dyn Error>> {
|
||||
let dist_path = Path::new("./dist/");
|
||||
let wx_path = PathBuf::from(format!("./dist/{}", WX_PATH));
|
||||
if wx_path.exists() || is_stub() || is_linux() {
|
||||
if wx_path.exists() || is_stub() || uses_wx_config() {
|
||||
return Ok(wx_path);
|
||||
}
|
||||
println!("cargo:warning=wx-rs: Downloading source to './dist/");
|
||||
@@ -120,8 +140,8 @@ fn build_bridge_lib(wx_path: &Path) -> Result<(), Box<dyn Error>> {
|
||||
|
||||
// alkane-toolkit patch: compile the bridge (upstream + widgets extension)
|
||||
// against the wx shown by $WX_RS_WXCONFIG (default `wx-config`).
|
||||
if is_linux() {
|
||||
return build_linux();
|
||||
if uses_wx_config() {
|
||||
return build_with_wx_config();
|
||||
}
|
||||
|
||||
if is_windows() {
|
||||
@@ -232,25 +252,27 @@ fn osx_libs(wx_path: &Path) -> Result<String, Box<dyn Error>> {
|
||||
)?)
|
||||
}
|
||||
|
||||
fn build_linux() -> Result<(), Box<dyn Error>> {
|
||||
// alkane-toolkit patch: GTK3 build driven entirely by wx-config, so the
|
||||
// same code builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG
|
||||
// pointing at its prefix) or any system wxGTK3.
|
||||
fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
|
||||
// alkane-toolkit patch: build driven entirely by wx-config, so the same code
|
||||
// builds against our vendored static wx 3.3.3 (WX_RS_WXCONFIG pointing at its
|
||||
// GTK or mingw prefix) or any system wx. wx-config is a POSIX shell script;
|
||||
// cross builds run it on the Linux host, native mingw builds under MSYS2.
|
||||
println!("cargo:rerun-if-env-changed=WX_RS_WXCONFIG");
|
||||
let wxconfig = env::var("WX_RS_WXCONFIG").unwrap_or_else(|_| String::from("wx-config"));
|
||||
let cxxflags = String::from_utf8(
|
||||
Command::new(&wxconfig).arg("--cxxflags").output()?.stdout,
|
||||
)?;
|
||||
let libs = String::from_utf8(Command::new(&wxconfig).arg("--libs").output()?.stdout)?;
|
||||
// The widget bridge uses GTK directly (zebra-striping CSS), so add GTK's own
|
||||
// include paths. Best-effort: if pkg-config or gtk3-dev is missing the flags
|
||||
// are simply empty and the GTK-only code stays disabled.
|
||||
let gtk_cflags = Command::new("pkg-config")
|
||||
.args(["--cflags", "gtk+-3.0"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.unwrap_or_default();
|
||||
let wx_config = |arg: &str| -> Result<String, Box<dyn Error>> {
|
||||
let out = Command::new(&wxconfig).arg(arg).output().map_err(|e| {
|
||||
format!("wx-rs: cannot run {wxconfig} {arg} (set WX_RS_WXCONFIG): {e}")
|
||||
})?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("wx-rs: {wxconfig} {arg} failed").into());
|
||||
}
|
||||
Ok(String::from_utf8(out.stdout)?)
|
||||
};
|
||||
let cxxflags = wx_config("--cxxflags")?;
|
||||
let libs = wx_config("--libs")?;
|
||||
if is_windows() && !cxxflags.contains("__WXMSW__") {
|
||||
return Err(format!("wx-rs: {wxconfig} is not a wxMSW build").into());
|
||||
}
|
||||
|
||||
let mut build = cc::Build::new();
|
||||
build.cpp(true)
|
||||
@@ -259,15 +281,37 @@ fn build_linux() -> Result<(), Box<dyn Error>> {
|
||||
for f in cxxflags.split_whitespace() {
|
||||
build.flag(f);
|
||||
}
|
||||
for f in gtk_cflags.split_whitespace() {
|
||||
build.flag(f);
|
||||
if is_linux() {
|
||||
// The widget bridge uses GTK directly (native rubber-band selection,
|
||||
// tooltips, themed colours), so add GTK's own include paths.
|
||||
// Best-effort: if pkg-config or gtk3-dev is missing the flags are simply
|
||||
// empty and the GTK-only code stays disabled.
|
||||
let gtk_cflags = Command::new("pkg-config")
|
||||
.args(["--cflags", "gtk+-3.0"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.unwrap_or_default();
|
||||
for f in gtk_cflags.split_whitespace() {
|
||||
build.flag(f);
|
||||
}
|
||||
}
|
||||
if is_windows() {
|
||||
// Ship one self-contained .exe: link the C++ runtime statically rather
|
||||
// than depending on the toolchain's libstdc++-6.dll/libgcc_s_seh-1.dll/
|
||||
// libwinpthread-1.dll, which no Windows machine has. `-bundle` hands the
|
||||
// archives to the final link instead of copying them into this rlib.
|
||||
build.cpp_link_stdlib(None);
|
||||
println!("cargo:rustc-link-lib=static:-bundle=stdc++");
|
||||
println!("cargo:rustc-link-lib=static:-bundle=winpthread");
|
||||
}
|
||||
build.compile("wxbridge");
|
||||
|
||||
for flag in libs.split_whitespace() {
|
||||
if flag.starts_with('/') && flag.ends_with(".a") {
|
||||
if flag.ends_with(".a") && Path::new(flag).is_absolute() {
|
||||
// static wx builds: wx-config emits the archive as a full path
|
||||
let file = flag.rsplit('/').next().unwrap_or(flag);
|
||||
let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
|
||||
let stem = file
|
||||
.strip_prefix("lib")
|
||||
.unwrap_or(file)
|
||||
@@ -281,6 +325,9 @@ fn build_linux() -> Result<(), Box<dyn Error>> {
|
||||
} else if flag == "-pthread" {
|
||||
println!("cargo:rustc-link-arg=-pthread");
|
||||
}
|
||||
// `-mwindows` / `-Wl,--subsystem,windows` are deliberately dropped: the
|
||||
// console-vs-GUI subsystem is the application's decision
|
||||
// (`#![windows_subsystem]`), not the GUI library's.
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+293
-109
@@ -36,7 +36,13 @@
|
||||
#include <cstdio>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#ifdef __WXMSW__
|
||||
// Themed list-view colours, to draw selected rows the way the native renderer does.
|
||||
#include <wx/msw/uxtheme.h>
|
||||
#include <vssym32.h>
|
||||
#endif
|
||||
#ifdef __WXGTK__
|
||||
// For native GtkTreeView rubber-band (click-drag) selection, which wx does not
|
||||
// enable and which cannot be done via wx mouse events on GTK (the native widget
|
||||
@@ -48,8 +54,9 @@ typedef void (*WxWidgetEventFn)(int kind, long p1, long p2);
|
||||
static WxWidgetEventFn g_widget_event = nullptr;
|
||||
|
||||
#ifndef __WXGTK__
|
||||
// Anchor row per data-view control for the wx-mouse-event rubber-band fallback
|
||||
// (non-GTK platforms; GTK uses native GtkTreeView rubber-banding instead).
|
||||
// Anchor row per data-view control for the wx-mouse-event rubber-band selection
|
||||
// used with the generic wxDataViewCtrl (wxMSW and any other non-GTK port; GTK
|
||||
// uses native GtkTreeView rubber-banding instead).
|
||||
static std::map<wxDataViewCtrl*, int> g_drag_anchor;
|
||||
#endif
|
||||
|
||||
@@ -72,6 +79,26 @@ enum WxWidgetEventKind {
|
||||
WxEV_SIZE = 16, // p1 = new client width, p2 = new client height
|
||||
};
|
||||
|
||||
// Sizes cross the Rust <-> C++ boundary in DIPs (device-independent pixels,
|
||||
// 1/96 inch: the size at 100 % display scale). The bridge converts them for the
|
||||
// window they apply to. wxGTK and wxOSX lay out in logical pixels already, so
|
||||
// FromDIP/ToDIP are the identity there and nothing changes; per-monitor-DPI-
|
||||
// aware wxMSW works in physical pixels, where a 180 px column must become
|
||||
// 270 px at 150 % or text clips. Non-positive values (wxDefaultCoord and the
|
||||
// like) pass through untouched.
|
||||
static wxWindow* DipWindow(wxWindow* win) {
|
||||
if (win) return win;
|
||||
return wxTheApp ? wxTheApp->GetTopWindow() : nullptr;
|
||||
}
|
||||
static int PxFromDip(wxWindow* win, int dip) {
|
||||
wxWindow* w = DipWindow(win);
|
||||
return (w && dip > 0) ? w->FromDIP(dip) : dip;
|
||||
}
|
||||
static int DipFromPx(wxWindow* win, int px) {
|
||||
wxWindow* w = DipWindow(win);
|
||||
return (w && px > 0) ? w->ToDIP(px) : px;
|
||||
}
|
||||
|
||||
// A list store that carries an optional per-row foreground colour plus an
|
||||
// alternating-row (zebra) background, surfaced to the native control via
|
||||
// GetAttrByRow. The zebra background is set on odd rows only; because it is a
|
||||
@@ -196,6 +223,20 @@ static wxVector<int> g_zoom_base_w; // column widths at 100% (per co
|
||||
static wxSlider* g_zoom_slider = nullptr; // the status-bar zoom slider
|
||||
static wxTextCtrl* g_zoom_entry = nullptr; // the editable "100%" field next to it
|
||||
|
||||
// Display density for the custom-drawn shapes and icons. wxGTK and wxOSX draw
|
||||
// in DPI-independent logical pixels, so FromDIP() is the identity there and
|
||||
// these change nothing. Per-monitor-DPI-aware wxMSW draws in physical pixels,
|
||||
// so a 15 px shape slot has to become 23 px at 150 % to keep the same physical
|
||||
// size as the (already scaled) text beside it.
|
||||
static double DipFactor() {
|
||||
return g_zoom_table ? g_zoom_table->FromDIP(1000) / 1000.0 : 1.0;
|
||||
}
|
||||
static int Dip(int px) { return (int)(px * DipFactor() + 0.5); }
|
||||
// Space one vector shape occupies, at the current display density.
|
||||
static int ShapeAdvance() { return Dip(SHAPE_ADVANCE); }
|
||||
// Icon size factor: the table zoom (round 14 #3) times the display density.
|
||||
static double ShapeScale() { return g_table_zoom * DipFactor(); }
|
||||
|
||||
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
|
||||
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
|
||||
// the timer can invalidate exactly it.
|
||||
@@ -313,7 +354,7 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
// health icons are square, so the advance is (h - 3) just like a real one.
|
||||
if (shape == SHAPE_GAP) {
|
||||
int h = cell.height - 1;
|
||||
int cap = (int)(28 * g_table_zoom + 0.5);
|
||||
int cap = (int)(28 * ShapeScale() + 0.5);
|
||||
if (cap < 8) cap = 8;
|
||||
if (h > cap) h = cap;
|
||||
if (h < 8) h = 8;
|
||||
@@ -329,7 +370,7 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
|
||||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
|
||||
int h = cell.height - (health ? 1 : 4);
|
||||
int cap = (int)((health ? 28 : 15) * g_table_zoom + 0.5);
|
||||
int cap = (int)((health ? 28 : 15) * ShapeScale() + 0.5);
|
||||
if (cap < 8) cap = 8;
|
||||
if (h > cap) h = cap;
|
||||
if (h < 8) h = 8;
|
||||
@@ -362,25 +403,37 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
dc->DrawBitmap(bmp, x + (adv - dw) / 2, cy - dh / 2, true);
|
||||
return adv;
|
||||
}
|
||||
int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
|
||||
int slot = (w > ShapeAdvance()) ? w : ShapeAdvance();
|
||||
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
int cx = x + SHAPE_ADVANCE / 2;
|
||||
#ifdef __WXMSW__
|
||||
// GDI does not anti-alias, so the dots and the padlock came out jagged next
|
||||
// to the smooth SVG icons. Draw the vector shapes through GDI+ instead, as
|
||||
// Cairo already does on GTK; the context inherits the DC's origin, scale and
|
||||
// clip (the same approach wx's own generic markup renderer takes).
|
||||
std::unique_ptr<wxGCDC> smooth;
|
||||
if (wxGraphicsContext* gc = wxGraphicsContext::CreateFromUnknownDC(*dc)) {
|
||||
smooth.reset(new wxGCDC(gc));
|
||||
dc = smooth.get();
|
||||
}
|
||||
#endif
|
||||
const int adv = ShapeAdvance();
|
||||
int cx = x + adv / 2;
|
||||
if (shape == SHAPE_LIGHT_BEACON) {
|
||||
// A green dot above a red dot, both flashing quickly (round 15 #6). The blink
|
||||
// is a fast on/off (~0.5 s) driven by the shared pulse phase.
|
||||
double a = (std::sin(g_pulse_phase * 3.0) > 0.0) ? 1.0 : 0.18;
|
||||
wxColour green = BlendColour(bg, wxColour(30, 175, 70), a);
|
||||
wxColour red = BlendColour(bg, wxColour(215, 45, 40), a);
|
||||
int r = 3;
|
||||
int r = Dip(3);
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(green));
|
||||
dc->DrawCircle(cx, cy - (r + 1), r);
|
||||
dc->SetBrush(wxBrush(red));
|
||||
dc->DrawCircle(cx, cy + (r + 1), r);
|
||||
return SHAPE_ADVANCE;
|
||||
return adv;
|
||||
}
|
||||
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
|
||||
wxColour fill = colour;
|
||||
@@ -391,21 +444,21 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
}
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(fill));
|
||||
dc->DrawCircle(cx, cy, 4);
|
||||
return SHAPE_ADVANCE;
|
||||
dc->DrawCircle(cx, cy, Dip(4));
|
||||
return adv;
|
||||
}
|
||||
// Padlock: a filled body with a staple shackle above. The colour carries the
|
||||
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
|
||||
bool open = (shape == SHAPE_UNLOCK);
|
||||
int bw = 9, bh = 7;
|
||||
int bw = Dip(9), bh = Dip(7);
|
||||
int bx = cx - bw / 2;
|
||||
int by = cy - bh / 2 + 1;
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(colour));
|
||||
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5);
|
||||
dc->DrawRoundedRectangle(bx, by, bw, bh, 1.5 * DipFactor());
|
||||
dc->SetBrush(*wxTRANSPARENT_BRUSH);
|
||||
dc->SetPen(wxPen(colour, 2));
|
||||
int sr = 3;
|
||||
dc->SetPen(wxPen(colour, Dip(2)));
|
||||
int sr = Dip(3);
|
||||
int legTop = by - sr - 1;
|
||||
int lx = cx - sr, rx = cx + sr;
|
||||
dc->DrawLine(lx, by, lx, legTop); // left leg
|
||||
@@ -414,11 +467,45 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
|
||||
else
|
||||
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
|
||||
return SHAPE_ADVANCE;
|
||||
return adv;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// True when selected rows keep their own background under a light, translucent
|
||||
// highlight (the Explorer list-view style of Windows 10/11 with visual styles)
|
||||
// rather than a solid highlight colour.
|
||||
static bool SelectionIsTranslucent(wxWindow* win) {
|
||||
#ifdef __WXMSW__
|
||||
if (win && wxUxThemeIsActive()) {
|
||||
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
|
||||
return ::IsThemePartDefined(theme, LVP_LISTITEM, 0) != 0;
|
||||
}
|
||||
#else
|
||||
(void)win;
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
// Text colour for a selected row, matching the platform's native data-view text
|
||||
// renderer. Windows 10/11 (visual styles on) draw the Explorer list-view
|
||||
// selection: a light translucent highlight under the normal dark text, taken
|
||||
// from the theme (dark-mode aware). Elsewhere -- GTK, or Windows with visual
|
||||
// styles off / high contrast -- the selection is a solid highlight, so the text
|
||||
// switches to the system highlight-text colour.
|
||||
static wxColour SelectedTextColour(wxWindow* win) {
|
||||
#ifdef __WXMSW__
|
||||
if (SelectionIsTranslucent(win)) {
|
||||
wxUxThemeHandle theme(win, L"EXPLORER::LISTVIEW;LISTVIEW", L"DarkMode_ItemsView::LISTVIEW");
|
||||
wxColour c = theme.GetColour(LVP_LISTITEM, TMT_TEXTCOLOR, LISS_SELECTED);
|
||||
if (c.IsOk()) return c;
|
||||
}
|
||||
#else
|
||||
(void)win;
|
||||
#endif
|
||||
return wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
|
||||
}
|
||||
|
||||
class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
public:
|
||||
SegmentRenderer()
|
||||
@@ -467,7 +554,9 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
bg.height += 80;
|
||||
dc->DrawRectangle(bg);
|
||||
}
|
||||
wxColour highlight = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
|
||||
wxDataViewColumn* owner_col = const_cast<SegmentRenderer*>(this)->GetOwner();
|
||||
wxColour highlight =
|
||||
SelectedTextColour(owner_col ? owner_col->GetOwner() : nullptr);
|
||||
// An uncoloured (default) segment -- the "/" in a combined cell, a "Stock"
|
||||
// firmware family, etc. -- must dim exactly like the native columns when the
|
||||
// top-level window is backdropped. wxGTK dims a native cell's text via the
|
||||
@@ -503,7 +592,7 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
if (IsShapeSentinel(seg.text, shape)) {
|
||||
// Background the shape sits on, so the pulsing locate dot fades toward it.
|
||||
wxColour cellbg;
|
||||
if (selected) {
|
||||
if (selected && !SelectionIsTranslucent(owner_col ? owner_col->GetOwner() : nullptr)) {
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
@@ -530,11 +619,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
if (IsShapeSentinel(seg.text, shape)) {
|
||||
bool health = (shape == SHAPE_BOLT || shape == SHAPE_BRAIN ||
|
||||
shape == SHAPE_FAN || shape == SHAPE_CHIP);
|
||||
int adv = SHAPE_ADVANCE;
|
||||
int adv = ShapeAdvance();
|
||||
// Health icons measure bigger and pack tighter, and report a taller
|
||||
// content height so the row grows to fit them (round 14 #1). Sizes scale
|
||||
// with the table zoom (round 14 #3).
|
||||
int hh = (int)((health ? 22 : 15) * g_table_zoom + 0.5);
|
||||
int hh = (int)((health ? 22 : 15) * ShapeScale() + 0.5);
|
||||
if (hh < 8) hh = 8;
|
||||
// The alignment gap is one health-icon-width slot that draws nothing
|
||||
// (round 15 #5); health icons are square, so its advance is hh - 3.
|
||||
@@ -646,7 +735,7 @@ void wxbr_sizer_add(void* sizer, void* win, int proportion, int flags, int borde
|
||||
if (flags & 16) f |= wxBOTTOM;
|
||||
if (flags & 32) f |= wxLEFT;
|
||||
if (flags & 64) f |= wxRIGHT;
|
||||
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, border);
|
||||
((wxSizer*)sizer)->Add((wxWindow*)win, proportion, f, PxFromDip((wxWindow*)win, border));
|
||||
}
|
||||
|
||||
void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags, int border) {
|
||||
@@ -658,11 +747,12 @@ void wxbr_sizer_add_sizer(void* sizer, void* subsizer, int proportion, int flags
|
||||
if (flags & 16) f |= wxBOTTOM;
|
||||
if (flags & 32) f |= wxLEFT;
|
||||
if (flags & 64) f |= wxRIGHT;
|
||||
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f, border);
|
||||
((wxSizer*)sizer)->Add((wxSizer*)subsizer, proportion, f,
|
||||
PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), border));
|
||||
}
|
||||
|
||||
void wxbr_sizer_add_spacer(void* sizer, int px) {
|
||||
((wxSizer*)sizer)->AddSpacer(px);
|
||||
((wxSizer*)sizer)->AddSpacer(PxFromDip(((wxSizer*)sizer)->GetContainingWindow(), px));
|
||||
}
|
||||
|
||||
void wxbr_sizer_add_stretch(void* sizer, int proportion) {
|
||||
@@ -694,9 +784,11 @@ void wxbr_sizer_show(void* sizer, void* win, int show) {
|
||||
// Emit WxEV_SIZE (p1 = new client width, p2 = height) whenever this window is
|
||||
// resized. e.Skip() keeps the normal sizer layout running (round 11 #2).
|
||||
void wxbr_bind_size(void* win) {
|
||||
((wxWindow*)win)->Bind(wxEVT_SIZE, [](wxSizeEvent& e) {
|
||||
if (g_widget_event) g_widget_event(WxEV_SIZE, (long)e.GetSize().GetWidth(),
|
||||
(long)e.GetSize().GetHeight());
|
||||
wxWindow* w = (wxWindow*)win;
|
||||
w->Bind(wxEVT_SIZE, [w](wxSizeEvent& e) {
|
||||
if (g_widget_event)
|
||||
g_widget_event(WxEV_SIZE, (long)DipFromPx(w, e.GetSize().GetWidth()),
|
||||
(long)DipFromPx(w, e.GetSize().GetHeight()));
|
||||
e.Skip();
|
||||
});
|
||||
}
|
||||
@@ -704,7 +796,8 @@ void wxbr_bind_size(void* win) {
|
||||
void wxbr_fit(void* win) { ((wxWindow*)win)->Fit(); }
|
||||
|
||||
void wxbr_set_min_size(void* win, int w, int h) {
|
||||
((wxWindow*)win)->SetMinSize(wxSize(w, h));
|
||||
wxWindow* window = (wxWindow*)win;
|
||||
window->SetMinSize(wxSize(PxFromDip(window, w), PxFromDip(window, h)));
|
||||
}
|
||||
|
||||
// Attach a hover tooltip to any widget (round 15 #10). An empty string clears it.
|
||||
@@ -902,7 +995,8 @@ int wxbr_clb_string(void* win, int i, char* buf, int cap) {
|
||||
void* wxbr_dialog(void* parent, const char* title) {
|
||||
return (void*)new wxDialog((wxWindow*)parent, wxID_ANY,
|
||||
wxString::FromUTF8(title), wxDefaultPosition,
|
||||
wxSize(360, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
|
||||
DipWindow((wxWindow*)parent)->FromDIP(wxSize(360, 480)),
|
||||
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
|
||||
}
|
||||
|
||||
int wxbr_dialog_show_modal(void* win) {
|
||||
@@ -957,6 +1051,96 @@ static AttrListStore* dvlc_store(void* win) {
|
||||
return static_cast<AttrListStore*>(((wxDataViewCtrl*)win)->GetModel());
|
||||
}
|
||||
|
||||
// Per-icon tooltip hit-testing for a Health-style cell (round 15 #15), shared by
|
||||
// the GTK and generic tooltip paths so both pick the same icon. The slot advance
|
||||
// must match DrawShape's UNIFORM health-icon slot: (row height - 1, capped at
|
||||
// 28*zoom) - 3 for every glyph and gap alike (round 19 #2). A right-aligned
|
||||
// column (round 19 #21) draws the icon block flush to the cell's right edge, so
|
||||
// slots are measured from the block's left, not the cell's left.
|
||||
struct IconSlots {
|
||||
int left; // x of the first slot, in the same coordinates as the cell
|
||||
int adv; // width of one slot
|
||||
};
|
||||
|
||||
static IconSlots HealthIconSlots(int cell_x, int cell_w, int cell_h, int n,
|
||||
bool right_aligned) {
|
||||
int h = cell_h - 1;
|
||||
int cap = (int)(28 * ShapeScale() + 0.5);
|
||||
if (cap < 8) cap = 8;
|
||||
if (h > cap) h = cap;
|
||||
if (h < 8) h = 8;
|
||||
int adv = h - 3;
|
||||
if (adv < 1) adv = 1;
|
||||
int left = cell_x;
|
||||
if (right_aligned) {
|
||||
int content_w = n * adv;
|
||||
if (content_w < cell_w) left = cell_x + (cell_w - content_w);
|
||||
}
|
||||
return IconSlots{left, adv};
|
||||
}
|
||||
|
||||
static int HealthIconSlotAt(const IconSlots& slots, int x, int n) {
|
||||
int off = x - slots.left;
|
||||
if (off < 0) off = 0;
|
||||
int slot = off / slots.adv;
|
||||
if (slot >= n) slot = n - 1;
|
||||
return slot < 0 ? 0 : slot;
|
||||
}
|
||||
|
||||
#ifndef __WXGTK__
|
||||
// Generic wxDataViewCtrl (wxMSW): per-cell and per-icon hover tooltips.
|
||||
// The control draws its rows in an inner main window, which is where mouse
|
||||
// events arrive, so the tooltip lives on that window. Windows only re-shows a
|
||||
// tooltip when its text is re-set, so the handler tracks the (row, column,
|
||||
// icon slot) under the pointer and replaces the tooltip only when it changes;
|
||||
// moving from one Health icon to the next therefore pops the right text.
|
||||
struct DvTipKey {
|
||||
int row = -1;
|
||||
unsigned col = (unsigned)-1;
|
||||
int slot = -1;
|
||||
bool operator==(const DvTipKey& o) const {
|
||||
return row == o.row && col == o.col && slot == o.slot;
|
||||
}
|
||||
};
|
||||
static std::map<wxDataViewCtrl*, DvTipKey> g_tip_key;
|
||||
|
||||
// Padding the generic renderer leaves on each side of a cell (PADDING_RIGHTLEFT
|
||||
// in src/generic/datavgen.cpp); custom renderers draw inside it.
|
||||
static const int GENERIC_CELL_PADDING = 3;
|
||||
|
||||
static void dvlc_update_tooltip(wxDataViewCtrl* dv, wxWindow* area, wxPoint area_pos) {
|
||||
const wxPoint p = dv->ScreenToClient(area->ClientToScreen(area_pos));
|
||||
wxDataViewItem item;
|
||||
wxDataViewColumn* col = nullptr;
|
||||
dv->HitTest(p, item, col);
|
||||
DvTipKey key;
|
||||
wxString tip;
|
||||
if (item.IsOk() && col) {
|
||||
AttrListStore* store = static_cast<AttrListStore*>(dv->GetModel());
|
||||
key.row = (int)store->GetRow(item);
|
||||
key.col = col->GetModelColumn();
|
||||
auto iit = store->icon_tip.find({(unsigned)key.row, key.col});
|
||||
if (iit != store->icon_tip.end() && !iit->second.empty()) {
|
||||
wxRect r = dv->GetItemRect(item, col);
|
||||
int pad = dv->FromDIP(GENERIC_CELL_PADDING);
|
||||
int n = (int)iit->second.size();
|
||||
IconSlots slots = HealthIconSlots(r.x + pad, r.width - 2 * pad, r.height, n,
|
||||
col->GetAlignment() == wxALIGN_RIGHT);
|
||||
key.slot = HealthIconSlotAt(slots, p.x, n);
|
||||
tip = iit->second[(size_t)key.slot];
|
||||
} else {
|
||||
auto it = store->cell_tip.find({(unsigned)key.row, key.col});
|
||||
if (it != store->cell_tip.end()) tip = it->second;
|
||||
}
|
||||
}
|
||||
DvTipKey& last = g_tip_key[dv];
|
||||
if (last == key) return;
|
||||
last = key;
|
||||
area->UnsetToolTip();
|
||||
if (!tip.IsEmpty()) area->SetToolTip(tip);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __WXGTK__
|
||||
// GtkTreeView "query-tooltip" handler: show the per-cell tooltip stored for the
|
||||
// (row, model column) under the pointer (used by the Errors column). wx does
|
||||
@@ -987,31 +1171,12 @@ static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keybo
|
||||
GdkRectangle crect;
|
||||
gtk_tree_view_get_cell_area(GTK_TREE_VIEW(tv), path, gcol, &crect);
|
||||
gtk_tree_path_free(path);
|
||||
// Icon advance must match DrawShape's now-UNIFORM health-icon slot, which is
|
||||
// (row height - 1, capped at 28*zoom) - 3 for every glyph and gap alike. The
|
||||
// earlier per-glyph advance (w-3) shifted the hit slots so tooltips landed on
|
||||
// the wrong icon (round 19 #2); with the uniform slot the hit-test lines up.
|
||||
int h = crect.height - 1;
|
||||
int cap = (int)(28 * g_table_zoom + 0.5);
|
||||
if (cap < 8) cap = 8;
|
||||
if (h > cap) h = cap;
|
||||
if (h < 8) h = 8;
|
||||
int adv = h - 3;
|
||||
if (adv < 1) adv = 1;
|
||||
int n = (int)iit->second.size();
|
||||
// A right-aligned column (round 19 #21) draws the icon block flush to the
|
||||
// cell's right edge, so measure the pointer from the block's left, not the
|
||||
// cell's left.
|
||||
int block_left = crect.x;
|
||||
if (wxcol->GetAlignment() == wxALIGN_RIGHT) {
|
||||
int content_w = n * adv;
|
||||
if (content_w < crect.width) block_left = crect.x + (crect.width - content_w);
|
||||
}
|
||||
int off = bx - block_left;
|
||||
if (off < 0) off = 0;
|
||||
int slot = off / adv;
|
||||
if (slot < 0) slot = 0;
|
||||
if (slot >= n) slot = n - 1;
|
||||
IconSlots slots = HealthIconSlots(crect.x, crect.width, crect.height, n,
|
||||
wxcol->GetAlignment() == wxALIGN_RIGHT);
|
||||
int slot = HealthIconSlotAt(slots, bx, n);
|
||||
int adv = slots.adv;
|
||||
int block_left = slots.left;
|
||||
const wxString& tip = iit->second[(size_t)slot];
|
||||
if (tip.IsEmpty()) return FALSE;
|
||||
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
|
||||
@@ -1103,49 +1268,61 @@ void* wxbr_dvlc(void* parent) {
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Non-GTK fallback: track a drag anchor and extend the selection to the row
|
||||
// under the cursor. LEFT_DOWN records the anchor (and lets the native handler
|
||||
// select it); dragging with the button down selects the inclusive range.
|
||||
dv->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& e) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||
if (!dv) { e.Skip(); return; }
|
||||
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
|
||||
if (e.ControlDown() || e.ShiftDown()) { g_drag_anchor.erase(dv); e.Skip(); return; }
|
||||
wxDataViewItem item;
|
||||
wxDataViewColumn* col = nullptr;
|
||||
dv->HitTest(e.GetPosition(), item, col);
|
||||
if (item.IsOk()) {
|
||||
g_drag_anchor[dv] =
|
||||
(int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
|
||||
} else {
|
||||
// Generic wxDataViewCtrl (wxMSW): no native rubber-banding, so track a drag
|
||||
// anchor and extend the selection to the row under the cursor. The generic
|
||||
// control draws and receives mouse input in an inner "main window", not in
|
||||
// the wxDataViewCtrl itself (mouse events do not propagate to parents), so
|
||||
// the handlers bind there; HitTest wants control coordinates.
|
||||
{
|
||||
wxWindow* area = dv->GetMainWindow();
|
||||
auto row_at = [dv, area](const wxPoint& area_pos, int& row) {
|
||||
wxDataViewItem item;
|
||||
wxDataViewColumn* col = nullptr;
|
||||
dv->HitTest(dv->ScreenToClient(area->ClientToScreen(area_pos)), item, col);
|
||||
if (!item.IsOk()) return false;
|
||||
row = (int)((wxDataViewIndexListModel*)dv->GetModel())->GetRow(item);
|
||||
return true;
|
||||
};
|
||||
area->Bind(wxEVT_LEFT_DOWN, [dv, row_at](wxMouseEvent& e) {
|
||||
// Leave modifier-clicks to the native ctrl/shift multi-select behaviour.
|
||||
int row = -1;
|
||||
if (!e.ControlDown() && !e.ShiftDown() && row_at(e.GetPosition(), row)) {
|
||||
g_drag_anchor[dv] = row;
|
||||
} else {
|
||||
g_drag_anchor.erase(dv);
|
||||
}
|
||||
e.Skip(); // let the control select the anchor row
|
||||
});
|
||||
area->Bind(wxEVT_MOTION, [dv, area, row_at](wxMouseEvent& e) {
|
||||
e.Skip();
|
||||
dvlc_update_tooltip(dv, area, e.GetPosition());
|
||||
auto it = g_drag_anchor.find(dv);
|
||||
int cur = -1;
|
||||
if (!e.LeftIsDown() || it == g_drag_anchor.end() || !row_at(e.GetPosition(), cur))
|
||||
return;
|
||||
int lo = it->second < cur ? it->second : cur;
|
||||
int hi = it->second < cur ? cur : it->second;
|
||||
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
wxDataViewItemArray sel;
|
||||
for (int r = lo; r <= hi; ++r) sel.push_back(model->GetItem((unsigned)r));
|
||||
dv->SetSelections(sel);
|
||||
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
|
||||
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
|
||||
});
|
||||
area->Bind(wxEVT_LEFT_UP, [dv](wxMouseEvent& e) {
|
||||
g_drag_anchor.erase(dv);
|
||||
}
|
||||
e.Skip(); // let the native handler select the anchor row
|
||||
});
|
||||
dv->Bind(wxEVT_MOTION, [](wxMouseEvent& e) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||
if (!dv || !e.LeftIsDown()) { e.Skip(); return; }
|
||||
auto it = g_drag_anchor.find(dv);
|
||||
if (it == g_drag_anchor.end()) { e.Skip(); return; }
|
||||
wxDataViewItem item;
|
||||
wxDataViewColumn* col = nullptr;
|
||||
dv->HitTest(e.GetPosition(), item, col);
|
||||
if (!item.IsOk()) { e.Skip(); return; }
|
||||
wxDataViewIndexListModel* model = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
int cur = (int)model->GetRow(item);
|
||||
int lo = it->second < cur ? it->second : cur;
|
||||
int hi = it->second < cur ? cur : it->second;
|
||||
dv->UnselectAll();
|
||||
for (int r = lo; r <= hi; ++r) dv->Select(model->GetItem((unsigned)r));
|
||||
// Selecting programmatically does not emit SELECTION_CHANGED, so notify.
|
||||
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
|
||||
e.Skip();
|
||||
});
|
||||
dv->Bind(wxEVT_LEFT_UP, [](wxMouseEvent& e) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)e.GetEventObject();
|
||||
if (dv) g_drag_anchor.erase(dv);
|
||||
e.Skip();
|
||||
});
|
||||
e.Skip();
|
||||
});
|
||||
area->Bind(wxEVT_LEAVE_WINDOW, [dv](wxMouseEvent& e) {
|
||||
g_tip_key.erase(dv);
|
||||
e.Skip();
|
||||
});
|
||||
dv->Bind(wxEVT_DESTROY, [dv](wxWindowDestroyEvent& e) {
|
||||
g_drag_anchor.erase(dv);
|
||||
g_tip_key.erase(dv);
|
||||
e.Skip();
|
||||
});
|
||||
}
|
||||
#endif
|
||||
// Row activation (double-click / Enter): report the row + column so the app
|
||||
// can, e.g., open the miner's IP in a browser.
|
||||
@@ -1177,6 +1354,7 @@ void wxbr_dvlc_append_text_col(void* win, const char* title, int width, int reor
|
||||
if (reorderable) flags |= wxDATAVIEW_COL_REORDERABLE;
|
||||
unsigned col = dv->GetColumnCount(); // next model column index
|
||||
dvlc_store(win)->AppendColumn("string");
|
||||
width = PxFromDip(dv, width);
|
||||
dv->AppendTextColumn(wxString::FromUTF8(title), col, wxDATAVIEW_CELL_INERT,
|
||||
width, dvlc_wx_align(align), flags);
|
||||
// Record the 100% column width for the zoom (round 14 #3); the first column of
|
||||
@@ -1196,6 +1374,7 @@ void* wxbr_dvlc_append_colored_col(void* win, const char* title, int width, int
|
||||
unsigned col = dv->GetColumnCount(); // next model column index
|
||||
dvlc_store(win)->AppendColumn("string");
|
||||
SegmentRenderer* renderer = new SegmentRenderer();
|
||||
width = PxFromDip(dv, width);
|
||||
wxAlignment al = dvlc_wx_align(align);
|
||||
renderer->SetAlignment(al);
|
||||
wxDataViewColumn* c = new wxDataViewColumn(wxString::FromUTF8(title), renderer, col,
|
||||
@@ -1211,7 +1390,7 @@ void wxbr_dvlc_append_toggle_col(void* win, int width) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
unsigned col = dv->GetColumnCount();
|
||||
dvlc_store(win)->AppendColumn("bool");
|
||||
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, width,
|
||||
dv->AppendToggleColumn(wxT(""), col, wxDATAVIEW_CELL_ACTIVATABLE, PxFromDip(dv, width),
|
||||
wxALIGN_CENTRE, 0);
|
||||
}
|
||||
|
||||
@@ -1356,7 +1535,8 @@ void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
|
||||
if (!c) return;
|
||||
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
|
||||
int w = c->GetWidth();
|
||||
const int floor_px = 24;
|
||||
cap_px = PxFromDip(dv, cap_px);
|
||||
const int floor_px = PxFromDip(dv, 24);
|
||||
if (w < floor_px) w = floor_px;
|
||||
if (cap_px > 0 && w > cap_px) w = cap_px;
|
||||
c->SetWidth(w);
|
||||
@@ -1483,7 +1663,7 @@ void* wxbr_timer(int id, int ms) {
|
||||
|
||||
void* wxbr_gauge(void* parent, int range) {
|
||||
wxGauge* g = new wxGauge((wxWindow*)parent, wxID_ANY, range < 1 ? 1 : range,
|
||||
wxDefaultPosition, wxSize(-1, 6),
|
||||
wxDefaultPosition, wxSize(-1, PxFromDip((wxWindow*)parent, 6)),
|
||||
wxGA_HORIZONTAL | wxGA_SMOOTH);
|
||||
return (void*)g;
|
||||
}
|
||||
@@ -1510,11 +1690,10 @@ int wxbr_launch_browser(const char* url) {
|
||||
|
||||
// ---- appearance / dark mode -------------------------------------------------
|
||||
|
||||
void wxbr_set_appearance_system() {
|
||||
#if wxCHECK_VERSION(3, 3, 0)
|
||||
if (wxTheApp) wxTheApp->SetAppearance(wxApp::Appearance::System);
|
||||
#endif
|
||||
}
|
||||
// init_app() now sets the appearance before the frame exists (the only point
|
||||
// at which wxMSW honours it, and where ALKANE_APPEARANCE is applied); this is
|
||||
// kept for API compatibility and does nothing further.
|
||||
void wxbr_set_appearance_system() {}
|
||||
|
||||
int wxbr_is_dark() {
|
||||
return wxSystemSettings::GetAppearance().IsDark() ? 1 : 0;
|
||||
@@ -1658,7 +1837,8 @@ static void ReorderMoveTo(wxListCtrl* lc, const wxPoint& pos) {
|
||||
|
||||
void* wxbr_reorder_list(void* parent, int n, const int* order, const char** items) {
|
||||
wxListCtrl* lc = new wxListCtrl((wxWindow*)parent, wxID_ANY, wxDefaultPosition,
|
||||
wxSize(-1, 240), wxLC_REPORT | wxLC_NO_HEADER);
|
||||
wxSize(-1, PxFromDip((wxWindow*)parent, 240)),
|
||||
wxLC_REPORT | wxLC_NO_HEADER);
|
||||
lc->EnableCheckBoxes(true);
|
||||
// Narrower than before so the picker dialog is not over-wide (round 13 #1).
|
||||
lc->InsertColumn(0, wxT("Column"), wxLIST_FORMAT_LEFT, 190);
|
||||
@@ -1874,7 +2054,9 @@ void wxbr_choice_set_selection(void* win, int i) {
|
||||
// given colour on a transparent bitmap so it reads as a coloured glyph on the
|
||||
// native button. Emits WxEV_BUTTON_CLICKED with `id`, like a normal button.
|
||||
void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
|
||||
const int sz = 20;
|
||||
// The glyph is designed on a 20x20 DIP grid and drawn at the display scale.
|
||||
const int sz = PxFromDip((wxWindow*)parent, 20);
|
||||
const double scale = sz / 20.0;
|
||||
wxImage img(sz, sz);
|
||||
img.InitAlpha();
|
||||
unsigned char* a = img.GetAlpha();
|
||||
@@ -1885,6 +2067,7 @@ void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
|
||||
wxGraphicsContext* gc = wxGraphicsContext::Create(mdc);
|
||||
if (gc) {
|
||||
gc->SetAntialiasMode(wxANTIALIAS_DEFAULT);
|
||||
gc->Scale(scale, scale);
|
||||
wxColour col(r, g, b);
|
||||
gc->SetBrush(wxBrush(col));
|
||||
gc->SetPen(wxPen(col, 1.0));
|
||||
@@ -1915,9 +2098,10 @@ void* wxbr_media_button(void* parent, int id, int kind, int r, int g, int b) {
|
||||
// #RRGGBB) into a wxStaticBitmap for the KPI cards (round 11 #15). The caller
|
||||
// passes the target pixel size (w chosen from the SVG aspect ratio, h fixed).
|
||||
void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
|
||||
// A bitmap bundle (w x h DIPs) rather than a fixed bitmap, so the icon is
|
||||
// rasterised for the window's actual display scale.
|
||||
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
|
||||
wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
|
||||
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
|
||||
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
|
||||
}
|
||||
|
||||
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
|
||||
@@ -1990,7 +2174,7 @@ static void reposition_status_indicator() {
|
||||
int fld = (sb->GetFieldsCount() >= 3) ? 2 : 1;
|
||||
wxRect r;
|
||||
if (sb->GetFieldRect(fld, r)) {
|
||||
int ew = 52;
|
||||
int ew = PxFromDip(sb, 52);
|
||||
int eh = g_zoom_entry->GetBestSize().GetHeight();
|
||||
if (eh > r.height - 2) eh = r.height - 2;
|
||||
g_zoom_entry->SetSize(r.x + r.width - ew - 2, r.y + (r.height - eh) / 2, ew, eh);
|
||||
@@ -2039,7 +2223,7 @@ void wxbr_status_indicator_init(void* frame_ptr) {
|
||||
wxFrame* frame = (wxFrame*)frame_ptr;
|
||||
wxStatusBar* sb = frame->GetStatusBar();
|
||||
if (!sb) sb = frame->CreateStatusBar();
|
||||
int widths[2] = { -1, 340 };
|
||||
int widths[2] = { -1, PxFromDip(frame, 340) };
|
||||
sb->SetFieldsCount(2);
|
||||
sb->SetStatusWidths(2, widths);
|
||||
if (!g_status_indicator) {
|
||||
@@ -2072,12 +2256,12 @@ void wxbr_status_zoom_init(void* frame_ptr) {
|
||||
wxFrame* frame = (wxFrame*)frame_ptr;
|
||||
wxStatusBar* sb = frame->GetStatusBar();
|
||||
if (!sb) sb = frame->CreateStatusBar();
|
||||
int widths[3] = { -1, 240, 190 };
|
||||
int widths[3] = { -1, PxFromDip(frame, 240), PxFromDip(frame, 190) };
|
||||
sb->SetFieldsCount(3);
|
||||
sb->SetStatusWidths(3, widths);
|
||||
// A native slider needs more vertical room than a default status bar gives, so
|
||||
// grow the bar to fit it (round 14 #3).
|
||||
sb->SetMinHeight(30);
|
||||
sb->SetMinHeight(PxFromDip(frame, 30));
|
||||
if (!g_zoom_slider) {
|
||||
g_zoom_slider = new wxSlider(sb, wxID_ANY, 100, 50, 250);
|
||||
g_zoom_slider->SetToolTip(wxT("Table zoom"));
|
||||
|
||||
+83
-2
@@ -1,5 +1,7 @@
|
||||
#include <wx/wx.h>
|
||||
#include "wx/clipbrd.h"
|
||||
#include "wx/display.h"
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(WIN64) || defined(WIN32) || defined(__MINGW32__) || defined(__MINGW64__)
|
||||
@@ -34,6 +36,21 @@ void setDPIAware() {
|
||||
void setDPIAware() {}
|
||||
#endif
|
||||
|
||||
#ifdef __WXMSW__
|
||||
#include <wx/msw/darkmode.h>
|
||||
// alkane-toolkit patch: wx's dark palette leaves wxSYS_COLOUR_3DLIGHT at its
|
||||
// light value, and the generic wxDataViewCtrl (the table on MSW) draws its row
|
||||
// and column rules in that colour -- bright grid lines across a dark table.
|
||||
// Give it a dark-grey rule colour; everything else stays wx's default palette.
|
||||
class DarkModeSettings : public wxDarkModeSettings {
|
||||
public:
|
||||
wxColour GetColour(wxSystemColour index) override {
|
||||
if (index == wxSYS_COLOUR_3DLIGHT) return wxColour(0x3a, 0x3a, 0x3a);
|
||||
return wxDarkModeSettings::GetColour(index);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
enum cursor {
|
||||
NO_CURSOR,
|
||||
ARROW_CURSOR,
|
||||
@@ -129,10 +146,19 @@ MyFrame::MyFrame(const wxString& title, const wxSize& size)
|
||||
render = NULL;
|
||||
handle_events = NULL;
|
||||
// Needed to get App to catch key events on OSX
|
||||
// alkane-toolkit patch: not on MSW. There this invisible child ends up above
|
||||
// the application's own widgets in the sibling z-order, and a
|
||||
// wxTRANSPARENT_WINDOW (WS_EX_TRANSPARENT) is transparent to painting only,
|
||||
// not to hit-testing, so it silently swallowed every click and key press
|
||||
// aimed at the real UI. On GTK later siblings stack above it, so it is kept.
|
||||
#ifdef __WXMSW__
|
||||
inputWin = NULL;
|
||||
#else
|
||||
inputWin = new wxWindow(this, wxID_ANY,
|
||||
wxDefaultPosition,
|
||||
wxSize(-1, -1),
|
||||
wxBORDER_NONE | wxTRANSPARENT_WINDOW);
|
||||
#endif
|
||||
|
||||
InitCursors();
|
||||
Show(true);
|
||||
@@ -344,12 +370,43 @@ extern "C" {
|
||||
int fake_argc = 0;
|
||||
char *fake_argv[1] = {NULL};
|
||||
wxEntryStart(fake_argc, fake_argv);
|
||||
// alkane-toolkit patch: light/dark appearance, decided before the first
|
||||
// window exists because wxMSW cannot switch it afterwards (SetAppearance
|
||||
// then returns CannotChange). System follows the desktop: the GTK theme's
|
||||
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
|
||||
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
|
||||
{
|
||||
wxString pref;
|
||||
wxGetEnv("ALKANE_APPEARANCE", &pref);
|
||||
pref.MakeLower();
|
||||
wxApp::Appearance appearance = wxApp::Appearance::System;
|
||||
if (pref == "dark") appearance = wxApp::Appearance::Dark;
|
||||
else if (pref == "light") appearance = wxApp::Appearance::Light;
|
||||
#ifdef __WXMSW__
|
||||
// Same as SetAppearance(), but with our dark palette tweak (below).
|
||||
if (appearance != wxApp::Appearance::Light) {
|
||||
wxTheApp->MSWEnableDarkMode(appearance == wxApp::Appearance::Dark
|
||||
? wxApp::DarkMode_Always
|
||||
: wxApp::DarkMode_Auto,
|
||||
new DarkModeSettings()); // wx takes ownership
|
||||
}
|
||||
#else
|
||||
wxTheApp->SetAppearance(appearance);
|
||||
#endif
|
||||
}
|
||||
wxTheApp->OnInit();
|
||||
|
||||
#ifdef __WINDOWS__
|
||||
// Adjust the window according to the display scale factor
|
||||
double scale = wxGetApp().frame->GetDPIScaleFactor();
|
||||
wxGetApp().frame->SetSize(width * scale, height * scale);
|
||||
// alkane-toolkit patch: title-bar/Alt-Tab icon from the executable's own
|
||||
// icon resource. By wx convention the application icon group is named
|
||||
// "aaaa" (first alphabetically, so Explorer shows it too); an executable
|
||||
// without one keeps the default rather than showing a load-error dialog.
|
||||
if (::FindResourceW(::GetModuleHandleW(NULL), L"aaaa", MAKEINTRESOURCEW(14) /* RT_GROUP_ICON */)) {
|
||||
wxGetApp().frame->SetIcons(wxIconBundle(wxS("aaaa"), ::GetModuleHandleW(NULL)));
|
||||
}
|
||||
#else
|
||||
// OSX
|
||||
double scale = wxGetApp().frame->GetDPIScaleFactor();
|
||||
@@ -358,6 +415,24 @@ extern "C" {
|
||||
wxGetApp().frame->Move(0.0, 20.0);
|
||||
}
|
||||
#endif
|
||||
// alkane-toolkit patch: never open larger than the monitor's work area
|
||||
// (the screen minus taskbar/panels). A 1280x800 request on a 1280x800 or
|
||||
// 1366x768 laptop otherwise put the bottom of the window, with the status
|
||||
// bar, behind the Windows taskbar.
|
||||
{
|
||||
wxFrame* frame = wxGetApp().frame;
|
||||
int index = wxDisplay::GetFromWindow(frame);
|
||||
wxRect work = wxDisplay(index == wxNOT_FOUND ? 0u : (unsigned)index).GetClientArea();
|
||||
wxRect rect = frame->GetRect();
|
||||
if (rect.width > work.width || rect.height > work.height) {
|
||||
rect.SetSize(wxSize(std::min(rect.width, work.width), std::min(rect.height, work.height)));
|
||||
frame->SetSize(rect.GetSize());
|
||||
}
|
||||
if (!work.Contains(frame->GetRect())) {
|
||||
frame->Move(work.x + (work.width - rect.width) / 2,
|
||||
work.y + (work.height - rect.height) / 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void set_render(void (*render)()) {
|
||||
@@ -602,15 +677,21 @@ extern "C" {
|
||||
}
|
||||
}
|
||||
|
||||
// alkane-toolkit patch: Rust hands UTF-8; upstream cast `help` to wxChar*,
|
||||
// which is wchar_t* on MSW (garbage text), and fell off the end of a
|
||||
// non-void function when `i` was out of range (undefined behaviour).
|
||||
int insert_to_menu(wxMenu* menu, size_t i, char* str, char* help) {
|
||||
if (i <= menu->GetMenuItemCount()) {
|
||||
return menu->Insert(i, wxID_ANY, str, (help != NULL) ? (const wxChar *) help : wxEmptyString)->GetId();
|
||||
return menu->Insert(i, wxID_ANY, wxString::FromUTF8(str),
|
||||
help ? wxString::FromUTF8(help) : wxString())->GetId();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void insert_submenu(wxMenu* menu, size_t i, wxMenu* subMenu, char* str, char* help) {
|
||||
if (i <= menu->GetMenuItemCount()) {
|
||||
menu->Insert(i, wxID_ANY, str, subMenu, (help != NULL) ? (const wxChar *) help : wxEmptyString);
|
||||
menu->Insert(i, wxID_ANY, wxString::FromUTF8(str), subMenu,
|
||||
help ? wxString::FromUTF8(help) : wxString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -260,7 +260,8 @@ pub fn launch_browser(url: &str) -> bool {
|
||||
unsafe { notsafe::wxbr_launch_browser(c.as_ptr()) != 0 }
|
||||
}
|
||||
|
||||
/// Ask wx to follow the system light/dark appearance (no-op before 3.3).
|
||||
/// Kept for API compatibility: `init_app` already follows the system light/dark
|
||||
/// appearance (or `ALKANE_APPEARANCE=light|dark`), before any window exists.
|
||||
pub fn set_appearance_system() {
|
||||
unsafe { notsafe::wxbr_set_appearance_system() }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user