Compare commits

...
2 Commits
Author SHA1 Message Date
faumaray ebf33b62dc Let the CI Python distribution locate its packaging interpreter
CI / check (push) Successful in 1m28s
CI / windows (push) Successful in 3m27s
Native release / linux (push) Successful in 1m29s
Native release / windows (push) Successful in 3m1s
Native release / publish (push) Successful in 9s
2026-11-27 23:43:54 +03:00
faumaray 3ea497d38a Ship a self-contained Windows GUI with game shortcuts and application icons
CI / check (push) Successful in 1m30s
CI / windows (push) Failing after 4m27s
2026-11-27 23:34:01 +03:00
17 changed files with 606 additions and 58 deletions

No files matched your search

+41 -2
View File
@@ -10,11 +10,12 @@ on:
permissions:
code: read
env:
RUSTUP_TOOLCHAIN: nightly-2026-11-24
jobs:
check:
runs-on: ubuntu-latest
env:
RUSTUP_TOOLCHAIN: nightly-2026-11-24
defaults:
run:
shell: bash
@@ -44,3 +45,41 @@ jobs:
- name: Test
run: cargo test --locked --features vendored-lua
windows:
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main'
runs-on: windows-x64
defaults:
run:
shell: powershell
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
with:
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
targets: x86_64-pc-windows-msvc
- name: Build and verify Windows packages
id: stage
run: |
$dist = Join-Path $env:RUNNER_TEMP ([IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Path $dist | Out-Null
[IO.File]::AppendAllText($env:GITHUB_OUTPUT, "dist=$dist" + [Environment]::NewLine)
& .\packaging\windows\build.ps1 -OutputDirectory $dist
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: windows-packages
path: ${{ steps.stage.outputs.dist }}/*
if-no-files-found: error
compression-level: 0
retention-days: 1
- name: Remove temporary packages
if: always() && steps.stage.outputs.dist != ''
env:
DIST: ${{ steps.stage.outputs.dist }}
run: Remove-Item -LiteralPath $env:DIST -Recurse -Force
+2 -29
View File
@@ -81,9 +81,7 @@ jobs:
overwrite: true
windows:
# Native x64 host: Git, Node 20, Windows PowerShell 5.1+, Python 3.11+,
# VS 2022 C++ x64 tools + SDK + vswhere, NASM, CMake, Perl, NSIS 3.
# Put Python/NASM/CMake/Perl on PATH; NSIS may use its standard path.
# Same MSVC build and packaged-executable checks as the Windows job on main.
runs-on: windows-x64
defaults:
run:
@@ -108,34 +106,9 @@ jobs:
id: stage
run: |
$ErrorActionPreference = 'Stop'
if (-not [Environment]::Is64BitOperatingSystem) { throw 'Windows x64 is required' }
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if ($LASTEXITCODE -ne 0 -or -not $vs) { throw 'Visual Studio C++ x64 tools not found' }
Import-Module (Join-Path $vs 'Common7\Tools\Microsoft.VisualStudio.DevShell.dll')
Enter-VsDevShell -VsInstallPath $vs -SkipAutomaticLocation -DevCmdArguments '-arch=x64 -host_arch=x64'
$nsis = Get-Command makensis.exe -ErrorAction SilentlyContinue
if (-not $nsis) {
$nsisDir = Join-Path ${env:ProgramFiles(x86)} 'NSIS'
if (-not (Test-Path (Join-Path $nsisDir 'makensis.exe'))) { throw 'NSIS 3 is required' }
$env:PATH = "$nsisDir;$env:PATH"
}
$nsisVersion = & makensis.exe /VERSION
if ($LASTEXITCODE -ne 0 -or $nsisVersion -notmatch '^v?3\.') { throw 'NSIS 3 is required' }
$dist = Join-Path $env:RUNNER_TEMP ('release-windows-' + [guid]::NewGuid())
$env:CARGO_TARGET_DIR = Join-Path $env:RUNNER_TEMP ('build-windows-' + [guid]::NewGuid())
New-Item -ItemType Directory -Path $dist | Out-Null
cargo build --locked --release --features vendored-lua
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$binary = Join-Path $env:CARGO_TARGET_DIR 'release\rusty-path-of-building.exe'
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$imports = & dumpbin.exe /DEPENDENTS $binary
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$dlls = @($imports | ForEach-Object { if ($_ -match '^\s+([\w.-]+\.dll)\s*$') { $Matches[1].ToLowerInvariant() } })
if ($dlls.Count -eq 0) { throw 'Could not inspect PE imports' }
$dlls | Write-Output
python packaging/package.py windows $binary --output $dist
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\packaging\windows\build.ps1 -OutputDirectory $dist
python packaging/publish.py check --assets $dist --platform windows
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
[IO.File]::AppendAllText($env:GITHUB_OUTPUT, "dist=$dist" + [Environment]::NewLine)
+13 -1
View File
@@ -2,6 +2,17 @@
## [Unreleased] - ReleaseDate
## [0.3.7] - 2026-11-27
### Fixed
- The Windows application starts on systems without the Visual C++ Redistributable. Its installer and portable ZIP include any required app-local DLLs.
- Opening the Windows application displays the launcher without opening a console window.
### Added
- The Windows executable and installer use the project icon. Start Menu shortcuts can open Path of Exile 1 or 2 directly.
## [0.3.6] - 2026-11-27
### Added
@@ -272,7 +283,8 @@
- First release
<!-- next-url -->
[Unreleased]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/v0.3.6...main
[Unreleased]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/v0.3.7...main
[0.3.7]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/v0.3.6...v0.3.7
[0.3.6]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/67cc995f786c12a9f81275f01412d2155debfd3e...v0.3.6
[0.3.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.4...v0.3.5
Generated
+77 -1
View File
@@ -911,6 +911,20 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "embed-resource"
version = "3.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"
dependencies = [
"cc",
"memchr",
"rustc_version",
"toml",
"vswhom",
"winreg",
]
[[package]]
name = "encoding_rs"
version = "0.8.42"
@@ -3502,7 +3516,7 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-path-of-building"
version = "0.3.6"
version = "0.3.7"
dependencies = [
"ahash",
"anyhow",
@@ -3512,6 +3526,7 @@ dependencies = [
"curl",
"dds",
"directories",
"embed-resource",
"env_logger",
"euclid",
"fast_image_resize",
@@ -3536,6 +3551,7 @@ dependencies = [
"swash",
"tar",
"wgpu",
"windows-sys 0.61.2",
"winit",
"zstd",
]
@@ -3642,6 +3658,15 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "serde_spanned"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
dependencies = [
"serde_core",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -4027,6 +4052,21 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml"
version = "1.1.8+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.2+spec-1.1.0"
@@ -4057,6 +4097,12 @@ dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
[[package]]
name = "tower"
version = "0.5.3"
@@ -4214,6 +4260,26 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vswhom"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"
dependencies = [
"libc",
"vswhom-sys",
]
[[package]]
name = "vswhom-sys"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -4908,6 +4974,16 @@ dependencies = [
"memchr",
]
[[package]]
name = "winreg"
version = "0.56.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
dependencies = [
"cfg-if",
"windows-sys 0.61.2",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
+7 -1
View File
@@ -4,7 +4,7 @@ authors = ["meehl"]
description = "Cross-platform runtime for Path of Building"
repository = "https://git.faumaray.com/faumaray/rusty-path-of-building"
license = "MIT"
version = "0.3.6"
version = "0.3.7"
edition = "2024"
publish = false
@@ -46,6 +46,12 @@ zstd = "0.14"
[target.'cfg(target_os = "linux")'.dependencies]
smithay-clipboard = "0.7.3"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Console"] }
[build-dependencies]
embed-resource = "=3.0.12"
[features]
default = ["bundled-lua-modules"]
# Register Rust implementations of the Lua modules required by PoB's Lua code.
+8 -7
View File
@@ -22,7 +22,7 @@ Download the x64 package for your system from the [Gitea releases page](https://
| System | Installer | Archive |
| --- | --- | --- |
| Windows | Run the setup EXE, then open **Rusty Path of Building** from Start. | Extract the ZIP and run `rusty-path-of-building.exe`. |
| Windows | Run the setup EXE. In Start, **Rusty Path of Building** opens the chooser. **Rusty Path of Building - PoE 1** and **Rusty Path of Building - PoE 2** open their game directly. | Extract the whole ZIP into one folder and run `rusty-path-of-building.exe`. |
| Linux | On a compatible Debian or Ubuntu system, run `sudo apt install ./rusty-path-of-building_<version>_amd64.deb`, substituting the downloaded filename. | Extract the tar.gz and run the included `rusty-path-of-building` executable. |
Both games use the existing Vulkan renderer on Windows and Linux. You need a compatible graphics driver. Game downloads and saved builds live in separate per-game directories under your account.
@@ -54,16 +54,17 @@ cargo build --release
The packager reads the version from `Cargo.toml` and writes to `target/dist/`. It takes a built executable as input. Python 3.11 or newer is required on both platforms.
**Windows x64.** Run these commands in an x64 Visual Studio developer PowerShell with Rust, NASM, CMake, Perl and NSIS 3 installed.
**Windows x64.** The Windows release links the Microsoft C runtime statically. Both the installer and portable ZIP include any additional DLLs the application needs alongside its executable.
For the build machine, install the Visual Studio C++ x64 build tools with the Windows SDK, Git, Rust via rustup, Python 3.11+ with pip, and NSIS 3. The Gitea runner also needs Node for its Actions. From the repository root in x64 PowerShell, use the same build script as CI.
```powershell
$env:RUSTFLAGS = '-C target-feature=+crt-static'
$env:VCPKGRS_DISABLE = '1'
cargo build --locked --release --target x86_64-pc-windows-msvc --features vendored-lua,curl/static-curl
python packaging/package.py windows target/x86_64-pc-windows-msvc/release/rusty-path-of-building.exe
$env:RUSTUP_TOOLCHAIN = 'nightly-2026-11-24'
rustup toolchain install $env:RUSTUP_TOOLCHAIN --profile minimal --target x86_64-pc-windows-msvc
powershell -NoProfile -File .\packaging\windows\build.ps1
```
The setup EXE installs for the current user and adds a Start Menu shortcut. Uninstalling preserves the per-game user data.
The script builds both packages in `target/dist/` and checks the extracted program's CLI output, GUI subsystem and icon. It resolves app-local DLLs alongside the input executable and in explicitly supplied directories. When packaging a custom build, pass its dependency folder with `-DllDirectory`. The installer uses the current user's account and uninstalling preserves saved builds.
**Linux x64.** On Ubuntu 24.04, install the C build tools, `pkg-config`, `libcurl4-openssl-dev`, and `dpkg-dev`. Build the executable and package it with the following commands.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

+1
View File
@@ -0,0 +1 @@
1 ICON "assets/icon.ico"
+11
View File
@@ -0,0 +1,11 @@
fn main() {
println!("cargo:rerun-if-changed=assets/windows.rc");
println!("cargo:rerun-if-changed=assets/icon.ico");
// Check the target rather than the host so cross builds also receive the icon.
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
embed_resource::compile("assets/windows.rc", embed_resource::NONE)
.manifest_required()
.expect("failed to embed the Windows application icon");
}
}
+53
View File
@@ -0,0 +1,53 @@
"""Check the packaged Windows executable on the native runner."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import tomllib
import zipfile
import pefile
from windows_deps import resolve_dependencies
def check_package(directory):
with (Path(__file__).resolve().parents[1] / "Cargo.toml").open("rb") as stream:
package = tomllib.load(stream)["package"]
name, version = package["name"], package["version"]
with tempfile.TemporaryDirectory() as temp:
unpacked = Path(temp) / "portable"
with zipfile.ZipFile(directory / f"{name}-{version}-windows-x86_64.zip") as archive:
archive.extractall(unpacked)
exe = unpacked / f"{name}.exe"
# Verify closure using only files that made it into the ZIP. A globally
# installed DLL on the build machine could otherwise mask an omission.
resolve_dependencies(exe, require_static_crt=True)
with pefile.PE(str(exe), fast_load=True) as pe:
if pe.OPTIONAL_HEADER.Subsystem != pefile.SUBSYSTEM_TYPE["IMAGE_SUBSYSTEM_WINDOWS_GUI"]:
raise ValueError("The packaged executable opens a console window")
pe.parse_data_directories([pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_RESOURCE"]])
resources = {entry.id for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries}
if not {pefile.RESOURCE_TYPE["RT_ICON"], pefile.RESOURCE_TYPE["RT_GROUP_ICON"]} <= resources:
raise ValueError("The packaged executable is missing its application icon")
windows = Path(os.environ["SystemRoot"])
env = {**os.environ, "PATH": os.pathsep.join(map(str, (windows / "System32", windows)))}
for argument, code, expected in [
("--version", 0, f"{name} {version}"),
("--help", 0, "poe2"),
("invalid-game", 2, "invalid-game"),
]:
# Exercise both pipes together and each redirected stream independently.
result = subprocess.run([exe, argument], cwd=temp, env=env, text=True, timeout=30,
stdout=subprocess.PIPE if not code else None,
stderr=subprocess.PIPE if argument != "--help" else None)
output = result.stderr if code else result.stdout
if result.returncode != code or expected not in output:
raise ValueError(f"{argument} returned {result.returncode:#x}: {output.strip()}")
print(f"Verified the packaged {name} {version}, its GUI subsystem, icon and CLI output.")
if __name__ == "__main__":
check_package(Path(sys.argv[1]))
+67 -6
View File
@@ -38,19 +38,70 @@ def check_binary(binary, platform):
raise ValueError(f"{binary} is not an x86_64 {platform} executable")
def package_windows(binary, work):
def windows_inventory(payload, include):
from windows_deps import safe_basename
paths = sorted(payload.rglob("*"), key=lambda p: p.relative_to(payload).as_posix().lower())
files, directories, seen = [], [], set()
for path in paths:
relative = path.relative_to(payload)
for part in relative.parts:
safe_basename(part)
key = relative.as_posix().lower()
if key in seen or key == "uninstall.exe":
raise ValueError(f"Conflicting Windows payload filename: {relative}")
seen.add(key)
if path.is_symlink():
raise ValueError(f"Symlink in Windows payload: {relative}")
if path.is_dir():
directories.append(relative)
elif path.is_file():
files.append(relative)
else:
raise ValueError(f"Not a regular payload file: {relative}")
install = ["!macro InstallPayload"]
previous = None
for path in files:
parent = "\\".join(path.parts[:-1])
destination = "$INSTDIR" + ("\\" + parent if parent else "")
if destination != previous:
install.append(f' SetOutPath "{destination}"')
previous = destination
source = "\\".join(path.parts)
install.append(f' File "payload\\{source}"')
install.extend([' SetOutPath "$INSTDIR"', "!macroend", "", "!macro UninstallPayload"])
for path in files:
name = "\\".join(path.parts)
install.append(f' Delete "$INSTDIR\\{name}"')
for path in sorted(directories, key=lambda p: (-len(p.parts), p.as_posix().lower())):
name = "\\".join(path.parts)
install.append(f' RMDir "$INSTDIR\\{name}"')
install.append("!macroend")
include.write_text("\n".join(install) + "\n", encoding="utf-8")
return files
def package_windows(binary, work, dll_dirs=(), require_static_crt=False):
from windows_deps import resolve_dependencies, safe_basename
safe_basename(NAME)
safe_basename(VERSION)
dependencies = resolve_dependencies(binary, dll_dirs, require_static_crt)
stem = f"{NAME}-{VERSION}-windows-x86_64"
payload = work / "payload"
(payload / "licenses").mkdir(parents=True)
shutil.copyfile(binary, payload / f"{NAME}.exe")
for name, source in dependencies.items():
shutil.copyfile(source, payload / name)
for name, source in NOTICES.items():
shutil.copyfile(source, payload / "licenses" / name)
# Freeze one validated inventory for the archive and both NSIS macros.
inventory = windows_inventory(payload, work / "payload-files.nsh")
archive = work / f"{stem}.zip"
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as bundle:
for path in sorted(payload.rglob("*")):
if path.is_file():
bundle.write(path, path.relative_to(payload))
for relative in inventory:
bundle.write(payload / relative, relative.as_posix())
makensis = shutil.which("makensis")
if not makensis and os.name == "nt":
@@ -63,6 +114,7 @@ def package_windows(binary, work):
if not makensis:
raise ValueError("Install NSIS 3 and make makensis available")
shutil.copyfile(ROOT / "packaging/windows/installer.nsi", work / "installer.nsi")
shutil.copyfile(ROOT / "assets/icon.ico", work / "app.ico")
define = "/D" if os.name == "nt" else "-D"
installer = work / f"{stem}-setup.exe"
subprocess.run(
@@ -137,14 +189,23 @@ def main():
parser.add_argument("platform", choices=("windows", "linux"))
parser.add_argument("binary", type=Path)
parser.add_argument("--output", type=Path, default=ROOT / "target/dist")
parser.add_argument("--dll-dir", type=Path, action="append", default=[], metavar="DIR",
help="Windows DLL source directory (repeatable; no PATH search)")
parser.add_argument("--require-static-crt", action="store_true",
help="Reject direct/delay CRT imports in the Windows executable")
args = parser.parse_args()
if args.platform != "windows" and (args.dll_dir or args.require_static_crt):
parser.error("--dll-dir and --require-static-crt apply only to Windows")
binary = args.binary.resolve()
output = args.output.resolve()
check_binary(binary, args.platform)
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=output) as temp:
package = package_windows if args.platform == "windows" else package_linux
for artifact in package(binary, Path(temp)):
if args.platform == "windows":
artifacts = package_windows(binary, Path(temp), args.dll_dir, args.require_static_crt)
else:
artifacts = package_linux(binary, Path(temp))
for artifact in artifacts:
destination = output / artifact.name
artifact.replace(destination)
print(destination)
+44
View File
@@ -0,0 +1,44 @@
param(
[string]$OutputDirectory = (Join-Path $PSScriptRoot '..\..\target\dist'),
[string[]]$DllDirectory = @()
)
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$destination = [IO.Path]::GetFullPath($OutputDirectory)
$dllDirs = @($DllDirectory | ForEach-Object { (Resolve-Path -LiteralPath $_).Path })
if (-not [Environment]::Is64BitProcess) { throw 'Run this build in x64 PowerShell.' }
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if ($LASTEXITCODE -ne 0 -or -not $vs) { throw 'Install the Visual Studio C++ x64 build tools and Windows SDK.' }
Import-Module (Join-Path $vs 'Common7\Tools\Microsoft.VisualStudio.DevShell.dll')
Enter-VsDevShell -VsInstallPath $vs -SkipAutomaticLocation -DevCmdArguments '-arch=x64 -host_arch=x64'
# A short, fresh target path keeps link.exe below MAX_PATH on service-account runners.
$work = New-Item -ItemType Directory -Path (Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName()))
Push-Location $repo
try {
$env:CARGO_TARGET_DIR = Join-Path $work.FullName 'b'
# With --target, Cargo applies this to target crates only. The encoded setting
# takes precedence over inherited RUSTFLAGS, including on self-hosted runners.
$env:CARGO_ENCODED_RUSTFLAGS = '-Ctarget-feature=+crt-static'
$env:VCPKGRS_DISABLE = '1'
cargo build --locked --release --target x86_64-pc-windows-msvc --features vendored-lua,curl/static-curl
if ($LASTEXITCODE -ne 0) { throw "Windows build failed ($LASTEXITCODE)." }
$binary = Join-Path $env:CARGO_TARGET_DIR 'x86_64-pc-windows-msvc\release\rusty-path-of-building.exe'
# A third-party DLL can itself use the VC runtime. Use the selected toolset's
# app-local redistributables when needed, even on a host with a global redist.
if ($env:VCToolsRedistDir) {
$x64 = Join-Path $env:VCToolsRedistDir 'x64'
if (Test-Path -LiteralPath $x64) {
$dllDirs += @(Get-ChildItem -LiteralPath $x64 -Directory -Filter 'Microsoft.VC*.CRT' | ForEach-Object { $_.FullName })
}
}
python packaging/windows/package_release.py $work.FullName $binary $destination @dllDirs
if ($LASTEXITCODE -ne 0) { throw "Windows package creation or verification failed ($LASTEXITCODE)." }
} finally {
Pop-Location
Remove-Item -LiteralPath $work.FullName -Recurse -Force -ErrorAction Continue
}
+9 -11
View File
@@ -1,5 +1,8 @@
Unicode true
!define MUI_ICON "app.ico"
!define MUI_UNICON "app.ico"
!include "MUI2.nsh"
!include "payload-files.nsh"
Name "Rusty Path of Building"
OutFile "${OUTPUT}"
@@ -24,15 +27,12 @@ FunctionEnd
Section "Rusty Path of Building"
SetShellVarContext current
SetOutPath "$INSTDIR"
File "payload\${APP}"
SetOutPath "$INSTDIR\licenses"
File "payload\licenses\LICENSE.txt"
File "payload\licenses\LiberationSans.txt"
File "payload\licenses\VeraMono.txt"
!insertmacro InstallPayload
SetOutPath "$INSTDIR"
WriteUninstaller "$INSTDIR\Uninstall.exe"
CreateShortcut "$SMPROGRAMS\Rusty Path of Building.lnk" "$INSTDIR\${APP}"
CreateShortcut "$SMPROGRAMS\Rusty Path of Building - PoE 1.lnk" "$INSTDIR\${APP}" "poe1"
CreateShortcut "$SMPROGRAMS\Rusty Path of Building - PoE 2.lnk" "$INSTDIR\${APP}" "poe2"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Rusty Path of Building"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\${APP}"
@@ -46,11 +46,9 @@ Section "Uninstall"
SetRegView 64
SetShellVarContext current
Delete "$SMPROGRAMS\Rusty Path of Building.lnk"
Delete "$INSTDIR\${APP}"
Delete "$INSTDIR\licenses\LICENSE.txt"
Delete "$INSTDIR\licenses\LiberationSans.txt"
Delete "$INSTDIR\licenses\VeraMono.txt"
RMDir "$INSTDIR\licenses"
Delete "$SMPROGRAMS\Rusty Path of Building - PoE 1.lnk"
Delete "$SMPROGRAMS\Rusty Path of Building - PoE 2.lnk"
!insertmacro UninstallPayload
Delete "$INSTDIR\Uninstall.exe"
RMDir "$INSTDIR"
DeleteRegKey HKCU "${UNINSTALL_KEY}"
+28
View File
@@ -0,0 +1,28 @@
"""Build and smoke-test the release packages with an isolated Python interpreter."""
from pathlib import Path
import subprocess
import sys
import venv
def main(work, binary, destination, dll_dirs):
root = Path(__file__).resolve().parents[2]
directory = str(Path(work).resolve() / "py")
builder = venv.EnvBuilder(with_pip=True)
builder.create(directory)
# CPython distributions use different executable names and venv layouts on Windows.
python = builder.ensure_directories(directory).env_exec_cmd
print(f"Packaging with {python} ({sys.platform})", flush=True)
subprocess.run([python, "-m", "pip", "install", "--disable-pip-version-check", "--no-input",
"--require-hashes", "-r", root / "packaging/windows/requirements.txt"], check=True)
args = [python, root / "packaging/package.py", "windows", binary,
"--output", destination, "--require-static-crt"]
for directory in dll_dirs:
args.extend(["--dll-dir", directory])
subprocess.run(args, check=True)
subprocess.run([python, root / "packaging/check_windows_release.py", destination], check=True)
if __name__ == "__main__":
main(*sys.argv[1:4], sys.argv[4:])
+3
View File
@@ -0,0 +1,3 @@
# Windows packaging only; the universal wheel digest is from PyPI.
--only-binary=:all:
pefile==2024.8.26 --hash=sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f
+202
View File
@@ -0,0 +1,202 @@
"""Resolve the app-local PE dependency closure without consulting PATH or System32."""
from collections import deque
from dataclasses import dataclass
import hashlib
from pathlib import Path
import re
# Windows 10+ supplies these libraries. Redistributables and driver-provided
# libraries deliberately do not belong here. UCRT is an OS component on 10+.
SYSTEM_DLLS = frozenset("""
advapi32.dll avrt.dll bcrypt.dll bcryptprimitives.dll cabinet.dll cfgmgr32.dll
clbcatq.dll comctl32.dll comdlg32.dll combase.dll crypt32.dll cryptbase.dll
cryptnet.dll cryptsp.dll d2d1.dll d3d11.dll d3d12.dll d3d9.dll dcomp.dll
dbghelp.dll dnsapi.dll dwrite.dll dwmapi.dll dxgi.dll gdi32.dll
gdi32full.dll hid.dll imagehlp.dll imm32.dll iphlpapi.dll kernel32.dll
kernelbase.dll mpr.dll msimg32.dll msvcrt.dll mswsock.dll ncrypt.dll
netapi32.dll normaliz.dll nsi.dll ntdll.dll ole32.dll oleacc.dll oleaut32.dll
opengl32.dll powrprof.dll propsys.dll psapi.dll rpcrt4.dll sechost.dll
secur32.dll setupapi.dll shcore.dll shell32.dll shlwapi.dll sspicli.dll
ucrtbase.dll user32.dll userenv.dll usp10.dll uxtheme.dll version.dll
wer.dll windowscodecs.dll winhttp.dll wininet.dll winmm.dll winspool.drv
wintrust.dll wldap32.dll ws2_32.dll wtsapi32.dll
""".split())
API_SET = re.compile(r"(?:api|ext)-ms-[a-z0-9-]+-l\d+-\d+-\d+\.dll\Z")
VC_RUNTIME = re.compile(r"(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*\.dll\Z")
DEBUG_RUNTIME = re.compile(
r"(?:(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*d(?:_\w+)?"
r"|mfc(?:m)?\d+u?d|ucrtbased|msvcrtd)\.dll\Z"
)
DEVICE_NAME = re.compile(r"(?:con|prn|aux|nul|com[1-9]|lpt[1-9])\Z", re.I)
def safe_basename(name):
"""Use a portable subset of Windows filenames that is also literal NSIS text."""
if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.+ -]{0,254}", name)
or name.endswith((".", " "))
or DEVICE_NAME.fullmatch(name.split(".")[0].rstrip())):
raise ValueError(f"Unsafe Windows/NSIS filename: {name!r}")
return name
def dll_name(value):
name = safe_basename(value.decode("ascii")).lower()
if not name.endswith((".dll", ".drv")):
raise ValueError(f"Expected a DLL basename, got {name!r}")
return name
def dynamic_crt(name):
return (bool(VC_RUNTIME.fullmatch(name)) or name in {"msvcrt.dll", "ucrtbase.dll"}
or name.startswith(("api-ms-win-crt-", "ext-ms-win-crt-")))
@dataclass
class Imports:
libraries: dict[str, set[bytes | int]]
forwarders: dict[bytes | int, tuple[str, bytes | int]]
def descriptor_count(pe, directory, width):
"""pefile can skip unreadable DLL entries. Compare with the on-disk descriptors."""
if not (directory.VirtualAddress or directory.Size):
return 0
if not directory.VirtualAddress or directory.Size < width:
raise ValueError("Truncated PE import directory")
data = pe.get_data(directory.VirtualAddress, directory.Size)
if len(data) != directory.Size:
raise ValueError("Truncated PE import directory")
for offset in range(0, len(data) - width + 1, width):
if not any(data[offset:offset + width]):
return offset // width
raise ValueError("Unterminated PE import directory")
def inspect_pe(path, *, dll=False):
# Linux packaging never imports pefile or needs its wheel installed.
try:
import pefile
except ImportError as error:
raise ValueError("Windows packaging requires: python -m pip install --require-hashes "
"-r packaging/windows/requirements.txt") from error
try:
with pefile.PE(str(path), fast_load=True) as pe:
if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B:
raise ValueError("Expected an AMD64 PE32+ image")
if not pe.FILE_HEADER.Characteristics & 0x0002:
raise ValueError("PE is not an executable image")
if bool(pe.FILE_HEADER.Characteristics & 0x2000) != dll:
raise ValueError("Expected a DLL image" if dll else "Expected an executable, not a DLL")
directories = pe.OPTIONAL_HEADER.DATA_DIRECTORY
if pe.OPTIONAL_HEADER.NumberOfRvaAndSizes > len(directories):
raise ValueError("Truncated PE data directories")
before = len(pe.get_warnings())
pe.parse_data_directories([0, 1, 13])
# This heuristic says nothing about malformed data; real plugins may
# import only LoadLibrary/GetProcAddress. All parsing warnings fail.
warnings = [w for w in pe.get_warnings()[before:] if w !=
"Imported symbols contain entries typical of packed executables."]
if warnings:
raise ValueError("Malformed PE dependency data: " + "; ".join(warnings))
libraries = {}
for index, width, attr in ((1, 20, "DIRECTORY_ENTRY_IMPORT"),
(13, 32, "DIRECTORY_ENTRY_DELAY_IMPORT")):
if index >= len(directories):
continue
entries = getattr(pe, attr, [])
if len(entries) != descriptor_count(pe, directories[index], width):
raise ValueError(f"Incomplete PE directory {index}: parser skipped descriptors")
for entry in entries:
name = dll_name(entry.dll)
symbols = libraries.setdefault(name, set())
for symbol in entry.imports:
if symbol.import_by_ordinal:
symbols.add(symbol.ordinal)
else:
if not symbol.name or symbol.name == b"*invalid*":
raise ValueError(f"Malformed imported symbol in {name}")
symbols.add(symbol.name)
forwarders = {}
exports = getattr(pe, "DIRECTORY_ENTRY_EXPORT", None)
if directories and directories[0].VirtualAddress and exports is None:
raise ValueError("Unparsed PE export directory")
if exports is not None:
for symbol in exports.symbols:
if symbol.forwarder is None:
continue
forwarder = symbol.forwarder
library, separator, target = forwarder.rpartition(b".")
if not library or not separator or not target:
raise ValueError(f"Malformed forwarded export {forwarder!r}")
name = dll_name(library if library.lower().endswith(b".dll") else library + b".dll")
if target.startswith(b"#"):
if not target[1:].isdigit() or not 0 < int(target[1:]) <= 65535:
raise ValueError(f"Malformed forwarded ordinal {target!r}")
target = int(target[1:])
forwarders[symbol.ordinal] = (name, target)
if symbol.name is not None:
forwarders[symbol.name] = (name, target)
return Imports(libraries, forwarders)
except (pefile.PEFormatError, ValueError, OSError) as error:
raise ValueError(f"{path}: {error}") from error
def resolve_dependencies(binary, dll_dirs=(), require_static_crt=False):
"""Return {Windows basename: source path}, with only imported DLLs selected."""
binary = Path(binary).resolve()
directories = list(dict.fromkeys([binary.parent, *(Path(p).resolve() for p in dll_dirs)]))
candidates = {}
for directory in directories:
if not directory.is_dir():
raise ValueError(f"DLL source is not a directory: {directory}")
for path in sorted(directory.iterdir(), key=lambda p: p.name):
candidates.setdefault(path.name.lower(), []).append(path)
root = inspect_pe(binary)
if require_static_crt:
dynamic = sorted(name for name in root.libraries if dynamic_crt(name) or DEBUG_RUNTIME.fullmatch(name))
if dynamic:
raise ValueError(f"{binary.name}: --require-static-crt rejects dynamic CRT imports: "
+ ", ".join(dynamic))
pending = deque((name, symbols, (binary.name, name)) for name, symbols in sorted(root.libraries.items()))
selected, inspected, visited = {}, {}, {}
while pending:
name, symbols, chain = pending.popleft()
try:
if DEBUG_RUNTIME.fullmatch(name):
raise ValueError(f"Debug VC runtime cannot be redistributed: {name}")
if name in SYSTEM_DLLS or API_SET.fullmatch(name):
continue
if name not in inspected:
paths = candidates.get(name, [])
if not paths:
raise ValueError(f"Missing {name}; supply its redistributable directory with --dll-dir. "
f"Searched: {', '.join(map(str, directories))}")
for path in paths:
if path.is_symlink() or not path.is_file():
raise ValueError(f"DLL source must be a regular, non-symlink file: {path}")
safe_basename(path.name)
if len(paths) > 1:
digests = set()
for path in paths:
with path.open("rb") as stream:
digests.add(hashlib.file_digest(stream, "sha256").digest())
if len(digests) != 1:
raise ValueError(f"Ambiguous differing sources for {name}: {', '.join(map(str, paths))}")
selected[name] = paths[0]
inspected[name] = inspect_pe(paths[0], dll=True)
pending.extend((dependency, requested, (*chain, dependency)) for dependency, requested
in sorted(inspected[name].libraries.items()))
seen = visited.setdefault(name, set())
for symbol in symbols - seen:
forwarded = inspected[name].forwarders.get(symbol)
if forwarded:
dependency, target = forwarded
pending.append((dependency, {target}, (*chain, dependency)))
seen.update(symbols)
except (ValueError, OSError) as error:
raise ValueError(f"{' -> '.join(chain)}: {error}") from error
return dict(sorted(selected.items()))
+40
View File
@@ -1,3 +1,5 @@
#![cfg_attr(windows, windows_subsystem = "windows")]
use crate::{app::App, args::Args};
use clap::Parser;
use std::path::{Path, PathBuf};
@@ -25,6 +27,9 @@ mod window;
mod worker_pool;
fn main() -> anyhow::Result<()> {
#[cfg(windows)]
attach_parent_console();
profiling::register_thread!("Main Thread");
env_logger::init();
@@ -48,6 +53,41 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
/// Reuse a terminal's console without opening one for Explorer or Start Menu launches.
#[cfg(windows)]
fn attach_parent_console() {
use windows_sys::Win32::{
Foundation::{GetHandleInformation, INVALID_HANDLE_VALUE},
System::Console::{
ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE,
STD_OUTPUT_HANDLE, SetStdHandle,
},
};
let inherited = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE].map(|stream| {
// SAFETY: These calls only query process-owned handles; no ownership is transferred.
let handle = unsafe { GetStdHandle(stream) };
let mut flags = 0;
let valid = !handle.is_null()
&& handle != INVALID_HANDLE_VALUE
&& unsafe { GetHandleInformation(handle, &mut flags) } != 0;
(stream, handle, valid)
});
// SAFETY: Called before logging, argument parsing, or application threads start.
// Attaching can replace the standard handle table, so restore each valid inherited
// handle independently, including when only stdout or stderr was redirected.
unsafe {
if AttachConsole(ATTACH_PARENT_PROCESS) != 0 {
for (stream, handle, valid) in inherited {
if valid {
SetStdHandle(stream, handle);
}
}
}
}
}
/// Search for the Launch.lua file in nearby locations
fn find_nearby_launch_script() -> Option<PathBuf> {
let mut candidates = vec![Path::new("Launch.lua"), Path::new("src/Launch.lua")];