Compare commits
6
Commits
67cc995f78
...
v0.3.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
329a1ad4df | ||
|
|
d5df8da8b9 | ||
|
|
f9a3d8dbf1 | ||
|
|
67fba6c7e2 | ||
|
|
35ef0c59e4 | ||
|
|
4118c3943f |
No files matched your search
@@ -0,0 +1,46 @@
|
|||||||
|
# Gitea selects .gitea/workflows before .github/workflows. Keep the inherited
|
||||||
|
# push/PR checks active here; the existing GitHub workflows remain independent.
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
code: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
RUSTUP_TOOLCHAIN: nightly-2026-11-24
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Install build dependencies
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sudo_cmd=()
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then sudo_cmd=(sudo); fi
|
||||||
|
"${sudo_cmd[@]}" apt-get update
|
||||||
|
"${sudo_cmd[@]}" apt-get install -y ca-certificates curl build-essential cmake perl nasm pkg-config libcurl4-openssl-dev
|
||||||
|
|
||||||
|
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
|
||||||
|
with:
|
||||||
|
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
|
||||||
|
components: rustfmt, clippy
|
||||||
|
|
||||||
|
- name: Format
|
||||||
|
run: cargo fmt --check
|
||||||
|
|
||||||
|
- name: Clippy
|
||||||
|
run: cargo clippy --locked --all-targets --features vendored-lua -- -D warnings
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: cargo test --locked --features vendored-lua
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
name: Native release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*'] # publish.py enforces exactly vX.Y.Z == Cargo.toml.
|
||||||
|
|
||||||
|
# Requires Gitea >=1.26.2; check it before any artifact transfer. Never cancel
|
||||||
|
# an in-flight publisher. Other publishers for this tag must use the same group.
|
||||||
|
concurrency:
|
||||||
|
group: release-${{ gitea.repository }}-${{ gitea.ref }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
code: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
GITEA_API_URL: ${{ gitea.api_url }}
|
||||||
|
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||||
|
RELEASE_TAG: ${{ gitea.ref_name }}
|
||||||
|
RELEASE_COMMIT: ${{ gitea.sha }}
|
||||||
|
RUSTUP_TOOLCHAIN: nightly-2026-11-24
|
||||||
|
CARGO_INCREMENTAL: '0'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
linux:
|
||||||
|
# Host/image prerequisites: Git, Bash, Node 20, Python 3.11+,
|
||||||
|
# and root or passwordless sudo for the explicit apt packages below.
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
ref: ${{ gitea.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Check tag, checkout and Gitea prerequisite
|
||||||
|
run: python3 packaging/publish.py check
|
||||||
|
|
||||||
|
- name: Prepare native Linux build
|
||||||
|
id: stage
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
. /etc/os-release
|
||||||
|
[[ "$ID" == ubuntu && "$VERSION_ID" == 24.04 ]]
|
||||||
|
test "$(uname -m)" = x86_64
|
||||||
|
sudo_cmd=()
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then sudo_cmd=(sudo); fi
|
||||||
|
"${sudo_cmd[@]}" apt-get update
|
||||||
|
"${sudo_cmd[@]}" apt-get install -y ca-certificates curl build-essential cmake perl nasm pkg-config libcurl4-openssl-dev dpkg-dev
|
||||||
|
dist=$(mktemp -d "$RUNNER_TEMP/release-linux.XXXXXXXX")
|
||||||
|
build=$(mktemp -d "$RUNNER_TEMP/build-linux.XXXXXXXX")
|
||||||
|
echo "dist=$dist" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "CARGO_TARGET_DIR=$build" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
|
||||||
|
with:
|
||||||
|
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
|
||||||
|
targets: x86_64-unknown-linux-gnu
|
||||||
|
|
||||||
|
- name: Build and package Linux
|
||||||
|
env:
|
||||||
|
DIST: ${{ steps.stage.outputs.dist }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cargo build --locked --release --target x86_64-unknown-linux-gnu --features vendored-lua
|
||||||
|
binary="$CARGO_TARGET_DIR/x86_64-unknown-linux-gnu/release/rusty-path-of-building"
|
||||||
|
"$binary" --version
|
||||||
|
python3 packaging/package.py linux "$binary" --output "$DIST"
|
||||||
|
python3 packaging/publish.py check --assets "$DIST" --platform linux
|
||||||
|
|
||||||
|
# Gitea's v4 protocol needs these compatible forks (Gitea 1.22 release notes).
|
||||||
|
# Runtime artifact credentials are supplied by the runner, not GITEA_TOKEN.
|
||||||
|
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||||
|
with:
|
||||||
|
name: packages-linux
|
||||||
|
path: ${{ steps.stage.outputs.dist }}/*
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
|
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.
|
||||||
|
runs-on: windows-x64
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: powershell
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
ref: ${{ gitea.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Check tag, checkout and Gitea prerequisite
|
||||||
|
run: |
|
||||||
|
python packaging/publish.py check
|
||||||
|
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||||
|
|
||||||
|
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
|
||||||
|
with:
|
||||||
|
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
|
||||||
|
targets: x86_64-pc-windows-msvc
|
||||||
|
|
||||||
|
- name: Build and package Windows
|
||||||
|
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 }
|
||||||
|
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)
|
||||||
|
|
||||||
|
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||||
|
with:
|
||||||
|
name: packages-windows
|
||||||
|
path: ${{ steps.stage.outputs.dist }}/*
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
|
publish:
|
||||||
|
needs: [linux, windows]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
code: read
|
||||||
|
releases: write
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
ref: ${{ gitea.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Check prerequisites and prepare empty download directory
|
||||||
|
id: stage
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 packaging/publish.py check
|
||||||
|
dist=$(mktemp -d "$RUNNER_TEMP/release-publish.XXXXXXXX")
|
||||||
|
echo "dist=$dist" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7 # v4
|
||||||
|
with:
|
||||||
|
name: packages-linux
|
||||||
|
path: ${{ steps.stage.outputs.dist }}
|
||||||
|
|
||||||
|
- uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7 # v4
|
||||||
|
with:
|
||||||
|
name: packages-windows
|
||||||
|
path: ${{ steps.stage.outputs.dist }}
|
||||||
|
|
||||||
|
- name: Publish verified four-attachment release
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
DIST: ${{ steps.stage.outputs.dist }}
|
||||||
|
run: python3 packaging/publish.py publish --assets "$DIST"
|
||||||
+9
-1
@@ -2,6 +2,13 @@
|
|||||||
|
|
||||||
## [Unreleased] - ReleaseDate
|
## [Unreleased] - ReleaseDate
|
||||||
|
|
||||||
|
## [0.3.6] - 2026-11-27
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Choose Path of Exile 1 or 2 in the launcher when starting without arguments.
|
||||||
|
- Tagged Gitea releases include Windows x64 setup and ZIP downloads and Linux x64 Debian and tar.gz packages.
|
||||||
|
|
||||||
## [0.3.5] - 2026-11-20
|
## [0.3.5] - 2026-11-20
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
@@ -265,7 +272,8 @@
|
|||||||
- First release
|
- First release
|
||||||
|
|
||||||
<!-- next-url -->
|
<!-- next-url -->
|
||||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.5...HEAD
|
[Unreleased]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/v0.3.6...main
|
||||||
|
[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
|
[0.3.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.4...v0.3.5
|
||||||
[0.3.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.3...v0.3.4
|
[0.3.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.3...v0.3.4
|
||||||
|
|||||||
Generated
+1
-1
@@ -3502,7 +3502,7 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rusty-path-of-building"
|
name = "rusty-path-of-building"
|
||||||
version = "0.3.5"
|
version = "0.3.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ahash",
|
"ahash",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
|||||||
+2
-2
@@ -2,9 +2,9 @@
|
|||||||
name = "rusty-path-of-building"
|
name = "rusty-path-of-building"
|
||||||
authors = ["meehl"]
|
authors = ["meehl"]
|
||||||
description = "Cross-platform runtime for Path of Building"
|
description = "Cross-platform runtime for Path of Building"
|
||||||
repository = "https://github.com/meehl/rusty-path-of-building"
|
repository = "https://git.faumaray.com/faumaray/rusty-path-of-building"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
version = "0.3.5"
|
version = "0.3.6"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
|
|||||||
@@ -6,12 +6,29 @@ The main focus of this project is native Linux support for Path of Building. It
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
Open **Rusty Path of Building** from the applications menu, double-click the executable, or run it without arguments. Choose **Path of Exile 1** or **Path of Exile 2**. The first launch of each game downloads its Path of Building files into your user data directory.
|
||||||
|
|
||||||
|
To open a specific game directly or pass a build URL, use the command line.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
rusty-path-of-building [poe1|poe2]
|
rusty-path-of-building
|
||||||
|
rusty-path-of-building poe1
|
||||||
|
rusty-path-of-building poe2 'pob://pobbin/<id>'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
Download the x64 package for your system from the [Gitea releases page](https://git.faumaray.com/faumaray/rusty-path-of-building/releases).
|
||||||
|
|
||||||
|
| 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`. |
|
||||||
|
| 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.
|
||||||
|
|
||||||
|
The Linux release is built on Ubuntu 24.04. The tarball requires glibc 2.39 or newer, libcurl, Vulkan, and the X11 or Wayland client libraries. Installing the Debian package through APT resolves its library dependencies.
|
||||||
|
|
||||||
[](https://repology.org/project/rusty-path-of-building/versions)
|
[](https://repology.org/project/rusty-path-of-building/versions)
|
||||||
|
|
||||||
### Flathub
|
### Flathub
|
||||||
@@ -33,6 +50,30 @@ cargo build --release
|
|||||||
- `LuaJIT` - Required by the `mlua` crate. Alternatively, enable the `vendored-lua` feature to build LuaJIT from source instead of using a system installation.
|
- `LuaJIT` - Required by the `mlua` crate. Alternatively, enable the `vendored-lua` feature to build LuaJIT from source instead of using a system installation.
|
||||||
- `libcurl` - Required when the `bundled-lua-modules` feature (enabled by default) is used.
|
- `libcurl` - Required when the `bundled-lua-modules` feature (enabled by default) is used.
|
||||||
|
|
||||||
|
### Creating release packages
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
The setup EXE installs for the current user and adds a Start Menu shortcut. Uninstalling preserves the per-game user data.
|
||||||
|
|
||||||
|
**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.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --locked --release --target x86_64-unknown-linux-gnu --features vendored-lua
|
||||||
|
python3 packaging/package.py linux target/x86_64-unknown-linux-gnu/release/rusty-path-of-building
|
||||||
|
```
|
||||||
|
|
||||||
|
**Gitea releases.** A new `vX.Y.Z` tag matching the version in `Cargo.toml` triggers the release workflow. It builds on the `windows-x64` and `ubuntu-latest` runners, gathers the four packages and verifies their SHA-256 hashes before publishing. Use a native Windows x64 runner with the build tools above and an Ubuntu 24.04 x64 runner with APT access. Both runners need Git, a Node runtime for the checkout and artifact actions, and Python 3.11+. The repository's Actions job token needs read access to code and write access to releases.
|
||||||
|
|
||||||
## Runtime Dependencies
|
## Runtime Dependencies
|
||||||
|
|
||||||
Path of Building's Lua code requires the following C libraries:
|
Path of Building's Lua code requires the following C libraries:
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Rusty Path of Building
|
||||||
|
Comment=Plan characters for Path of Exile 1 and 2
|
||||||
|
Exec=rusty-path-of-building
|
||||||
|
Icon=rusty-path-of-building
|
||||||
|
Terminal=false
|
||||||
|
Categories=Game;RolePlaying;
|
||||||
|
StartupWMClass=rusty-path-of-building
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
"""Package a release binary built with the vendored-lua feature."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import tomllib
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
PACKAGE = tomllib.loads((ROOT / "Cargo.toml").read_text(encoding="utf-8"))["package"]
|
||||||
|
NAME = PACKAGE["name"]
|
||||||
|
VERSION = PACKAGE["version"]
|
||||||
|
NOTICES = {
|
||||||
|
"LICENSE.txt": ROOT / "LICENSE",
|
||||||
|
"LiberationSans.txt": ROOT / "assets/fonts/LiberationSans License.txt",
|
||||||
|
"VeraMono.txt": ROOT / "assets/fonts/VeraMono License.txt",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def check_binary(binary, platform):
|
||||||
|
with binary.open("rb") as stream:
|
||||||
|
header = stream.read(64)
|
||||||
|
if platform == "linux":
|
||||||
|
# ELF64, little endian, EM_X86_64.
|
||||||
|
if header[:6] == b"\x7fELF\x02\x01" and header[18:20] == b"\x3e\x00":
|
||||||
|
return
|
||||||
|
elif len(header) == 64 and header[:2] == b"MZ":
|
||||||
|
stream.seek(struct.unpack_from("<I", header, 60)[0])
|
||||||
|
if stream.read(6) == b"PE\x00\x00\x64\x86":
|
||||||
|
return
|
||||||
|
raise ValueError(f"{binary} is not an x86_64 {platform} executable")
|
||||||
|
|
||||||
|
|
||||||
|
def package_windows(binary, work):
|
||||||
|
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 NOTICES.items():
|
||||||
|
shutil.copyfile(source, payload / "licenses" / name)
|
||||||
|
|
||||||
|
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))
|
||||||
|
|
||||||
|
makensis = shutil.which("makensis")
|
||||||
|
if not makensis and os.name == "nt":
|
||||||
|
for key in ("ProgramFiles(x86)", "ProgramFiles"):
|
||||||
|
if key in os.environ:
|
||||||
|
candidate = Path(os.environ[key]) / "NSIS" / "makensis.exe"
|
||||||
|
if candidate.is_file():
|
||||||
|
makensis = str(candidate)
|
||||||
|
break
|
||||||
|
if not makensis:
|
||||||
|
raise ValueError("Install NSIS 3 and make makensis available")
|
||||||
|
shutil.copyfile(ROOT / "packaging/windows/installer.nsi", work / "installer.nsi")
|
||||||
|
define = "/D" if os.name == "nt" else "-D"
|
||||||
|
installer = work / f"{stem}-setup.exe"
|
||||||
|
subprocess.run(
|
||||||
|
[makensis, f"{define}VERSION={VERSION}", f"{define}OUTPUT={installer.name}", "installer.nsi"],
|
||||||
|
cwd=work, check=True,
|
||||||
|
)
|
||||||
|
return archive, installer
|
||||||
|
|
||||||
|
|
||||||
|
def package_linux(binary, work):
|
||||||
|
stem = f"{NAME}-{VERSION}-linux-x86_64"
|
||||||
|
package = work / "debian" / NAME
|
||||||
|
executable = package / "usr/bin" / NAME
|
||||||
|
executable.parent.mkdir(parents=True)
|
||||||
|
shutil.copyfile(binary, executable)
|
||||||
|
executable.chmod(0o755)
|
||||||
|
|
||||||
|
docs = package / "usr/share/doc" / NAME
|
||||||
|
docs.mkdir(parents=True)
|
||||||
|
for name, source in NOTICES.items():
|
||||||
|
shutil.copyfile(source, docs / ("copyright" if name == "LICENSE.txt" else name))
|
||||||
|
desktop = package / "usr/share/applications" / f"{NAME}.desktop"
|
||||||
|
desktop.parent.mkdir(parents=True)
|
||||||
|
shutil.copyfile(ROOT / "packaging/linux" / desktop.name, desktop)
|
||||||
|
icon = package / "usr/share/icons/hicolor/256x256/apps" / f"{NAME}.png"
|
||||||
|
icon.parent.mkdir(parents=True)
|
||||||
|
shutil.copyfile(ROOT / "assets/icon.png", icon)
|
||||||
|
|
||||||
|
# dpkg-shlibdeps reads the build system's package database and requires a source stanza.
|
||||||
|
(work / "debian/control").write_text(f"Source: {NAME}\n", encoding="utf-8")
|
||||||
|
control = package / "DEBIAN/control"
|
||||||
|
control.parent.mkdir()
|
||||||
|
linked = subprocess.check_output(
|
||||||
|
["dpkg-shlibdeps", "-O", executable.relative_to(work)], cwd=work, text=True
|
||||||
|
).strip().removeprefix("shlibs:Depends=")
|
||||||
|
# winit and wgpu load the window-system and Vulkan libraries at runtime.
|
||||||
|
extra = ("ca-certificates", "libvulkan1", "libx11-6", "libx11-xcb1", "libxcursor1",
|
||||||
|
"libxi6", "libxkbcommon0", "libxkbcommon-x11-0", "libwayland-client0",
|
||||||
|
"libwayland-cursor0")
|
||||||
|
control.write_text(
|
||||||
|
f"Package: {NAME}\nVersion: {VERSION}\nArchitecture: amd64\n"
|
||||||
|
"Section: games\nPriority: optional\n"
|
||||||
|
"Maintainer: Rusty Path of Building contributors <noreply@git.faumaray.com>\n"
|
||||||
|
f"Homepage: {PACKAGE['repository']}\n"
|
||||||
|
f"Depends: {', '.join((linked, *extra))}\n"
|
||||||
|
"Recommends: mesa-vulkan-drivers | vulkan-icd\n"
|
||||||
|
f"Description: {PACKAGE['description']}\n"
|
||||||
|
" Plan characters for Path of Exile 1 and 2.\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
# The runner's umask must not give package files writable system permissions.
|
||||||
|
for path in [package, *package.rglob("*")]:
|
||||||
|
path.chmod(0o755 if path.is_dir() or path == executable else 0o644)
|
||||||
|
installer = work / f"{NAME}_{VERSION}_amd64.deb"
|
||||||
|
subprocess.run(["dpkg-deb", "--root-owner-group", "--build", package, installer], check=True)
|
||||||
|
|
||||||
|
archive = work / f"{stem}.tar.gz"
|
||||||
|
with tarfile.open(archive, "w:gz") as bundle:
|
||||||
|
members = {NAME: executable, **{f"licenses/{key}": value for key, value in NOTICES.items()}}
|
||||||
|
for name, source in members.items():
|
||||||
|
entry = bundle.gettarinfo(str(source), arcname=f"{stem}/{name}")
|
||||||
|
entry.uid = entry.gid = 0
|
||||||
|
entry.uname = entry.gname = "root"
|
||||||
|
entry.mode = 0o755 if name == NAME else 0o644
|
||||||
|
with source.open("rb") as stream:
|
||||||
|
bundle.addfile(entry, stream)
|
||||||
|
return archive, installer
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("platform", choices=("windows", "linux"))
|
||||||
|
parser.add_argument("binary", type=Path)
|
||||||
|
parser.add_argument("--output", type=Path, default=ROOT / "target/dist")
|
||||||
|
args = parser.parse_args()
|
||||||
|
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)):
|
||||||
|
destination = output / artifact.name
|
||||||
|
artifact.replace(destination)
|
||||||
|
print(destination)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except (OSError, ValueError, subprocess.CalledProcessError) as error:
|
||||||
|
sys.exit(str(error))
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Validate packages and publish a resumable, commit-bound Gitea draft.
|
||||||
|
|
||||||
|
Requires Python 3.11+, Git and Gitea >=1.26.2. Run from the tagged checkout.
|
||||||
|
`check` is read-only; `publish` requires GITEA_TOKEN. Arguments default to the
|
||||||
|
workflow's GITEA_API_URL, GITEA_REPOSITORY, RELEASE_TAG and RELEASE_COMMIT env.
|
||||||
|
Serialize invocations for the same repository/tag (the workflow does this).
|
||||||
|
HTTP is accepted only for loopback fixtures. API redirects are never followed;
|
||||||
|
attachment redirects receive credentials only while they stay on the API origin.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tomllib
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
NAME = "rusty-path-of-building"
|
||||||
|
VERSION = r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
|
||||||
|
CHUNK = 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
class ReleaseError(Exception):
|
||||||
|
"""A conflict or failed prerequisite; leave the release for inspection/retry."""
|
||||||
|
|
||||||
|
|
||||||
|
def require(condition, message):
|
||||||
|
if not condition:
|
||||||
|
raise ReleaseError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def expected_names(version, platform="all"):
|
||||||
|
names = {
|
||||||
|
"windows": [f"{NAME}-{version}-windows-x86_64.zip",
|
||||||
|
f"{NAME}-{version}-windows-x86_64-setup.exe"],
|
||||||
|
"linux": [f"{NAME}-{version}-linux-x86_64.tar.gz",
|
||||||
|
f"{NAME}_{version}_amd64.deb"],
|
||||||
|
}
|
||||||
|
return names[platform] if platform != "all" else names["windows"] + names["linux"]
|
||||||
|
|
||||||
|
|
||||||
|
def fingerprint(stream, limit=None):
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
size = 0
|
||||||
|
while chunk := stream.read(CHUNK):
|
||||||
|
size += len(chunk)
|
||||||
|
require(limit is None or size <= limit, "Attachment exceeds expected size")
|
||||||
|
digest.update(chunk)
|
||||||
|
return size, digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def local_assets(directory, names):
|
||||||
|
require(directory.is_dir() and not directory.is_symlink(), "Asset directory is missing or a symlink")
|
||||||
|
require({p.name for p in directory.iterdir()} == set(names),
|
||||||
|
"Asset directory must contain exactly the expected filenames: " + ", ".join(names))
|
||||||
|
result = {}
|
||||||
|
for name in names:
|
||||||
|
path = directory / name
|
||||||
|
require(path.is_file() and not path.is_symlink(), f"Not a regular asset: {name}")
|
||||||
|
with path.open("rb") as stream:
|
||||||
|
size, digest = fingerprint(stream)
|
||||||
|
require(size > 0, f"Empty asset: {name}")
|
||||||
|
result[name] = (path, size, digest)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def local_identity(source, tag, revision):
|
||||||
|
require(re.fullmatch("v" + VERSION, tag or ""), "Tag must be exactly vX.Y.Z")
|
||||||
|
with (source / "Cargo.toml").open("rb") as stream:
|
||||||
|
package = tomllib.load(stream)["package"]
|
||||||
|
require(package["name"] == NAME, "Unexpected Cargo package name")
|
||||||
|
require(tag == "v" + package["version"], "Tag does not match Cargo.toml version")
|
||||||
|
require(re.fullmatch(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})", revision or ""),
|
||||||
|
"Supply the full event commit/object SHA with --commit or RELEASE_COMMIT")
|
||||||
|
|
||||||
|
def resolve(ref):
|
||||||
|
completed = subprocess.run(["git", "-C", str(source), "rev-parse", "--verify", ref],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
require(completed.returncode == 0, "Cannot resolve checkout/event commit")
|
||||||
|
return completed.stdout.strip().lower()
|
||||||
|
|
||||||
|
commit = resolve("HEAD^{commit}")
|
||||||
|
require(commit == resolve(revision + "^{commit}"), "Checkout differs from event commit")
|
||||||
|
return package["version"], commit
|
||||||
|
|
||||||
|
|
||||||
|
def checked_url(url):
|
||||||
|
parsed = urllib.parse.urlsplit(url)
|
||||||
|
require(parsed.scheme == "https" or
|
||||||
|
(parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}),
|
||||||
|
"Use HTTPS (HTTP is allowed only for a loopback fixture)")
|
||||||
|
require(parsed.hostname and not parsed.username and not parsed.password and not parsed.fragment,
|
||||||
|
"Invalid URL or embedded URL credentials")
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
|
def origin(url):
|
||||||
|
parsed = checked_url(url)
|
||||||
|
return parsed.scheme, parsed.hostname, parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class Gitea:
|
||||||
|
def __init__(self, api_url, token=""):
|
||||||
|
self.api_url = api_url.rstrip("/")
|
||||||
|
parsed = checked_url(self.api_url)
|
||||||
|
require(parsed.path.endswith("/api/v1") and not parsed.query, "API URL must end in /api/v1")
|
||||||
|
self.token = token
|
||||||
|
self.opener = urllib.request.build_opener(NoRedirect())
|
||||||
|
|
||||||
|
def open(self, method, url, data=None, headers=None, authenticated=True):
|
||||||
|
checked_url(url)
|
||||||
|
headers = {"User-Agent": NAME + "-release", **(headers or {})}
|
||||||
|
if authenticated and self.token:
|
||||||
|
require(origin(url) == origin(self.api_url), "Refusing cross-origin credentials")
|
||||||
|
headers["Authorization"] = "token " + self.token
|
||||||
|
return self.opener.open(urllib.request.Request(url, data=data, headers=headers, method=method),
|
||||||
|
timeout=120)
|
||||||
|
|
||||||
|
def request(self, method, path, body=None, missing_ok=False, data=None, headers=None):
|
||||||
|
headers = {"Accept": "application/json", **(headers or {})}
|
||||||
|
if body is not None:
|
||||||
|
data = json.dumps(body).encode()
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
try:
|
||||||
|
with self.open(method, self.api_url + path, data, headers) as response:
|
||||||
|
payload = response.read()
|
||||||
|
return json.loads(payload) if payload else None
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
error.close()
|
||||||
|
if error.code == 404 and missing_ok:
|
||||||
|
return None
|
||||||
|
# Never echo response bodies, signed redirect URLs or headers containing credentials.
|
||||||
|
raise ReleaseError(f"Gitea {method} request failed (HTTP {error.code})") from None
|
||||||
|
|
||||||
|
def check_version(self):
|
||||||
|
version = self.request("GET", "/version").get("version", "")
|
||||||
|
match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?", version)
|
||||||
|
require(match and tuple(map(int, match.groups())) >= (1, 26, 2),
|
||||||
|
"Gitea >=1.26.2 stable is required for release concurrency/artifact safety")
|
||||||
|
return version
|
||||||
|
|
||||||
|
def download_fingerprint(self, url, size):
|
||||||
|
# A storage redirect may carry its own signed query, but never our token.
|
||||||
|
authenticated = origin(url) == origin(self.api_url)
|
||||||
|
for _ in range(6):
|
||||||
|
try:
|
||||||
|
with self.open("GET", url, authenticated=authenticated) as response:
|
||||||
|
return fingerprint(response, limit=size)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
location = error.headers.get("Location")
|
||||||
|
code = error.code
|
||||||
|
error.close()
|
||||||
|
if code not in {301, 302, 303, 307, 308} or not location:
|
||||||
|
raise ReleaseError(f"Attachment download failed (HTTP {code})") from None
|
||||||
|
next_url = urllib.parse.urljoin(url, location)
|
||||||
|
require(not (checked_url(url).scheme == "https" and checked_url(next_url).scheme != "https"),
|
||||||
|
"Refusing attachment HTTPS downgrade")
|
||||||
|
authenticated = authenticated and origin(next_url) == origin(self.api_url)
|
||||||
|
url = next_url
|
||||||
|
raise ReleaseError("Too many attachment redirects")
|
||||||
|
|
||||||
|
def upload(self, path, asset):
|
||||||
|
filename, size, _ = asset
|
||||||
|
boundary = "release-" + uuid.uuid4().hex
|
||||||
|
prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; '
|
||||||
|
f'filename="{filename.name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()
|
||||||
|
suffix = f"\r\n--{boundary}--\r\n".encode()
|
||||||
|
|
||||||
|
def chunks():
|
||||||
|
yield prefix
|
||||||
|
with filename.open("rb") as stream:
|
||||||
|
while chunk := stream.read(CHUNK):
|
||||||
|
yield chunk
|
||||||
|
yield suffix
|
||||||
|
|
||||||
|
return self.request("POST", path, data=chunks(), headers={
|
||||||
|
"Content-Type": f"multipart/form-data; boundary={boundary}",
|
||||||
|
"Content-Length": str(len(prefix) + size + len(suffix)),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def release_notes(source, version):
|
||||||
|
changelog = source / "CHANGELOG.md"
|
||||||
|
if not changelog.is_file():
|
||||||
|
return f"Release v{version}"
|
||||||
|
text = changelog.read_text(encoding="utf-8")
|
||||||
|
match = re.search(r"^## \[" + re.escape(version) + r"\][^\n]*\n(.*?)(?=^## \[|\Z)",
|
||||||
|
text, re.MULTILINE | re.DOTALL)
|
||||||
|
return match.group(1).strip() if match else f"Release v{version}"
|
||||||
|
|
||||||
|
|
||||||
|
class Publisher:
|
||||||
|
def __init__(self, api, repository, tag, commit, assets):
|
||||||
|
require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository or ""),
|
||||||
|
"Repository must be owner/name")
|
||||||
|
require(all(part not in {".", ".."} for part in repository.split("/")), "Invalid repository")
|
||||||
|
self.api, self.tag, self.commit, self.assets = api, tag, commit, assets
|
||||||
|
self.base = "/repos/" + repository
|
||||||
|
self.marker = f"<!-- {NAME}:gitea-release:v1 commit={commit} -->"
|
||||||
|
|
||||||
|
def check_tag(self):
|
||||||
|
tag = self.api.request("GET", self.base + "/tags/" + self.tag)
|
||||||
|
require(tag.get("name") == self.tag and tag.get("commit", {}).get("sha") == self.commit,
|
||||||
|
"Live tag does not point to the checked-out commit")
|
||||||
|
|
||||||
|
def release(self):
|
||||||
|
return self.api.request("GET", self.base + "/releases/tags/" + self.tag, missing_ok=True)
|
||||||
|
|
||||||
|
def inspect(self, release):
|
||||||
|
require(release and release.get("tag_name") == self.tag and
|
||||||
|
release.get("target_commitish") == self.commit and
|
||||||
|
release.get("body", "").splitlines().count(self.marker) == 1 and
|
||||||
|
release.get("prerelease") is False and type(release.get("draft")) is bool,
|
||||||
|
"Release is not an owned, commit-matching stable release; refusing changes")
|
||||||
|
require(type(release.get("id")) is int and release["id"] > 0, "Invalid release ID")
|
||||||
|
attachments = self.api.request("GET", self.base + f'/releases/{release["id"]}/assets')
|
||||||
|
indexed = {}
|
||||||
|
for attachment in attachments:
|
||||||
|
name = attachment.get("name")
|
||||||
|
require(name in self.assets and name not in indexed, "Unexpected or duplicate release attachment")
|
||||||
|
require(type(attachment.get("id")) is int and attachment["id"] > 0 and
|
||||||
|
type(attachment.get("size")) is int and attachment["size"] >= 0,
|
||||||
|
"Invalid attachment metadata")
|
||||||
|
# Download counters change during our own hash verification.
|
||||||
|
indexed[name] = {key: attachment[key] for key in
|
||||||
|
("id", "name", "size", "browser_download_url")}
|
||||||
|
return indexed
|
||||||
|
|
||||||
|
def matches(self, attachment, asset):
|
||||||
|
_, size, digest = asset
|
||||||
|
if attachment["size"] != size:
|
||||||
|
return False
|
||||||
|
return self.api.download_fingerprint(attachment["browser_download_url"], size) == (size, digest)
|
||||||
|
|
||||||
|
def verify_complete(self, attachments):
|
||||||
|
require(set(attachments) == set(self.assets), "Release does not have exactly four expected attachments")
|
||||||
|
for name, asset in self.assets.items():
|
||||||
|
require(self.matches(attachments[name], asset), f"Release attachment differs: {name}")
|
||||||
|
|
||||||
|
def guard_draft(self, release_id):
|
||||||
|
release = self.release()
|
||||||
|
attachments = self.inspect(release)
|
||||||
|
require(release["id"] == release_id and release["draft"], "Draft changed or became public; refusing mutation")
|
||||||
|
self.check_tag()
|
||||||
|
return attachments
|
||||||
|
|
||||||
|
def publish(self, notes):
|
||||||
|
self.check_tag()
|
||||||
|
release = self.release()
|
||||||
|
if release is None:
|
||||||
|
self.check_tag()
|
||||||
|
release = self.api.request("POST", self.base + "/releases", {
|
||||||
|
"tag_name": self.tag, "target_commitish": self.commit,
|
||||||
|
"name": self.tag, "body": notes + "\n\n" + self.marker,
|
||||||
|
"draft": True, "prerelease": False,
|
||||||
|
})
|
||||||
|
attachments = self.inspect(release)
|
||||||
|
if not release["draft"]:
|
||||||
|
self.verify_complete(attachments)
|
||||||
|
self.check_tag()
|
||||||
|
print("Published release already matches all four assets; no changes made.")
|
||||||
|
return
|
||||||
|
|
||||||
|
release_id = release["id"]
|
||||||
|
path = self.base + f"/releases/{release_id}/assets"
|
||||||
|
# Plan all conflicts before changing anything. Unknown attachments always fail closed.
|
||||||
|
replace = [name for name, attachment in attachments.items()
|
||||||
|
if not self.matches(attachment, self.assets[name])]
|
||||||
|
for name, asset in self.assets.items():
|
||||||
|
if name in attachments and name not in replace:
|
||||||
|
continue
|
||||||
|
current = self.guard_draft(release_id)
|
||||||
|
if name in current:
|
||||||
|
require(name in replace and current[name]["id"] == attachments[name]["id"],
|
||||||
|
"Attachment changed concurrently; rerun after inspection")
|
||||||
|
self.api.request("DELETE", path + f'/{current[name]["id"]}')
|
||||||
|
self.guard_draft(release_id)
|
||||||
|
self.api.upload(path, asset)
|
||||||
|
current = self.guard_draft(release_id)
|
||||||
|
self.verify_complete(current)
|
||||||
|
# Hashing can take time: check draft status and the live tag again immediately before PATCH.
|
||||||
|
latest = self.guard_draft(release_id)
|
||||||
|
require(set(latest) == set(current) and all(
|
||||||
|
latest[name]["id"] == item["id"] and latest[name]["size"] == item["size"]
|
||||||
|
for name, item in current.items()
|
||||||
|
), "Attachments changed during verification")
|
||||||
|
self.api.request("PATCH", self.base + f"/releases/{release_id}", {"draft": False})
|
||||||
|
published = self.release()
|
||||||
|
require(published and published.get("draft") is False, "Publication was not confirmed; rerun safely")
|
||||||
|
self.verify_complete(self.inspect(published))
|
||||||
|
self.check_tag()
|
||||||
|
print("Published release verified: four attachments with matching sizes and SHA-256.")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("command", choices=["check", "publish"])
|
||||||
|
parser.add_argument("--source", type=Path, default=Path.cwd(), help="Tagged Git checkout (default: cwd)")
|
||||||
|
parser.add_argument("--assets", type=Path, help="Directory containing only the expected packages")
|
||||||
|
parser.add_argument("--platform", choices=["all", "windows", "linux"], default="all", help="check only")
|
||||||
|
parser.add_argument("--tag", default=os.environ.get("RELEASE_TAG"))
|
||||||
|
parser.add_argument("--commit", default=os.environ.get("RELEASE_COMMIT"), help="Full event SHA; peeled before comparison")
|
||||||
|
parser.add_argument("--repository", default=os.environ.get("GITEA_REPOSITORY"))
|
||||||
|
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL"), help="Gitea API base, ending /api/v1")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
try:
|
||||||
|
version, commit = local_identity(args.source, args.tag, args.commit)
|
||||||
|
require(args.command != "publish" or (args.assets and args.platform == "all"),
|
||||||
|
"publish requires --assets with all four packages")
|
||||||
|
assets = local_assets(args.assets, expected_names(version, args.platform)) if args.assets else None
|
||||||
|
require(args.api_url, "Supply --api-url or GITEA_API_URL")
|
||||||
|
token = os.environ.get("GITEA_TOKEN", "") if args.command == "publish" else ""
|
||||||
|
require(args.command != "publish" or token, "publish requires GITEA_TOKEN")
|
||||||
|
api = Gitea(args.api_url, token)
|
||||||
|
server_version = api.check_version()
|
||||||
|
if args.command == "check":
|
||||||
|
print(f"Validated {args.tag} at {commit}; Gitea {server_version}; "
|
||||||
|
f"{len(assets) if assets else 0} assets checked.")
|
||||||
|
else:
|
||||||
|
Publisher(api, args.repository, args.tag, commit, assets).publish(release_notes(args.source, version))
|
||||||
|
return 0
|
||||||
|
except (ReleaseError, OSError, ValueError, KeyError, TypeError, urllib.error.URLError) as error:
|
||||||
|
# Network errors can embed signed URLs; report only their type.
|
||||||
|
message = str(error) if isinstance(error, ReleaseError) else type(error).__name__
|
||||||
|
print("Release failed: " + message, file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
Unicode true
|
||||||
|
!include "MUI2.nsh"
|
||||||
|
|
||||||
|
Name "Rusty Path of Building"
|
||||||
|
OutFile "${OUTPUT}"
|
||||||
|
RequestExecutionLevel user
|
||||||
|
InstallDir "$LOCALAPPDATA\Programs\Rusty Path of Building"
|
||||||
|
SetCompressor /SOLID lzma
|
||||||
|
|
||||||
|
!define APP "rusty-path-of-building.exe"
|
||||||
|
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\RustyPathOfBuilding"
|
||||||
|
!insertmacro MUI_PAGE_DIRECTORY
|
||||||
|
!insertmacro MUI_PAGE_INSTFILES
|
||||||
|
!insertmacro MUI_UNPAGE_CONFIRM
|
||||||
|
!insertmacro MUI_UNPAGE_INSTFILES
|
||||||
|
!insertmacro MUI_LANGUAGE "English"
|
||||||
|
|
||||||
|
Function .onInit
|
||||||
|
SetRegView 64
|
||||||
|
ReadRegStr $0 HKCU "${UNINSTALL_KEY}" "InstallLocation"
|
||||||
|
StrCmp $0 "" +2
|
||||||
|
StrCpy $INSTDIR $0
|
||||||
|
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"
|
||||||
|
SetOutPath "$INSTDIR"
|
||||||
|
WriteUninstaller "$INSTDIR\Uninstall.exe"
|
||||||
|
CreateShortcut "$SMPROGRAMS\Rusty Path of Building.lnk" "$INSTDIR\${APP}"
|
||||||
|
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Rusty Path of Building"
|
||||||
|
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
|
||||||
|
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\${APP}"
|
||||||
|
WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
|
||||||
|
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'
|
||||||
|
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
|
||||||
|
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
|
||||||
|
SectionEnd
|
||||||
|
|
||||||
|
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 "$INSTDIR\Uninstall.exe"
|
||||||
|
RMDir "$INSTDIR"
|
||||||
|
DeleteRegKey HKCU "${UNINSTALL_KEY}"
|
||||||
|
SectionEnd
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
pre-release-replacements = [
|
pre-release-replacements = [
|
||||||
{file="CHANGELOG.md", search="Unreleased", replace="{{version}}"},
|
{file="CHANGELOG.md", search="Unreleased", replace="{{version}}"},
|
||||||
{file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1},
|
{file="CHANGELOG.md", search="\\.\\.\\.main", replace="...{{tag_name}}", exactly=1},
|
||||||
{file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}"},
|
{file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}"},
|
||||||
{file="CHANGELOG.md", search="<!-- next-header -->", replace="<!-- next-header -->\n\n## [Unreleased] - ReleaseDate", exactly=1},
|
{file="CHANGELOG.md", search="<!-- next-header -->", replace="<!-- next-header -->\n\n## [Unreleased] - ReleaseDate", exactly=1},
|
||||||
{file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/{{tag_name}}...HEAD", exactly=1},
|
{file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/{{tag_name}}...main", exactly=1},
|
||||||
]
|
]
|
||||||
+164
-50
@@ -1,6 +1,7 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
args::Game,
|
args::{Args, Game},
|
||||||
batcher::build_render_job,
|
batcher::build_render_job,
|
||||||
|
chooser::Chooser,
|
||||||
dpi::{PhysicalPoint, PhysicalSize},
|
dpi::{PhysicalPoint, PhysicalSize},
|
||||||
fonts::{FontData, FontDefinitions, Fonts},
|
fonts::{FontData, FontDefinitions, Fonts},
|
||||||
gfx::GraphicsContext,
|
gfx::GraphicsContext,
|
||||||
@@ -9,7 +10,7 @@ use crate::{
|
|||||||
renderer::{RenderJob, textures::TextureManager},
|
renderer::{RenderJob, textures::TextureManager},
|
||||||
stage::{ActiveStage, StageEvent, StageTransition},
|
stage::{ActiveStage, StageEvent, StageTransition},
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::{Context, Result};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::{cell::RefCell, path::PathBuf, rc::Rc};
|
use std::{cell::RefCell, path::PathBuf, rc::Rc};
|
||||||
use winit::{
|
use winit::{
|
||||||
@@ -25,57 +26,107 @@ struct FrameOutput {
|
|||||||
pub request_redraw: bool,
|
pub request_redraw: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct GameLaunch {
|
||||||
|
game: Game,
|
||||||
|
script_dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct App {
|
pub struct App {
|
||||||
gfx_context: Option<GraphicsContext>,
|
gfx_context: Option<GraphicsContext>,
|
||||||
fonts: Rc<RefCell<Fonts>>,
|
fonts: Rc<RefCell<Fonts>>,
|
||||||
texture_manager: Rc<RefCell<TextureManager>>,
|
texture_manager: Rc<RefCell<TextureManager>>,
|
||||||
stage: ActiveStage,
|
stage: ActiveStage,
|
||||||
game: Game,
|
launch: Option<GameLaunch>,
|
||||||
script_dir: PathBuf,
|
custom_script_dir: Option<PathBuf>,
|
||||||
|
import_url: Option<String>,
|
||||||
|
pending_transition: Option<StageTransition>,
|
||||||
needs_reconfigure: bool,
|
needs_reconfigure: bool,
|
||||||
|
stage_changed: bool,
|
||||||
|
is_focused: bool,
|
||||||
|
is_hovered: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub fn new(game: Game, custom_script_dir: Option<PathBuf>) -> Result<Self> {
|
pub fn new(args: Args, custom_script_dir: Option<PathBuf>) -> Result<Self> {
|
||||||
let uses_custom_script_dir = custom_script_dir.is_some();
|
|
||||||
let script_dir = custom_script_dir.unwrap_or_else(|| game.script_dir());
|
|
||||||
|
|
||||||
let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions())));
|
let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions())));
|
||||||
let texture_manager = Rc::new(RefCell::new(TextureManager::new()));
|
let texture_manager = Rc::new(RefCell::new(TextureManager::new()));
|
||||||
|
let stage = ActiveStage::Chooser(Box::new(Chooser::new(Rc::clone(&fonts))));
|
||||||
let stage = if uses_custom_script_dir {
|
let mut app = Self {
|
||||||
// skip installer if custom script dir is provided. used for local testing.
|
|
||||||
let pob =
|
|
||||||
PathOfBuilding::new(&script_dir, Rc::clone(&fonts), Rc::clone(&texture_manager))?;
|
|
||||||
ActiveStage::Main(pob)
|
|
||||||
} else {
|
|
||||||
ActiveStage::Startup(Installer::new(game, Rc::clone(&fonts)))
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
gfx_context: None,
|
gfx_context: None,
|
||||||
fonts,
|
fonts,
|
||||||
texture_manager,
|
texture_manager,
|
||||||
stage,
|
stage,
|
||||||
game,
|
launch: None,
|
||||||
script_dir,
|
custom_script_dir,
|
||||||
|
import_url: args.import_url,
|
||||||
|
pending_transition: None,
|
||||||
needs_reconfigure: true,
|
needs_reconfigure: true,
|
||||||
})
|
stage_changed: true,
|
||||||
|
is_focused: true,
|
||||||
|
is_hovered: true,
|
||||||
|
};
|
||||||
|
if let Some(game) = args.game {
|
||||||
|
app.start_game(game)?;
|
||||||
|
}
|
||||||
|
Ok(app)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_game(&mut self, game: Game) -> Result<()> {
|
||||||
|
anyhow::ensure!(self.launch.is_none(), "A game has already been started");
|
||||||
|
let launch = GameLaunch {
|
||||||
|
game,
|
||||||
|
script_dir: self
|
||||||
|
.custom_script_dir
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| game.script_dir()),
|
||||||
|
};
|
||||||
|
let stage = if self.custom_script_dir.is_some() {
|
||||||
|
// Local scripts bypass installation, but only after a game is selected.
|
||||||
|
ActiveStage::Main(self.create_pob(&launch)?)
|
||||||
|
} else {
|
||||||
|
ActiveStage::Startup(Installer::new(game, Rc::clone(&self.fonts)))
|
||||||
|
};
|
||||||
|
self.launch = Some(launch);
|
||||||
|
self.set_stage(stage);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_pob(&self, launch: &GameLaunch) -> Result<PathOfBuilding> {
|
||||||
|
PathOfBuilding::new(
|
||||||
|
&launch.script_dir,
|
||||||
|
Rc::clone(&self.fonts),
|
||||||
|
Rc::clone(&self.texture_manager),
|
||||||
|
self.import_url.clone(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_stage(&mut self, stage: ActiveStage) {
|
||||||
|
self.stage = stage;
|
||||||
|
if let Some(gfx) = &self.gfx_context {
|
||||||
|
gfx.window.set_title(self.window_identity().0);
|
||||||
|
self.stage.set_window(Arc::clone(&gfx.window));
|
||||||
|
}
|
||||||
|
self.handle_event(StageEvent::FocusChanged(self.is_focused));
|
||||||
|
self.handle_event(StageEvent::HoverChanged(self.is_hovered));
|
||||||
|
self.stage_changed = true;
|
||||||
|
self.request_redraw();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
fn update(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||||
let transition = self.stage.update();
|
let transition = match self.pending_transition.take() {
|
||||||
if let Some(transition) = transition? {
|
Some(transition) => Some(transition),
|
||||||
|
None => self.stage.update()?,
|
||||||
|
};
|
||||||
|
if let Some(transition) = transition {
|
||||||
match transition {
|
match transition {
|
||||||
|
StageTransition::StartGame(game) => self.start_game(game)?,
|
||||||
StageTransition::ToMain => {
|
StageTransition::ToMain => {
|
||||||
self.stage = ActiveStage::Main(PathOfBuilding::new(
|
let launch = self
|
||||||
&self.script_dir,
|
.launch
|
||||||
Rc::clone(&self.fonts),
|
.as_ref()
|
||||||
Rc::clone(&self.texture_manager),
|
.context("No game selected for Lua startup")?;
|
||||||
)?);
|
let pob = self.create_pob(launch)?;
|
||||||
if let Some(gfx) = &self.gfx_context {
|
self.set_stage(ActiveStage::Main(pob));
|
||||||
self.stage.set_window(Arc::clone(&gfx.window));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
StageTransition::ToShutdown => {
|
StageTransition::ToShutdown => {
|
||||||
self.handle_event(StageEvent::Exit);
|
self.handle_event(StageEvent::Exit);
|
||||||
@@ -116,16 +167,27 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn handle_event(&mut self, event: StageEvent) {
|
fn handle_event(&mut self, event: StageEvent) {
|
||||||
if let Err(err) = self.stage.handle_event(event) {
|
match self.stage.handle_event(event) {
|
||||||
log::error!("{err}");
|
Ok(Some(transition)) => {
|
||||||
|
self.pending_transition.get_or_insert(transition);
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(err) => log::error!("{err}"),
|
||||||
|
}
|
||||||
|
// The chooser sleeps between events, including focus loss and cursor exit.
|
||||||
|
self.request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_identity(&self) -> (&'static str, &'static str) {
|
||||||
|
match self.launch.as_ref().map(|launch| launch.game) {
|
||||||
|
None => ("Rusty Path of Building", "rusty-path-of-building"),
|
||||||
|
Some(Game::Poe1) => ("Path of Building 1", "rusty-path-of-building-1"),
|
||||||
|
Some(Game::Poe2) => ("Path of Building 2", "rusty-path-of-building-2"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||||
let (title, _app_id) = match self.game {
|
let (title, _app_id) = self.window_identity();
|
||||||
Game::Poe1 => ("Path of Building 1", "rusty-path-of-building-1"),
|
|
||||||
Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"),
|
|
||||||
};
|
|
||||||
|
|
||||||
#[allow(unused_mut)]
|
#[allow(unused_mut)]
|
||||||
let mut window_attributes = Window::default_attributes()
|
let mut window_attributes = Window::default_attributes()
|
||||||
@@ -185,13 +247,19 @@ impl ApplicationHandler<GraphicsContext> for App {
|
|||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
profiling::scope!("RedrawRequested");
|
profiling::scope!("RedrawRequested");
|
||||||
|
|
||||||
|
if event_loop.exiting() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if let Err(err) = self.update(event_loop) {
|
if let Err(err) = self.update(event_loop) {
|
||||||
log::error!("{err}");
|
log::error!("{err}");
|
||||||
event_loop.exit();
|
event_loop.exit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if event_loop.exiting() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let mut inhibit_elision = false;
|
let mut inhibit_elision = std::mem::take(&mut self.stage_changed);
|
||||||
if self.needs_reconfigure {
|
if self.needs_reconfigure {
|
||||||
if let Some(ref mut gfx) = self.gfx_context {
|
if let Some(ref mut gfx) = self.gfx_context {
|
||||||
let size = gfx.window.inner_size();
|
let size = gfx.window.inner_size();
|
||||||
@@ -236,20 +304,17 @@ impl ApplicationHandler<GraphicsContext> for App {
|
|||||||
size.width,
|
size.width,
|
||||||
size.height,
|
size.height,
|
||||||
)));
|
)));
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::Focused(focused) => {
|
WindowEvent::Focused(focused) => {
|
||||||
|
self.is_focused = focused;
|
||||||
self.handle_event(StageEvent::FocusChanged(focused));
|
self.handle_event(StageEvent::FocusChanged(focused));
|
||||||
if focused {
|
if !focused {
|
||||||
self.request_redraw();
|
|
||||||
} else {
|
|
||||||
// Clear inputs on lost focus to avoid "stuck" keys on Wayland systems.
|
// Clear inputs on lost focus to avoid "stuck" keys on Wayland systems.
|
||||||
self.stage.clear_pressed();
|
self.stage.clear_pressed();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||||
self.handle_event(StageEvent::ScaleFactorChanged(scale_factor));
|
self.handle_event(StageEvent::ScaleFactorChanged(scale_factor));
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::KeyboardInput { event, .. } => {
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
let state = event.state;
|
let state = event.state;
|
||||||
@@ -274,13 +339,11 @@ impl ApplicationHandler<GraphicsContext> for App {
|
|||||||
self.handle_event(event);
|
self.handle_event(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::ModifiersChanged(modifiers) => {
|
WindowEvent::ModifiersChanged(modifiers) => {
|
||||||
self.handle_event(StageEvent::ModifiersChanged {
|
self.handle_event(StageEvent::ModifiersChanged {
|
||||||
state: modifiers.state(),
|
state: modifiers.state(),
|
||||||
});
|
});
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::MouseInput { state, button, .. } => {
|
WindowEvent::MouseInput { state, button, .. } => {
|
||||||
let event = match state {
|
let event = match state {
|
||||||
@@ -288,18 +351,17 @@ impl ApplicationHandler<GraphicsContext> for App {
|
|||||||
ElementState::Released => StageEvent::MouseUp { button },
|
ElementState::Released => StageEvent::MouseUp { button },
|
||||||
};
|
};
|
||||||
self.handle_event(event);
|
self.handle_event(event);
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::CursorMoved { position, .. } => {
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
|
let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
|
||||||
self.handle_event(StageEvent::MouseMoved { pos });
|
self.handle_event(StageEvent::MouseMoved { pos });
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::CursorEntered { .. } => {
|
WindowEvent::CursorEntered { .. } => {
|
||||||
|
self.is_hovered = true;
|
||||||
self.handle_event(StageEvent::HoverChanged(true));
|
self.handle_event(StageEvent::HoverChanged(true));
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
WindowEvent::CursorLeft { .. } => {
|
WindowEvent::CursorLeft { .. } => {
|
||||||
|
self.is_hovered = false;
|
||||||
self.handle_event(StageEvent::HoverChanged(false));
|
self.handle_event(StageEvent::HoverChanged(false));
|
||||||
}
|
}
|
||||||
WindowEvent::MouseWheel { delta, .. } => {
|
WindowEvent::MouseWheel { delta, .. } => {
|
||||||
@@ -310,7 +372,6 @@ impl ApplicationHandler<GraphicsContext> for App {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
self.handle_event(StageEvent::MouseWheel { delta });
|
self.handle_event(StageEvent::MouseWheel { delta });
|
||||||
self.request_redraw();
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@@ -381,3 +442,56 @@ fn load_icon() -> Option<winit::window::Icon> {
|
|||||||
let (width, height) = image.dimensions();
|
let (width, height) = image.dimensions();
|
||||||
winit::window::Icon::from_rgba(image.into_raw(), width, height).ok()
|
winit::window::Icon::from_rgba(image.into_raw(), width, height).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use winit::keyboard::{Key, NamedKey};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_defers_custom_scripts_and_allows_cancellation() {
|
||||||
|
for script_dir in [None, Some(PathBuf::from("missing-launch-script"))] {
|
||||||
|
let mut app = App::new(
|
||||||
|
Args {
|
||||||
|
game: None,
|
||||||
|
import_url: None,
|
||||||
|
},
|
||||||
|
script_dir,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(app.stage, ActiveStage::Chooser(_)));
|
||||||
|
assert!(app.launch.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
app.window_identity(),
|
||||||
|
("Rusty Path of Building", "rusty-path-of-building")
|
||||||
|
);
|
||||||
|
assert!(app.stage.can_exit());
|
||||||
|
|
||||||
|
app.handle_event(StageEvent::KeyDown {
|
||||||
|
key: Key::Named(NamedKey::Escape),
|
||||||
|
});
|
||||||
|
let transition = app
|
||||||
|
.pending_transition
|
||||||
|
.take()
|
||||||
|
.or_else(|| app.stage.update().unwrap());
|
||||||
|
assert!(matches!(transition, Some(StageTransition::ToShutdown)));
|
||||||
|
assert!(app.launch.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_games_bypass_selection_and_report_invalid_custom_scripts() {
|
||||||
|
for game in [Game::Poe1, Game::Poe2] {
|
||||||
|
assert!(
|
||||||
|
App::new(
|
||||||
|
Args {
|
||||||
|
game: Some(game),
|
||||||
|
import_url: None
|
||||||
|
},
|
||||||
|
Some(PathBuf::from("missing-launch-script")),
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+54
-3
@@ -7,9 +7,9 @@ use std::path::PathBuf;
|
|||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(version, about, long_about = None)]
|
#[command(version, about, long_about = None)]
|
||||||
pub struct Args {
|
pub struct Args {
|
||||||
/// Used to determine which PoB to start. (PoE1 or PoE2)
|
/// Which PoB to start. Opens the game chooser when omitted.
|
||||||
#[arg(value_enum)]
|
#[arg(value_enum)]
|
||||||
pub game: Game,
|
pub game: Option<Game>,
|
||||||
|
|
||||||
/// Specify a build to load on start using a URL. (Optional)
|
/// Specify a build to load on start using a URL. (Optional)
|
||||||
#[arg(
|
#[arg(
|
||||||
@@ -19,7 +19,7 @@ pub struct Args {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Enum representing the game version.
|
/// Enum representing the game version.
|
||||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||||
pub enum Game {
|
pub enum Game {
|
||||||
/// Path of Exile 1
|
/// Path of Exile 1
|
||||||
#[value(name = "poe1")]
|
#[value(name = "poe1")]
|
||||||
@@ -45,3 +45,54 @@ impl Game {
|
|||||||
self.data_dir()
|
self.data_dir()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use clap::error::ErrorKind;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_arguments_requests_game_selection() {
|
||||||
|
let args = Args::try_parse_from(["rpob"]).unwrap();
|
||||||
|
assert!(args.game.is_none());
|
||||||
|
assert!(args.import_url.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_games_accept_an_optional_import_url() {
|
||||||
|
for game in ["poe1", "poe2"] {
|
||||||
|
for import_url in [None, Some("pob://pobbin/example")] {
|
||||||
|
let args =
|
||||||
|
Args::try_parse_from(["rpob", game].into_iter().chain(import_url)).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
(game, args.game),
|
||||||
|
("poe1", Some(Game::Poe1)) | ("poe2", Some(Game::Poe2))
|
||||||
|
));
|
||||||
|
assert_eq!(args.import_url.as_deref(), import_url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_games_and_url_only_still_fail() {
|
||||||
|
for game in ["poe3", "pob://pobbin/example"] {
|
||||||
|
let error = Args::try_parse_from(["rpob", game]).unwrap_err();
|
||||||
|
assert_eq!(error.kind(), ErrorKind::InvalidValue);
|
||||||
|
assert_eq!(error.exit_code(), 2);
|
||||||
|
}
|
||||||
|
assert!(Args::try_parse_from(["rpob", "poe1", "url", "extra"]).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn help_and_version_keep_successful_cli_exit_codes() {
|
||||||
|
for (flag, kind) in [
|
||||||
|
("--help", ErrorKind::DisplayHelp),
|
||||||
|
("--version", ErrorKind::DisplayVersion),
|
||||||
|
] {
|
||||||
|
let error = Args::try_parse_from(["rpob", flag]).unwrap_err();
|
||||||
|
assert_eq!(error.kind(), kind);
|
||||||
|
assert_eq!(error.exit_code(), 0);
|
||||||
|
assert!(!error.use_stderr());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+661
@@ -0,0 +1,661 @@
|
|||||||
|
use std::{cell::RefCell, rc::Rc, sync::Arc};
|
||||||
|
|
||||||
|
use parley::{FontFamily, FontFamilyName, GenericFamily};
|
||||||
|
use winit::{keyboard::NamedKey, window::Window};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
args::Game,
|
||||||
|
color::Srgba,
|
||||||
|
dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint},
|
||||||
|
draw_commands::DrawCommandRecorder,
|
||||||
|
fonts::{FontStyle, Fonts, LayoutJob},
|
||||||
|
input::{InputState, Key, MouseButton},
|
||||||
|
stage::{StageEvent, StageFrameOutput, StageTransition},
|
||||||
|
window::WindowState,
|
||||||
|
};
|
||||||
|
|
||||||
|
impl Game {
|
||||||
|
const ALL: [Self; 2] = [Self::Poe1, Self::Poe2];
|
||||||
|
|
||||||
|
fn other(self) -> Self {
|
||||||
|
match self {
|
||||||
|
Self::Poe1 => Self::Poe2,
|
||||||
|
Self::Poe2 => Self::Poe1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Poe1 => "Path of Exile 1",
|
||||||
|
Self::Poe2 => "Path of Exile 2",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All drawing and hit testing share the same logical coordinates.
|
||||||
|
struct ChooserLayout {
|
||||||
|
center_x: f32,
|
||||||
|
top: f32,
|
||||||
|
scale: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChooserLayout {
|
||||||
|
fn new(size: LogicalSize<f32>) -> Self {
|
||||||
|
let scale = (size.width / 520.0).min(size.height / 380.0).min(1.0);
|
||||||
|
Self {
|
||||||
|
center_x: size.width / 2.0,
|
||||||
|
top: (size.height - 324.0 * scale) / 2.0,
|
||||||
|
scale,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn button(&self, choice: Game) -> LogicalRect<f32> {
|
||||||
|
let offset = match choice {
|
||||||
|
Game::Poe1 => 96.0,
|
||||||
|
Game::Poe2 => 184.0,
|
||||||
|
};
|
||||||
|
LogicalRect::from_origin_and_size(
|
||||||
|
LogicalPoint::new(self.center_x - 220.0 * self.scale, self.y(offset)),
|
||||||
|
LogicalSize::new(440.0 * self.scale, 72.0 * self.scale),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hit_test(&self, pos: LogicalPoint<f32>) -> Option<Game> {
|
||||||
|
Game::ALL
|
||||||
|
.into_iter()
|
||||||
|
.find(|&choice| self.button(choice).contains(pos))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn y(&self, offset: f32) -> f32 {
|
||||||
|
self.top + offset * self.scale
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Chooser {
|
||||||
|
fonts: Rc<RefCell<Fonts>>,
|
||||||
|
window_state: WindowState,
|
||||||
|
input: InputState,
|
||||||
|
cursor: Option<PhysicalPoint<f32>>,
|
||||||
|
focused: Game,
|
||||||
|
hovered: Option<Game>,
|
||||||
|
mouse_armed: Option<Game>,
|
||||||
|
key_armed: Option<(Key, Game)>,
|
||||||
|
pending: Option<StageTransition>,
|
||||||
|
finished: bool,
|
||||||
|
previous_frame_hash: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Chooser {
|
||||||
|
pub(crate) fn new(fonts: Rc<RefCell<Fonts>>) -> Self {
|
||||||
|
Self {
|
||||||
|
fonts,
|
||||||
|
window_state: WindowState::default(),
|
||||||
|
input: InputState::default(),
|
||||||
|
cursor: None,
|
||||||
|
focused: Game::Poe1,
|
||||||
|
hovered: None,
|
||||||
|
mouse_armed: None,
|
||||||
|
key_armed: None,
|
||||||
|
pending: None,
|
||||||
|
finished: false,
|
||||||
|
previous_frame_hash: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||||
|
Ok(self.pending.take())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
||||||
|
let size = self.window_state.logical_size();
|
||||||
|
let layout = ChooserLayout::new(size);
|
||||||
|
let mut recorder = DrawCommandRecorder::default();
|
||||||
|
recorder.reset();
|
||||||
|
recorder.set_viewport_from_size(size);
|
||||||
|
|
||||||
|
// A minimized/zero-sized surface has neither visible content nor hit targets.
|
||||||
|
if size.width > 0.0 && size.height > 0.0 {
|
||||||
|
recorder.set_draw_color(Srgba::from_rgb(18, 20, 25));
|
||||||
|
recorder.draw_image(LogicalRect::from_size(size), None, None, 0);
|
||||||
|
|
||||||
|
let gold = Srgba::from_rgb(218, 185, 119);
|
||||||
|
let muted = Srgba::from_rgb(180, 183, 191);
|
||||||
|
self.draw_text(
|
||||||
|
&mut recorder,
|
||||||
|
"Path of Building",
|
||||||
|
LogicalPoint::new(layout.center_x, layout.y(0.0)),
|
||||||
|
34.0 * layout.scale,
|
||||||
|
gold,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
self.draw_text(
|
||||||
|
&mut recorder,
|
||||||
|
"Choose your game",
|
||||||
|
LogicalPoint::new(layout.center_x, layout.y(48.0)),
|
||||||
|
20.0 * layout.scale,
|
||||||
|
muted,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
for choice in Game::ALL {
|
||||||
|
let rect = layout.button(choice);
|
||||||
|
let focused = self.window_state.is_focused && self.focused == choice;
|
||||||
|
let hovered = self.hovered == Some(choice);
|
||||||
|
let pressed = self.mouse_armed == Some(choice)
|
||||||
|
|| self.key_armed.as_ref().is_some_and(|(_, c)| *c == choice);
|
||||||
|
|
||||||
|
recorder.set_draw_color(if focused {
|
||||||
|
gold
|
||||||
|
} else if hovered {
|
||||||
|
Srgba::from_rgb(165, 172, 189)
|
||||||
|
} else {
|
||||||
|
Srgba::from_rgb(83, 86, 98)
|
||||||
|
});
|
||||||
|
recorder.draw_image(rect, None, None, 0);
|
||||||
|
recorder.set_draw_color(if pressed {
|
||||||
|
Srgba::from_rgb(88, 67, 36)
|
||||||
|
} else if hovered {
|
||||||
|
Srgba::from_rgb(47, 51, 62)
|
||||||
|
} else if focused {
|
||||||
|
Srgba::from_rgb(48, 43, 34)
|
||||||
|
} else {
|
||||||
|
Srgba::from_rgb(31, 34, 42)
|
||||||
|
});
|
||||||
|
recorder.draw_image(
|
||||||
|
rect.inflate(-2.0 * layout.scale, -2.0 * layout.scale),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
self.draw_text(
|
||||||
|
&mut recorder,
|
||||||
|
choice.label(),
|
||||||
|
LogicalPoint::new(layout.center_x, rect.center().y - 17.0 * layout.scale),
|
||||||
|
28.0 * layout.scale,
|
||||||
|
Srgba::WHITE,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (text, offset) in [
|
||||||
|
("Tab / arrows to choose Enter / Space to start", 280.0),
|
||||||
|
("Esc to quit", 304.0),
|
||||||
|
] {
|
||||||
|
self.draw_text(
|
||||||
|
&mut recorder,
|
||||||
|
text,
|
||||||
|
LogicalPoint::new(layout.center_x, layout.y(offset)),
|
||||||
|
15.0 * layout.scale,
|
||||||
|
muted,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (hash, layers) = recorder.finish();
|
||||||
|
let can_elide = self.previous_frame_hash == Some(hash);
|
||||||
|
self.previous_frame_hash = Some(hash);
|
||||||
|
Ok(StageFrameOutput {
|
||||||
|
draw_commands: layers.values().flatten().copied().collect(),
|
||||||
|
can_elide,
|
||||||
|
request_redraw: false,
|
||||||
|
scale_factor: self.window_state.scale_factor(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_event(
|
||||||
|
&mut self,
|
||||||
|
event: StageEvent,
|
||||||
|
) -> anyhow::Result<Option<StageTransition>> {
|
||||||
|
match event {
|
||||||
|
StageEvent::Exit
|
||||||
|
| StageEvent::KeyDown {
|
||||||
|
key: Key::Named(NamedKey::Escape),
|
||||||
|
} => {
|
||||||
|
// Cancellation supersedes a selection not yet consumed by update.
|
||||||
|
if !self.finished || self.pending.is_some() {
|
||||||
|
self.pending = Some(StageTransition::ToShutdown);
|
||||||
|
self.finished = true;
|
||||||
|
self.clear_pressed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::Resized(size) => {
|
||||||
|
self.window_state.size = size;
|
||||||
|
self.disarm();
|
||||||
|
}
|
||||||
|
StageEvent::ScaleFactorChanged(factor) => {
|
||||||
|
let factor = factor as f32;
|
||||||
|
if factor.is_finite() && factor > 0.0 {
|
||||||
|
self.window_state.set_scale_factor(factor);
|
||||||
|
self.disarm();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::FocusChanged(focused) => {
|
||||||
|
self.window_state.is_focused = focused;
|
||||||
|
if !focused {
|
||||||
|
self.clear_pressed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::HoverChanged(hovered) => {
|
||||||
|
self.window_state.is_hovered = hovered;
|
||||||
|
if !hovered {
|
||||||
|
self.disarm();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ if self.finished || !self.window_state.is_focused => {}
|
||||||
|
StageEvent::KeyDown { key } => {
|
||||||
|
if !self.input.key_pressed(&key) {
|
||||||
|
self.input.set_key_pressed(&key, true);
|
||||||
|
match key {
|
||||||
|
Key::Named(
|
||||||
|
NamedKey::Tab
|
||||||
|
| NamedKey::ArrowLeft
|
||||||
|
| NamedKey::ArrowRight
|
||||||
|
| NamedKey::ArrowUp
|
||||||
|
| NamedKey::ArrowDown,
|
||||||
|
) => {
|
||||||
|
// With two choices, forward and reverse traversal both toggle.
|
||||||
|
self.focused = self.focused.other();
|
||||||
|
self.hovered = None;
|
||||||
|
self.mouse_armed = None;
|
||||||
|
self.key_armed = None;
|
||||||
|
}
|
||||||
|
Key::Named(NamedKey::Enter | NamedKey::Space)
|
||||||
|
if self.key_armed.is_none() =>
|
||||||
|
{
|
||||||
|
self.key_armed = Some((key, self.focused));
|
||||||
|
self.mouse_armed = None;
|
||||||
|
self.hovered = None;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::KeyUp { key } => {
|
||||||
|
self.input.set_key_pressed(&key, false);
|
||||||
|
if self
|
||||||
|
.key_armed
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(armed, _)| *armed == key)
|
||||||
|
{
|
||||||
|
let (_, choice) = self.key_armed.take().unwrap();
|
||||||
|
self.select(choice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::MouseMoved { pos } => {
|
||||||
|
self.cursor = Some(pos);
|
||||||
|
self.hovered = self.pointer_target();
|
||||||
|
if self.mouse_armed != self.hovered {
|
||||||
|
self.mouse_armed = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::MouseDown {
|
||||||
|
button: MouseButton::Left,
|
||||||
|
} => {
|
||||||
|
if !self.input.mouse_pressed(MouseButton::Left) {
|
||||||
|
self.input.set_mouse_pressed(MouseButton::Left, true);
|
||||||
|
self.mouse_armed = self.pointer_target();
|
||||||
|
self.key_armed = None;
|
||||||
|
self.hovered = self.mouse_armed;
|
||||||
|
if let Some(choice) = self.mouse_armed {
|
||||||
|
self.focused = choice;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StageEvent::MouseUp {
|
||||||
|
button: MouseButton::Left,
|
||||||
|
} => {
|
||||||
|
self.input.set_mouse_pressed(MouseButton::Left, false);
|
||||||
|
if let Some(choice) = self.mouse_armed.take()
|
||||||
|
&& self.pointer_target() == Some(choice)
|
||||||
|
{
|
||||||
|
self.select(choice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
// App advances the queued transition from update, outside event dispatch.
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_window(&mut self, window: Arc<Window>) {
|
||||||
|
self.window_state.set_window(window);
|
||||||
|
self.previous_frame_hash = None;
|
||||||
|
self.clear_pressed();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn clear_pressed(&mut self) {
|
||||||
|
self.input.clear_pressed();
|
||||||
|
self.disarm();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn disarm(&mut self) {
|
||||||
|
// Keep held-key/button tracking across pointer exit or layout changes so
|
||||||
|
// repeats cannot rearm a cancelled press before its matching release.
|
||||||
|
self.mouse_armed = None;
|
||||||
|
self.key_armed = None;
|
||||||
|
self.hovered = None;
|
||||||
|
self.cursor = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select(&mut self, choice: Game) {
|
||||||
|
if !self.finished {
|
||||||
|
self.pending = Some(StageTransition::StartGame(choice));
|
||||||
|
self.finished = true;
|
||||||
|
self.clear_pressed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pointer_target(&self) -> Option<Game> {
|
||||||
|
if !self.window_state.is_hovered || !self.window_state.is_focused {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let pos = self.cursor? / self.window_state.scale_factor();
|
||||||
|
ChooserLayout::new(self.window_state.logical_size()).hit_test(pos)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_text(
|
||||||
|
&self,
|
||||||
|
recorder: &mut DrawCommandRecorder,
|
||||||
|
text: &str,
|
||||||
|
center_top: LogicalPoint<f32>,
|
||||||
|
size: f32,
|
||||||
|
color: Srgba,
|
||||||
|
bold: bool,
|
||||||
|
) {
|
||||||
|
let mut job = LayoutJob::new(
|
||||||
|
FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)),
|
||||||
|
size,
|
||||||
|
size * 1.2,
|
||||||
|
None,
|
||||||
|
Some(if bold { 700.0 } else { 400.0 }),
|
||||||
|
FontStyle::Normal,
|
||||||
|
);
|
||||||
|
job.append(text, color);
|
||||||
|
let scale = self.window_state.scale_factor();
|
||||||
|
let layout = self.fonts.borrow_mut().layout(job, scale);
|
||||||
|
let origin = LogicalPoint::new(center_top.x - layout.width() / 2.0, center_top.y);
|
||||||
|
recorder.draw_glyphs(&layout, origin, true, scale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::{
|
||||||
|
dpi::PhysicalSize,
|
||||||
|
fonts::{FontData, FontDefinitions},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn chooser() -> Chooser {
|
||||||
|
let mut definitions = FontDefinitions::default();
|
||||||
|
definitions.font_data.insert(
|
||||||
|
"liberation-sans".to_owned(),
|
||||||
|
Arc::new(FontData::from_static(include_bytes!(
|
||||||
|
"../assets/fonts/LiberationSans-Regular.ttf"
|
||||||
|
))),
|
||||||
|
);
|
||||||
|
definitions
|
||||||
|
.generic_families
|
||||||
|
.insert(GenericFamily::SansSerif, vec!["Liberation Sans".to_owned()]);
|
||||||
|
let mut chooser = Chooser::new(Rc::new(RefCell::new(Fonts::new(definitions))));
|
||||||
|
send(
|
||||||
|
&mut chooser,
|
||||||
|
StageEvent::Resized(PhysicalSize::new(800, 600)),
|
||||||
|
);
|
||||||
|
chooser
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(chooser: &mut Chooser, event: StageEvent) {
|
||||||
|
assert!(chooser.handle_event(event).unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(chooser: &mut Chooser, key: NamedKey, down: bool) {
|
||||||
|
send(
|
||||||
|
chooser,
|
||||||
|
if down {
|
||||||
|
StageEvent::KeyDown {
|
||||||
|
key: Key::Named(key),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
StageEvent::KeyUp {
|
||||||
|
key: Key::Named(key),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_to(chooser: &mut Chooser, choice: Game) {
|
||||||
|
let pos = ChooserLayout::new(chooser.window_state.logical_size())
|
||||||
|
.button(choice)
|
||||||
|
.center()
|
||||||
|
* chooser.window_state.scale_factor();
|
||||||
|
send(chooser, StageEvent::MouseMoved { pos });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse(chooser: &mut Chooser, down: bool) {
|
||||||
|
send(
|
||||||
|
chooser,
|
||||||
|
if down {
|
||||||
|
StageEvent::MouseDown {
|
||||||
|
button: MouseButton::Left,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
StageEvent::MouseUp {
|
||||||
|
button: MouseButton::Left,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_keyboard_selects_both_games_once_on_release() {
|
||||||
|
for (choice, activation) in [(Game::Poe1, NamedKey::Enter), (Game::Poe2, NamedKey::Space)] {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
if choice == Game::Poe2 {
|
||||||
|
key(&mut chooser, NamedKey::Tab, true);
|
||||||
|
key(&mut chooser, NamedKey::Tab, true); // repeat does not cycle again
|
||||||
|
key(&mut chooser, NamedKey::Tab, false);
|
||||||
|
}
|
||||||
|
key(&mut chooser, activation, true);
|
||||||
|
key(&mut chooser, activation, true);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
key(&mut chooser, activation, false);
|
||||||
|
assert!(matches!(
|
||||||
|
(choice, chooser.update().unwrap()),
|
||||||
|
(Game::Poe1, Some(StageTransition::StartGame(Game::Poe1)))
|
||||||
|
| (Game::Poe2, Some(StageTransition::StartGame(Game::Poe2)))
|
||||||
|
));
|
||||||
|
key(&mut chooser, activation, true);
|
||||||
|
key(&mut chooser, activation, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_arrow_navigation_works_after_hover_and_cursor_departure() {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
for arrow in [
|
||||||
|
NamedKey::ArrowRight,
|
||||||
|
NamedKey::ArrowDown,
|
||||||
|
NamedKey::ArrowLeft,
|
||||||
|
NamedKey::ArrowUp,
|
||||||
|
] {
|
||||||
|
key(&mut chooser, arrow, true);
|
||||||
|
key(&mut chooser, arrow, false);
|
||||||
|
}
|
||||||
|
assert_eq!(chooser.focused, Game::Poe1);
|
||||||
|
send(&mut chooser, StageEvent::HoverChanged(false));
|
||||||
|
key(&mut chooser, NamedKey::Tab, true);
|
||||||
|
key(&mut chooser, NamedKey::Tab, false);
|
||||||
|
key(&mut chooser, NamedKey::Space, true);
|
||||||
|
key(&mut chooser, NamedKey::Space, false);
|
||||||
|
assert!(matches!(
|
||||||
|
chooser.update().unwrap(),
|
||||||
|
Some(StageTransition::StartGame(Game::Poe2))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_pointer_uses_display_scale_and_selects_each_game_once() {
|
||||||
|
for choice in Game::ALL {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
send(&mut chooser, StageEvent::ScaleFactorChanged(2.0));
|
||||||
|
move_to(&mut chooser, choice);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(matches!(
|
||||||
|
(choice, chooser.update().unwrap()),
|
||||||
|
(Game::Poe1, Some(StageTransition::StartGame(Game::Poe1)))
|
||||||
|
| (Game::Poe2, Some(StageTransition::StartGame(Game::Poe2)))
|
||||||
|
));
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_rejects_unarmed_mismatched_and_departed_clicks() {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
move_to(&mut chooser, Game::Poe2);
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
send(
|
||||||
|
&mut chooser,
|
||||||
|
StageEvent::MouseMoved {
|
||||||
|
pos: PhysicalPoint::new(0.0, 0.0),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
send(&mut chooser, StageEvent::HoverChanged(false));
|
||||||
|
send(&mut chooser, StageEvent::HoverChanged(true));
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_focus_loss_and_navigation_disarm_activation() {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
key(&mut chooser, NamedKey::Enter, true);
|
||||||
|
send(&mut chooser, StageEvent::FocusChanged(false));
|
||||||
|
key(&mut chooser, NamedKey::Space, true);
|
||||||
|
send(&mut chooser, StageEvent::FocusChanged(true));
|
||||||
|
key(&mut chooser, NamedKey::Enter, false);
|
||||||
|
key(&mut chooser, NamedKey::Space, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
|
||||||
|
key(&mut chooser, NamedKey::Enter, true);
|
||||||
|
key(&mut chooser, NamedKey::Tab, true);
|
||||||
|
key(&mut chooser, NamedKey::Enter, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
send(&mut chooser, StageEvent::FocusChanged(false));
|
||||||
|
send(&mut chooser, StageEvent::FocusChanged(true));
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_departure_and_resize_cannot_rearm_a_held_key() {
|
||||||
|
for event in [
|
||||||
|
StageEvent::HoverChanged(false),
|
||||||
|
StageEvent::Resized(PhysicalSize::new(640, 480)),
|
||||||
|
StageEvent::ScaleFactorChanged(1.5),
|
||||||
|
] {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
key(&mut chooser, NamedKey::Enter, true);
|
||||||
|
send(&mut chooser, event);
|
||||||
|
key(&mut chooser, NamedKey::Enter, true);
|
||||||
|
key(&mut chooser, NamedKey::Enter, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
key(&mut chooser, NamedKey::Enter, true);
|
||||||
|
key(&mut chooser, NamedKey::Enter, false);
|
||||||
|
assert!(matches!(
|
||||||
|
chooser.update().unwrap(),
|
||||||
|
Some(StageTransition::StartGame(Game::Poe1))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_escape_overrides_a_pending_game_and_stays_cancelled() {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
key(&mut chooser, NamedKey::Enter, true);
|
||||||
|
key(&mut chooser, NamedKey::Enter, false);
|
||||||
|
key(&mut chooser, NamedKey::Escape, true);
|
||||||
|
assert!(matches!(
|
||||||
|
chooser.update().unwrap(),
|
||||||
|
Some(StageTransition::ToShutdown)
|
||||||
|
));
|
||||||
|
key(&mut chooser, NamedKey::Space, true);
|
||||||
|
key(&mut chooser, NamedKey::Space, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_layout_fits_small_windows_and_zero_surfaces_are_inert() {
|
||||||
|
for size in [
|
||||||
|
LogicalSize::new(320.0, 240.0),
|
||||||
|
LogicalSize::new(800.0, 600.0),
|
||||||
|
] {
|
||||||
|
let layout = ChooserLayout::new(size);
|
||||||
|
let screen = LogicalRect::from_size(size);
|
||||||
|
for choice in Game::ALL {
|
||||||
|
let button = layout.button(choice);
|
||||||
|
assert!(screen.contains_box(&button));
|
||||||
|
assert_eq!(layout.hit_test(button.center()), Some(choice));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut chooser = chooser();
|
||||||
|
move_to(&mut chooser, Game::Poe1);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
send(&mut chooser, StageEvent::Resized(PhysicalSize::new(0, 0)));
|
||||||
|
mouse(&mut chooser, false);
|
||||||
|
assert!(chooser.update().unwrap().is_none());
|
||||||
|
let frame = chooser.frame().unwrap();
|
||||||
|
assert!(frame.draw_commands.is_empty());
|
||||||
|
assert!(!frame.request_redraw);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chooser_initial_and_interaction_frames_render_then_idle() {
|
||||||
|
let mut chooser = chooser();
|
||||||
|
let initial = chooser.frame().unwrap();
|
||||||
|
assert!(!initial.can_elide);
|
||||||
|
assert!(!initial.request_redraw);
|
||||||
|
assert!(
|
||||||
|
initial
|
||||||
|
.draw_commands
|
||||||
|
.iter()
|
||||||
|
.filter(|cmd| cmd.color == Srgba::WHITE)
|
||||||
|
.count()
|
||||||
|
> 20,
|
||||||
|
"both game labels must produce visible glyphs"
|
||||||
|
);
|
||||||
|
assert!(chooser.frame().unwrap().can_elide);
|
||||||
|
move_to(&mut chooser, Game::Poe2);
|
||||||
|
assert!(!chooser.frame().unwrap().can_elide);
|
||||||
|
assert!(chooser.frame().unwrap().can_elide);
|
||||||
|
mouse(&mut chooser, true);
|
||||||
|
let pressed = chooser.frame().unwrap();
|
||||||
|
assert!(!pressed.can_elide);
|
||||||
|
assert!(!pressed.request_redraw);
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -6,6 +6,7 @@ use winit::event_loop::EventLoop;
|
|||||||
mod app;
|
mod app;
|
||||||
mod args;
|
mod args;
|
||||||
mod batcher;
|
mod batcher;
|
||||||
|
mod chooser;
|
||||||
mod clipboard;
|
mod clipboard;
|
||||||
mod color;
|
mod color;
|
||||||
mod dpi;
|
mod dpi;
|
||||||
@@ -39,7 +40,7 @@ fn main() -> anyhow::Result<()> {
|
|||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
let script_dir = find_nearby_launch_script();
|
let script_dir = find_nearby_launch_script();
|
||||||
|
|
||||||
let mut app = App::new(args.game, script_dir)?;
|
let mut app = App::new(args, script_dir)?;
|
||||||
|
|
||||||
let event_loop = EventLoop::with_user_event().build()?;
|
let event_loop = EventLoop::with_user_event().build()?;
|
||||||
event_loop.run_app(&mut app)?;
|
event_loop.run_app(&mut app)?;
|
||||||
|
|||||||
+105
-7
@@ -1,11 +1,9 @@
|
|||||||
use clap::Parser;
|
|
||||||
use mlua::{
|
use mlua::{
|
||||||
AppDataRef, AppDataRefMut, Function, Lua, Result as LuaResult, Table, thread::ThreadStatus,
|
AppDataRef, AppDataRefMut, Function, Lua, Result as LuaResult, Table, thread::ThreadStatus,
|
||||||
};
|
};
|
||||||
use winit::window::Window;
|
use winit::window::Window;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
args::Args,
|
|
||||||
dpi::{PhysicalPoint, ScaleFactor},
|
dpi::{PhysicalPoint, ScaleFactor},
|
||||||
draw_commands::DrawCommandRecorder,
|
draw_commands::DrawCommandRecorder,
|
||||||
fonts::Fonts,
|
fonts::Fonts,
|
||||||
@@ -85,6 +83,7 @@ impl Context {
|
|||||||
/// Exposes API, forwards events to Path of Building's event handlers, and manages subscripts.
|
/// Exposes API, forwards events to Path of Building's event handlers, and manages subscripts.
|
||||||
pub struct PathOfBuilding {
|
pub struct PathOfBuilding {
|
||||||
lua: Lua,
|
lua: Lua,
|
||||||
|
import_url: Option<String>,
|
||||||
/// Hash of the previous frame's draw commands. Used to skip rerendering identical frames.
|
/// Hash of the previous frame's draw commands. Used to skip rerendering identical frames.
|
||||||
previous_layers_hash: u64,
|
previous_layers_hash: u64,
|
||||||
}
|
}
|
||||||
@@ -94,27 +93,32 @@ impl PathOfBuilding {
|
|||||||
script_dir: &Path,
|
script_dir: &Path,
|
||||||
fonts: Rc<RefCell<Fonts>>,
|
fonts: Rc<RefCell<Fonts>>,
|
||||||
texture_manager: Rc<RefCell<TextureManager>>,
|
texture_manager: Rc<RefCell<TextureManager>>,
|
||||||
|
import_url: Option<String>,
|
||||||
) -> anyhow::Result<Self> {
|
) -> anyhow::Result<Self> {
|
||||||
let ctx = Context::new(script_dir, fonts, texture_manager);
|
let ctx = Context::new(script_dir, fonts, texture_manager);
|
||||||
let lua = Self::create_lua(ctx, SubscriptManager::default())?;
|
let lua = Self::create_lua(ctx, SubscriptManager::default(), import_url.as_deref())?;
|
||||||
|
|
||||||
Self::launch(&lua, script_dir)?;
|
Self::launch(&lua, script_dir)?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
lua,
|
lua,
|
||||||
|
import_url,
|
||||||
previous_layers_hash: Default::default(),
|
previous_layers_hash: Default::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds a `Lua` state with package paths, context, and all API functions registered.
|
/// Builds a `Lua` state with package paths, context, and all API functions registered.
|
||||||
fn create_lua(ctx: Context, subscript_manager: SubscriptManager) -> LuaResult<Lua> {
|
fn create_lua(
|
||||||
|
ctx: Context,
|
||||||
|
subscript_manager: SubscriptManager,
|
||||||
|
import_url: Option<&str>,
|
||||||
|
) -> LuaResult<Lua> {
|
||||||
// `unsafe_new` needed to allow loading of C modules
|
// `unsafe_new` needed to allow loading of C modules
|
||||||
let lua = unsafe { Lua::unsafe_new() };
|
let lua = unsafe { Lua::unsafe_new() };
|
||||||
append_lua_package_dir(&lua, &ctx.script_dir.join("lua"))?;
|
append_lua_package_dir(&lua, &ctx.script_dir.join("lua"))?;
|
||||||
|
|
||||||
// expose import url to lua
|
// expose import url to lua
|
||||||
let args = Args::parse();
|
let args_table = lua.create_sequence_from(import_url)?;
|
||||||
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
|
|
||||||
lua.globals().set("arg", args_table)?;
|
lua.globals().set("arg", args_table)?;
|
||||||
|
|
||||||
// make context and subscript manager accessible to API functions
|
// make context and subscript manager accessible to API functions
|
||||||
@@ -154,7 +158,7 @@ impl PathOfBuilding {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
// and move both into the new instance
|
// and move both into the new instance
|
||||||
self.lua = Self::create_lua(ctx, subscript_manager)?;
|
self.lua = Self::create_lua(ctx, subscript_manager, self.import_url.as_deref())?;
|
||||||
Self::launch(&self.lua, &script_dir)?;
|
Self::launch(&self.lua, &script_dir)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -377,3 +381,97 @@ impl PathOfBuilding {
|
|||||||
self.lua.app_data_mut().unwrap()
|
self.lua.app_data_mut().unwrap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::fonts::FontDefinitions;
|
||||||
|
use std::{fs, process::Command};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_and_restart_preserve_import_and_script_directory() {
|
||||||
|
const CHILD_ENV: &str = "RPOB_LUA_RESTART_TEST_CHILD";
|
||||||
|
// Launch changes the process CWD. Isolate it from concurrently running tests.
|
||||||
|
if std::env::var_os(CHILD_ENV).is_none() {
|
||||||
|
let output = Command::new(std::env::current_exe().unwrap())
|
||||||
|
.args([
|
||||||
|
"--exact",
|
||||||
|
"pob::tests::launch_and_restart_preserve_import_and_script_directory",
|
||||||
|
"--nocapture",
|
||||||
|
])
|
||||||
|
.env(CHILD_ENV, "1")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"Lua fixture failed:\n{}\n{}",
|
||||||
|
String::from_utf8_lossy(&output.stdout),
|
||||||
|
String::from_utf8_lossy(&output.stderr),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let original_dir = std::env::current_dir().unwrap();
|
||||||
|
let fixture_dir =
|
||||||
|
std::env::temp_dir().join(format!("rpob-lua-test-{}", std::process::id()));
|
||||||
|
fs::create_dir(&fixture_dir).unwrap();
|
||||||
|
let script_dir = fixture_dir.canonicalize().unwrap();
|
||||||
|
fs::write(script_dir.join("relative.txt"), "script directory").unwrap();
|
||||||
|
fs::write(
|
||||||
|
script_dir.join("Launch.lua"),
|
||||||
|
r#"
|
||||||
|
SetMainObject({
|
||||||
|
OnInit = function()
|
||||||
|
local file = assert(io.open("relative.txt", "r"))
|
||||||
|
assert(file:read("*a") == "script directory")
|
||||||
|
file:close()
|
||||||
|
initialized_arg = arg[1]
|
||||||
|
end,
|
||||||
|
CanExit = function() return allow_exit end,
|
||||||
|
})
|
||||||
|
allow_exit = true
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for import_url in [Some("pob://pobbin/restart-test"), None] {
|
||||||
|
let mut pob = PathOfBuilding::new(
|
||||||
|
&script_dir,
|
||||||
|
Rc::new(RefCell::new(Fonts::new(FontDefinitions::default()))),
|
||||||
|
Rc::new(RefCell::new(TextureManager::new())),
|
||||||
|
import_url.map(str::to_owned),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
pob.lua
|
||||||
|
.globals()
|
||||||
|
.get::<Option<String>>("initialized_arg")
|
||||||
|
.unwrap()
|
||||||
|
.as_deref(),
|
||||||
|
import_url
|
||||||
|
);
|
||||||
|
assert!(pob.can_exit());
|
||||||
|
pob.lua
|
||||||
|
.load("arg[1] = 'modified'; allow_exit = false; Restart()")
|
||||||
|
.exec()
|
||||||
|
.unwrap();
|
||||||
|
assert!(!pob.can_exit());
|
||||||
|
assert!(pob.update().unwrap().is_none());
|
||||||
|
assert_eq!(
|
||||||
|
pob.lua
|
||||||
|
.globals()
|
||||||
|
.get::<Option<String>>("initialized_arg")
|
||||||
|
.unwrap()
|
||||||
|
.as_deref(),
|
||||||
|
import_url
|
||||||
|
);
|
||||||
|
assert_eq!(std::env::current_dir().unwrap(), script_dir);
|
||||||
|
assert_eq!(pob.ctx().script_dir, script_dir);
|
||||||
|
assert!(!pob.ctx().needs_restart);
|
||||||
|
assert!(pob.can_exit());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::env::set_current_dir(original_dir).unwrap();
|
||||||
|
fs::remove_dir_all(fixture_dir).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ use std::sync::Arc;
|
|||||||
use winit::window::Window;
|
use winit::window::Window;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
args::Game,
|
||||||
|
chooser::Chooser,
|
||||||
dpi::{PhysicalPoint, PhysicalSize, ScaleFactor},
|
dpi::{PhysicalPoint, PhysicalSize, ScaleFactor},
|
||||||
draw_commands::DrawCommand,
|
draw_commands::DrawCommand,
|
||||||
input::{Key, ModifiersState, MouseButton},
|
input::{Key, ModifiersState, MouseButton},
|
||||||
@@ -27,6 +29,7 @@ pub enum StageEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub enum StageTransition {
|
pub enum StageTransition {
|
||||||
|
StartGame(Game),
|
||||||
ToMain,
|
ToMain,
|
||||||
ToShutdown,
|
ToShutdown,
|
||||||
}
|
}
|
||||||
@@ -39,6 +42,7 @@ pub struct StageFrameOutput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub enum ActiveStage {
|
pub enum ActiveStage {
|
||||||
|
Chooser(Box<Chooser>),
|
||||||
Startup(Installer),
|
Startup(Installer),
|
||||||
Main(PathOfBuilding),
|
Main(PathOfBuilding),
|
||||||
}
|
}
|
||||||
@@ -46,6 +50,7 @@ pub enum ActiveStage {
|
|||||||
impl ActiveStage {
|
impl ActiveStage {
|
||||||
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chooser(s) => s.update(),
|
||||||
Self::Startup(s) => s.update(),
|
Self::Startup(s) => s.update(),
|
||||||
Self::Main(s) => s.update(),
|
Self::Main(s) => s.update(),
|
||||||
}
|
}
|
||||||
@@ -53,6 +58,7 @@ impl ActiveStage {
|
|||||||
|
|
||||||
pub fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
pub fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chooser(s) => s.frame(),
|
||||||
Self::Startup(s) => s.frame(),
|
Self::Startup(s) => s.frame(),
|
||||||
Self::Main(s) => s.frame(),
|
Self::Main(s) => s.frame(),
|
||||||
}
|
}
|
||||||
@@ -60,6 +66,7 @@ impl ActiveStage {
|
|||||||
|
|
||||||
pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result<Option<StageTransition>> {
|
pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result<Option<StageTransition>> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chooser(s) => s.handle_event(event),
|
||||||
Self::Startup(s) => s.handle_event(event),
|
Self::Startup(s) => s.handle_event(event),
|
||||||
Self::Main(s) => s.handle_event(event),
|
Self::Main(s) => s.handle_event(event),
|
||||||
}
|
}
|
||||||
@@ -67,6 +74,7 @@ impl ActiveStage {
|
|||||||
|
|
||||||
pub fn set_window(&mut self, window: Arc<Window>) {
|
pub fn set_window(&mut self, window: Arc<Window>) {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chooser(s) => s.set_window(window),
|
||||||
Self::Startup(s) => s.set_window(window),
|
Self::Startup(s) => s.set_window(window),
|
||||||
Self::Main(s) => s.set_window(window),
|
Self::Main(s) => s.set_window(window),
|
||||||
}
|
}
|
||||||
@@ -74,6 +82,7 @@ impl ActiveStage {
|
|||||||
|
|
||||||
pub fn can_exit(&mut self) -> bool {
|
pub fn can_exit(&mut self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chooser(_) => true,
|
||||||
Self::Startup(_) => true,
|
Self::Startup(_) => true,
|
||||||
Self::Main(s) => s.can_exit(),
|
Self::Main(s) => s.can_exit(),
|
||||||
}
|
}
|
||||||
@@ -81,6 +90,7 @@ impl ActiveStage {
|
|||||||
|
|
||||||
pub fn clear_pressed(&mut self) {
|
pub fn clear_pressed(&mut self) {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chooser(s) => s.clear_pressed(),
|
||||||
Self::Startup(_) => {}
|
Self::Startup(_) => {}
|
||||||
Self::Main(s) => s.clear_pressed(),
|
Self::Main(s) => s.clear_pressed(),
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user