Compare commits

..
18 Commits
Author SHA1 Message Date
faumaray 329a1ad4df trying to fix release
Native release / linux (push) Successful in 1m42s
CI / check (push) Successful in 1m27s
Native release / windows (push) Successful in 3m51s
Native release / publish (push) Successful in 2m15s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:53:32 +03:00
faumaray d5df8da8b9 trying to fix release
CI / check (push) Successful in 1m30s
Native release / linux (push) Successful in 1m34s
Native release / windows (push) Failing after 3m57s
Native release / publish (push) Skipped
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:45:08 +03:00
faumaray f9a3d8dbf1 trying to fix release
CI / check (push) Successful in 1m54s
Native release / linux (push) Successful in 2m2s
Native release / windows (push) Failing after 3m55s
Native release / publish (push) Skipped
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:38:44 +03:00
faumaray 67fba6c7e2 trying to fix release
CI / check (push) Successful in 1m23s
Native release / linux (push) Successful in 1m30s
Native release / windows (push) Failing after 3m10s
Native release / publish (push) Skipped
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:28:38 +03:00
Aleksey Selihov 35ef0c59e4 Обновить .gitea/workflows/release.yml
CI / check (push) Successful in 1m51s
Native release / windows (push) Failing after 4m7s
Native release / linux (push) Successful in 4m17s
Native release / publish (push) Skipped
2026-11-27 19:12:48 +00:00
faumaray 4118c3943f Release 0.3.6 with a game chooser and native installers
CI / check (push) Failing after 7s
Native release / linux (push) Successful in 1m33s
Native release / windows (push) Failing after 9s
Native release / publish (push) Skipped
2026-11-27 21:48:45 +03:00
meehl 67cc995f78 chore: Release rusty-path-of-building version 0.3.5
CI / check (push) Successful in 3m47s
Release / create-release (push) Successful in 6s
2026-11-20 10:13:44 +01:00
meehl 534788f027 Update CHANGELOG 2026-11-20 10:13:29 +01:00
meehl a57e0afda0 Use positive indices for API C-functions
This fixes the issue where error messages display the wrong index number
for the bad argument.
2026-11-20 10:04:40 +01:00
meehl 91ddf5696a Make alignment argument in draw_string API function optional 2026-11-20 09:54:28 +01:00
meehl 08260cabd2 chore: Release rusty-path-of-building version 0.3.4
Release / create-release (push) Successful in 6s
2026-11-13 16:44:49 +01:00
meehl 4316366f87 Apply texture deltas even when skipping frames
Since the renderer rework, texture updates and frees were dropped
whenever a frame was skipped. Apply deltas before acquiring the surface
texture and free textures on skipped or lost surfaces.
2026-11-13 16:34:37 +01:00
meehl 01697e32bd Move text layout positioning into DrawCommandRecorder 2026-11-10 22:55:18 +01:00
Dodomew 3e065a8838 Snap text to pixel grid after applying viewport offset
Text inside viewports was blurry with fractional scale factors because it was aligned to the pixel grid before the viewport offset was applied.
2026-11-10 22:33:55 +01:00
meehl 1aa0aa128f Update contribution guidelines 2026-10-26 11:12:47 +01:00
meehl 098c967206 chore: Release rusty-path-of-building version 0.3.3
Release / create-release (push) Successful in 7s
2026-10-23 16:23:29 +02:00
meehl 1bb0fdf056 Update CHANGELOG 2026-10-23 16:23:07 +02:00
meehl 9a341cfb39 Support passing userdata/tables to luacurl write/header callbacks 2026-10-23 16:16:00 +02:00
23 changed files with 2088 additions and 224 deletions

No files matched your search

+46
View File
@@ -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
+188
View File
@@ -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"
+8 -49
View File
@@ -8,57 +8,16 @@
## Contributing code
- Get familiar with the code base before you start. I'll try to add more documentation providing a high-level overview of the architecture in the future. Until then, feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
- If you intend to work on the API functions, also check out the [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) code base. A great place to ask questions about it is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
- Get familiar with the code base before you start. Feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
- Make sure the [API](https://github.com/meehl/rusty-path-of-building/blob/main/src/pob/api.rs) functions stay compatible with [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) (SG). A great place to ask questions about SG is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
## macOS Development Setup
## Code Ownership and AI-Assisted Contributions
### 1. Install Lua runtime dependencies
Contributors are responsible for every line of code they submit, regardless of how it was written. Make sure to:
The application requires several Lua C libraries at runtime. Install them using LuaRocks with the LuaJIT backend:
- **Understand your code** - You must be able to explain how your contribution works and why it is implemented the way it is.
- **Review before submitting** - Carefully review all AI-generated code for correctness, security, maintainability, and consistency with the project's conventions.
- **Maintain quality** - AI assistance is not an excuse for untested code, unnecessary complexity, duplicated logic, or careless implementations.
```bash
brew install luajit luarocks
luarocks --lua-version 5.1 install luasocket
luarocks --lua-version 5.1 install luautf8
luarocks --lua-version 5.1 install lua-curl
```
Build and install `lzip` from the bundled source (requires zlib, which is pre-installed on macOS):
```bash
cd lua/libs/lzip && make LUA_IMPL=luajit install
```
### 2. Configure LUA_CPATH
Add the following to your shell profile (`~/.zshrc` or `~/.bash_profile`) so the runtime can locate the installed libraries:
```bash
eval $(luarocks --lua-version 5.1 path)
```
Then reload your shell or run `source ~/.bash_profile`.
### 3. Startup
```bash
cargo run <poe1|poe2>
```
Path of Building files are automatically downloaded to the following directories on first startup:
- poe1: `~/Library/Application Support/RustyPathOfBuilding1`
- poe2: `~/Library/Application Support/RustyPathOfBuilding2`
### Troubleshooting
**Build fails with `library 'luajit-5.1' not found`**
This usually means the build cache points to an old LuaJIT version after a Homebrew upgrade. Run:
```bash
cargo clean && cargo run <poe1|poe2>
```
If you cannot confidently explain and verify a piece of code, don't submit it.
+31 -1
View File
@@ -2,6 +2,32 @@
## [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
### Fixed
- Fix a crash when filtering nodes in the Timeless Jewel Finder
## [0.3.4] - 2026-11-13
### Fixed
- Fix blurry text inside viewports with fractional scale factors
- Fix crash on macOS
## [0.3.3] - 2026-10-23
### Fixed
- Fix error in built-in updater with new `bundled-lua-modules` feature
## [0.3.2] - 2026-10-22
### Changed
@@ -246,8 +272,12 @@
- First release
<!-- next-url -->
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.2...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.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.3...v0.3.4
[0.3.3]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.2...v0.3.3
[0.3.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.1...v0.3.2
[0.3.1]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.18...v0.3.0
Generated
+1 -1
View File
@@ -3502,7 +3502,7 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-path-of-building"
version = "0.3.2"
version = "0.3.6"
dependencies = [
"ahash",
"anyhow",
+2 -2
View File
@@ -2,9 +2,9 @@
name = "rusty-path-of-building"
authors = ["meehl"]
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"
version = "0.3.2"
version = "0.3.6"
edition = "2024"
publish = false
+42 -1
View File
@@ -6,12 +6,29 @@ The main focus of this project is native Linux support for Path of Building. It
## 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
rusty-path-of-building [poe1|poe2]
rusty-path-of-building
rusty-path-of-building poe1
rusty-path-of-building poe2 'pob://pobbin/<id>'
```
## 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.
[![Packaging status](https://repology.org/badge/vertical-allrepos/rusty-path-of-building.svg)](https://repology.org/project/rusty-path-of-building/versions)
### 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.
- `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
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
+157
View File
@@ -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))
+344
View File
@@ -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())
+57
View File
@@ -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
View File
@@ -1,7 +1,7 @@
pre-release-replacements = [
{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="<!-- 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
View File
@@ -1,6 +1,7 @@
use crate::{
args::Game,
args::{Args, Game},
batcher::build_render_job,
chooser::Chooser,
dpi::{PhysicalPoint, PhysicalSize},
fonts::{FontData, FontDefinitions, Fonts},
gfx::GraphicsContext,
@@ -9,7 +10,7 @@ use crate::{
renderer::{RenderJob, textures::TextureManager},
stage::{ActiveStage, StageEvent, StageTransition},
};
use anyhow::Result;
use anyhow::{Context, Result};
use std::sync::Arc;
use std::{cell::RefCell, path::PathBuf, rc::Rc};
use winit::{
@@ -25,57 +26,107 @@ struct FrameOutput {
pub request_redraw: bool,
}
struct GameLaunch {
game: Game,
script_dir: PathBuf,
}
pub struct App {
gfx_context: Option<GraphicsContext>,
fonts: Rc<RefCell<Fonts>>,
texture_manager: Rc<RefCell<TextureManager>>,
stage: ActiveStage,
game: Game,
script_dir: PathBuf,
launch: Option<GameLaunch>,
custom_script_dir: Option<PathBuf>,
import_url: Option<String>,
pending_transition: Option<StageTransition>,
needs_reconfigure: bool,
stage_changed: bool,
is_focused: bool,
is_hovered: bool,
}
impl App {
pub fn new(game: Game, 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());
pub fn new(args: Args, custom_script_dir: Option<PathBuf>) -> Result<Self> {
let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions())));
let texture_manager = Rc::new(RefCell::new(TextureManager::new()));
let stage = if uses_custom_script_dir {
// 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 {
let stage = ActiveStage::Chooser(Box::new(Chooser::new(Rc::clone(&fonts))));
let mut app = Self {
gfx_context: None,
fonts,
texture_manager,
stage,
game,
script_dir,
launch: None,
custom_script_dir,
import_url: args.import_url,
pending_transition: None,
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<()> {
let transition = self.stage.update();
if let Some(transition) = transition? {
let transition = match self.pending_transition.take() {
Some(transition) => Some(transition),
None => self.stage.update()?,
};
if let Some(transition) = transition {
match transition {
StageTransition::StartGame(game) => self.start_game(game)?,
StageTransition::ToMain => {
self.stage = ActiveStage::Main(PathOfBuilding::new(
&self.script_dir,
Rc::clone(&self.fonts),
Rc::clone(&self.texture_manager),
)?);
if let Some(gfx) = &self.gfx_context {
self.stage.set_window(Arc::clone(&gfx.window));
}
let launch = self
.launch
.as_ref()
.context("No game selected for Lua startup")?;
let pob = self.create_pob(launch)?;
self.set_stage(ActiveStage::Main(pob));
}
StageTransition::ToShutdown => {
self.handle_event(StageEvent::Exit);
@@ -116,16 +167,27 @@ impl App {
}
fn handle_event(&mut self, event: StageEvent) {
if let Err(err) = self.stage.handle_event(event) {
log::error!("{err}");
match self.stage.handle_event(event) {
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<()> {
let (title, _app_id) = match self.game {
Game::Poe1 => ("Path of Building 1", "rusty-path-of-building-1"),
Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"),
};
let (title, _app_id) = self.window_identity();
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes()
@@ -185,13 +247,19 @@ impl ApplicationHandler<GraphicsContext> for App {
WindowEvent::RedrawRequested => {
profiling::scope!("RedrawRequested");
if event_loop.exiting() {
return;
}
if let Err(err) = self.update(event_loop) {
log::error!("{err}");
event_loop.exit();
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 let Some(ref mut gfx) = self.gfx_context {
let size = gfx.window.inner_size();
@@ -236,20 +304,17 @@ impl ApplicationHandler<GraphicsContext> for App {
size.width,
size.height,
)));
self.request_redraw();
}
WindowEvent::Focused(focused) => {
self.is_focused = focused;
self.handle_event(StageEvent::FocusChanged(focused));
if focused {
self.request_redraw();
} else {
if !focused {
// Clear inputs on lost focus to avoid "stuck" keys on Wayland systems.
self.stage.clear_pressed();
}
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
self.handle_event(StageEvent::ScaleFactorChanged(scale_factor));
self.request_redraw();
}
WindowEvent::KeyboardInput { event, .. } => {
let state = event.state;
@@ -274,13 +339,11 @@ impl ApplicationHandler<GraphicsContext> for App {
self.handle_event(event);
}
}
self.request_redraw();
}
WindowEvent::ModifiersChanged(modifiers) => {
self.handle_event(StageEvent::ModifiersChanged {
state: modifiers.state(),
});
self.request_redraw();
}
WindowEvent::MouseInput { state, button, .. } => {
let event = match state {
@@ -288,18 +351,17 @@ impl ApplicationHandler<GraphicsContext> for App {
ElementState::Released => StageEvent::MouseUp { button },
};
self.handle_event(event);
self.request_redraw();
}
WindowEvent::CursorMoved { position, .. } => {
let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
self.handle_event(StageEvent::MouseMoved { pos });
self.request_redraw();
}
WindowEvent::CursorEntered { .. } => {
self.is_hovered = true;
self.handle_event(StageEvent::HoverChanged(true));
self.request_redraw();
}
WindowEvent::CursorLeft { .. } => {
self.is_hovered = false;
self.handle_event(StageEvent::HoverChanged(false));
}
WindowEvent::MouseWheel { delta, .. } => {
@@ -310,7 +372,6 @@ impl ApplicationHandler<GraphicsContext> for App {
}
};
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();
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
View File
@@ -7,9 +7,9 @@ use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
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)]
pub game: Game,
pub game: Option<Game>,
/// Specify a build to load on start using a URL. (Optional)
#[arg(
@@ -19,7 +19,7 @@ pub struct Args {
}
/// Enum representing the game version.
#[derive(Debug, Clone, Copy, ValueEnum)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Game {
/// Path of Exile 1
#[value(name = "poe1")]
@@ -45,3 +45,54 @@ impl Game {
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
View File
@@ -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);
}
}
+27 -10
View File
@@ -4,7 +4,8 @@ use ahash::AHasher;
use crate::{
color::Srgba,
dpi::{LogicalQuad, LogicalRect, LogicalSize},
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, ScaleFactor},
fonts::{Layout, LayoutToLogical},
math::Size,
renderer::textures::TextureId,
uv::{UvConstructors, UvQuad, UvRect},
@@ -143,20 +144,36 @@ impl DrawCommandRecorder {
});
}
pub fn draw_glyph(
/// Records a laid-out string whose top-left corner is at `layout_origin`.
pub fn draw_glyphs(
&mut self,
rect: LogicalRect<f32>,
layout: &Layout,
layout_origin: LogicalPoint<f32>,
is_absolute_position: bool,
scale_factor: ScaleFactor<f32>,
) {
// resolve the layout origin to screen space
let origin = if is_absolute_position {
layout_origin
} else {
layout_origin + self.current_viewport.min.to_vector()
};
// align the layout origin with the physical pixel grid to reduce blurriness
let origin = (origin * scale_factor).round() / scale_factor;
for glyph in &layout.glyphs {
let rect = LayoutToLogical::new(origin.x, origin.y).transform_box(&glyph.rect);
self.draw_glyph(rect, glyph.uv, glyph.color, glyph.layer_idx);
}
}
fn draw_glyph(
&mut self,
positions: LogicalRect<f32>,
uv: UvRect,
color: Srgba,
layer_idx: u32,
is_absolute_position: bool,
) {
let positions = if is_absolute_position {
rect
} else {
rect.translate(self.current_viewport.min.to_vector())
};
// cull if outside of viewport
if !positions.intersects(&self.current_viewport) {
return;
+15 -4
View File
@@ -174,7 +174,16 @@ impl GraphicsContext {
pub fn render(&mut self, render_job: Option<RenderJob>) -> anyhow::Result<()> {
profiling::scope!("render");
// apply textures delta
if let Some(render_job) = &render_job {
self.renderer
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
}
if !self.is_surface_configured {
if let Some(render_job) = &render_job {
self.renderer.free_textures(&render_job.textures_delta);
}
return Ok(());
}
@@ -185,10 +194,16 @@ impl GraphicsContext {
| wgpu::CurrentSurfaceTexture::Occluded
| wgpu::CurrentSurfaceTexture::Validation => {
// Skip frame
if let Some(render_job) = &render_job {
self.renderer.free_textures(&render_job.textures_delta);
}
return Ok(());
}
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
self.surface.configure(&self.device, &self.config);
if let Some(render_job) = &render_job {
self.renderer.free_textures(&render_job.textures_delta);
}
return Ok(());
}
};
@@ -208,10 +223,6 @@ impl GraphicsContext {
if let Some(render_job) = render_job {
let screen_size = PhysicalSize::new(self.config.width, self.config.height);
// upload new textures
self.renderer
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
// upload vertex, index, and uniform buffers
self.renderer.update_buffers(
&self.device,
+2 -1
View File
@@ -6,6 +6,7 @@ use winit::event_loop::EventLoop;
mod app;
mod args;
mod batcher;
mod chooser;
mod clipboard;
mod color;
mod dpi;
@@ -39,7 +40,7 @@ fn main() -> anyhow::Result<()> {
let args = Args::parse();
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()?;
event_loop.run_app(&mut app)?;
+105 -7
View File
@@ -1,11 +1,9 @@
use clap::Parser;
use mlua::{
AppDataRef, AppDataRefMut, Function, Lua, Result as LuaResult, Table, thread::ThreadStatus,
};
use winit::window::Window;
use crate::{
args::Args,
dpi::{PhysicalPoint, ScaleFactor},
draw_commands::DrawCommandRecorder,
fonts::Fonts,
@@ -85,6 +83,7 @@ impl Context {
/// Exposes API, forwards events to Path of Building's event handlers, and manages subscripts.
pub struct PathOfBuilding {
lua: Lua,
import_url: Option<String>,
/// Hash of the previous frame's draw commands. Used to skip rerendering identical frames.
previous_layers_hash: u64,
}
@@ -94,27 +93,32 @@ impl PathOfBuilding {
script_dir: &Path,
fonts: Rc<RefCell<Fonts>>,
texture_manager: Rc<RefCell<TextureManager>>,
import_url: Option<String>,
) -> anyhow::Result<Self> {
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)?;
Ok(Self {
lua,
import_url,
previous_layers_hash: Default::default(),
})
}
/// 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
let lua = unsafe { Lua::unsafe_new() };
append_lua_package_dir(&lua, &ctx.script_dir.join("lua"))?;
// expose import url to lua
let args = Args::parse();
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
let args_table = lua.create_sequence_from(import_url)?;
lua.globals().set("arg", args_table)?;
// make context and subscript manager accessible to API functions
@@ -154,7 +158,7 @@ impl PathOfBuilding {
.unwrap_or_default();
// 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)?;
Ok(())
@@ -377,3 +381,97 @@ impl PathOfBuilding {
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();
}
}
+46 -46
View File
@@ -41,24 +41,24 @@ pub unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_
match nargs {
// escape_code
1 => {
let esc_str = str_from_stack!(state, -nargs);
let esc_str = str_from_stack!(state, 1);
let color = Srgba::from_escape_code(esc_str);
ctx.recorder.set_draw_color(color);
}
// rgb
3 => {
let r = f32_from_stack!(state, -nargs);
let g = f32_from_stack!(state, -nargs + 1);
let b = f32_from_stack!(state, -nargs + 2);
let r = f32_from_stack!(state, 1);
let g = f32_from_stack!(state, 2);
let b = f32_from_stack!(state, 3);
let color = Srgba::new_f32(r, g, b, 1.0);
ctx.recorder.set_draw_color(color);
}
// rgba
4 => {
let r = f32_from_stack!(state, -nargs);
let g = f32_from_stack!(state, -nargs + 1);
let b = f32_from_stack!(state, -nargs + 2);
let a = f32_from_stack!(state, -nargs + 3);
let r = f32_from_stack!(state, 1);
let g = f32_from_stack!(state, 2);
let b = f32_from_stack!(state, 3);
let a = f32_from_stack!(state, 4);
let color = Srgba::new_f32(r, g, b, a);
ctx.recorder.set_draw_color(color);
}
@@ -91,10 +91,10 @@ pub unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_in
match nargs {
0 => ctx.set_recorder_viewport_to_window_size(),
4 => {
let x = f32_from_stack!(state, -nargs);
let y = f32_from_stack!(state, -nargs + 1);
let w = f32_from_stack!(state, -nargs + 2);
let h = f32_from_stack!(state, -nargs + 3);
let x = f32_from_stack!(state, 1);
let y = f32_from_stack!(state, 2);
let w = f32_from_stack!(state, 3);
let h = f32_from_stack!(state, 4);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
ctx.recorder.set_viewport(rect);
}
@@ -113,19 +113,19 @@ pub unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_
match nargs {
1 => {
let layer = i32_from_stack!(state, -nargs);
let layer = i32_from_stack!(state, 1);
ctx.recorder.set_draw_layer(layer, 0);
}
2 => {
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
let layer = match unsafe { ffi::lua_type(state, 1) } {
ffi::LUA_TNIL => None,
ffi::LUA_TNUMBER => {
let layer = i32_from_stack!(state, -nargs);
let layer = i32_from_stack!(state, 1);
Some(layer)
}
t => panic!("Expected Nil or Number, got {t:?}"),
};
let sublayer = i32_from_stack!(state, -nargs + 1);
let sublayer = i32_from_stack!(state, 2);
if let Some(layer) = layer {
ctx.recorder.set_draw_layer(layer, sublayer);
} else {
@@ -153,22 +153,22 @@ pub unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int
let parse_uv = matches!(nargs, 9 | 10);
let parse_layer_idx = matches!(nargs, 6 | 10);
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
let texture_id = unsafe { image_handle_texture_id(state, 1) };
// left, top, width, height
let x = f32_from_stack!(state, -nargs + 1);
let y = f32_from_stack!(state, -nargs + 2);
let w = f32_from_stack!(state, -nargs + 3);
let h = f32_from_stack!(state, -nargs + 4);
let x = f32_from_stack!(state, 2);
let y = f32_from_stack!(state, 3);
let w = f32_from_stack!(state, 4);
let h = f32_from_stack!(state, 5);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
// u1, v1, u2, v2
let mut i = 5;
let mut i = 6;
let uv = if parse_uv {
let u1 = f32_from_stack!(state, -nargs + i);
let v1 = f32_from_stack!(state, -nargs + i + 1);
let u2 = f32_from_stack!(state, -nargs + i + 2);
let v2 = f32_from_stack!(state, -nargs + i + 3);
let u1 = f32_from_stack!(state, i);
let v1 = f32_from_stack!(state, i + 1);
let u2 = f32_from_stack!(state, i + 2);
let v2 = f32_from_stack!(state, i + 3);
i += 4;
Some(Rect::new(Point::new(u1, v1), Point::new(u2, v2)))
} else {
@@ -176,7 +176,7 @@ pub unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int
};
let layer_idx = if parse_layer_idx {
let layer_idx = i32_from_stack!(state, -nargs + i);
let layer_idx = i32_from_stack!(state, i);
(layer_idx - 1) as u32
} else {
0
@@ -202,17 +202,17 @@ pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c
let parse_uv = matches!(nargs, 17 | 18);
let parse_layer_idx = matches!(nargs, 10 | 18);
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
let texture_id = unsafe { image_handle_texture_id(state, 1) };
// x1, y1, x2, y2, ...
let x1 = f32_from_stack!(state, -nargs + 1);
let y1 = f32_from_stack!(state, -nargs + 2);
let x2 = f32_from_stack!(state, -nargs + 3);
let y2 = f32_from_stack!(state, -nargs + 4);
let x3 = f32_from_stack!(state, -nargs + 5);
let y3 = f32_from_stack!(state, -nargs + 6);
let x4 = f32_from_stack!(state, -nargs + 7);
let y4 = f32_from_stack!(state, -nargs + 8);
let x1 = f32_from_stack!(state, 2);
let y1 = f32_from_stack!(state, 3);
let x2 = f32_from_stack!(state, 4);
let y2 = f32_from_stack!(state, 5);
let x3 = f32_from_stack!(state, 6);
let y3 = f32_from_stack!(state, 7);
let x4 = f32_from_stack!(state, 8);
let y4 = f32_from_stack!(state, 9);
let quad = Quad::new(
Point::new(x1, y1),
Point::new(x2, y2),
@@ -221,16 +221,16 @@ pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c
);
// u1, v1, u2, v2, ...
let mut i = 9;
let mut i = 10;
let uv = if parse_uv {
let u1 = f32_from_stack!(state, -nargs + i);
let v1 = f32_from_stack!(state, -nargs + i + 1);
let u2 = f32_from_stack!(state, -nargs + i + 2);
let v2 = f32_from_stack!(state, -nargs + i + 3);
let u3 = f32_from_stack!(state, -nargs + i + 4);
let v3 = f32_from_stack!(state, -nargs + i + 5);
let u4 = f32_from_stack!(state, -nargs + i + 6);
let v4 = f32_from_stack!(state, -nargs + i + 7);
let u1 = f32_from_stack!(state, i);
let v1 = f32_from_stack!(state, i + 1);
let u2 = f32_from_stack!(state, i + 2);
let v2 = f32_from_stack!(state, i + 3);
let u3 = f32_from_stack!(state, i + 4);
let v3 = f32_from_stack!(state, i + 5);
let u4 = f32_from_stack!(state, i + 6);
let v4 = f32_from_stack!(state, i + 7);
i += 8;
Some(Quad::new(
Point::new(u1, v1),
@@ -243,7 +243,7 @@ pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c
};
let layer_idx = if parse_layer_idx {
let layer_idx = i32_from_stack!(state, -nargs + i);
let layer_idx = i32_from_stack!(state, i);
(layer_idx - 1) as u32
} else {
0
+17 -26
View File
@@ -1,7 +1,7 @@
use crate::{
color::Srgba,
dpi::LogicalPoint,
fonts::{Alignment, FontStyle, LayoutJob, LayoutToLogical},
fonts::{Alignment, FontStyle, LayoutJob},
math::Point,
pob::Context,
};
@@ -46,14 +46,16 @@ pub unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
let x = f32_from_stack!(state, -nargs);
let y = f32_from_stack!(state, -nargs + 1);
let alignment = str_from_stack!(state, -nargs + 2);
let line_height = i32_from_stack!(state, -nargs + 3);
let font_type = str_from_stack!(state, -nargs + 4);
let text = str_from_stack!(state, -nargs + 5);
let x = f32_from_stack!(state, 1);
let y = f32_from_stack!(state, 2);
let alignment = if unsafe { ffi::lua_isnil(state, 3) } != 0 {
"LEFT"
} else {
str_from_stack!(state, 3)
};
let line_height = i32_from_stack!(state, 4);
let font_type = str_from_stack!(state, 5);
let text = str_from_stack!(state, 6);
let Ok(alignment) = alignment.parse::<PoBTextAlignment>() else {
panic!("Invalid alignment");
@@ -101,19 +103,10 @@ pub unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int
let layout = ctx.fonts.borrow_mut().layout(job, scale_factor);
// apply offset to account for anchor position
let position = position + layout.anchor_offset(halign);
// align layout anchor with the physical pixel grid to reduce blurriness
let position = (position * scale_factor).round() / scale_factor;
let layout_origin = position + layout.anchor_offset(halign);
for glyph in &layout.glyphs {
ctx.recorder.draw_glyph(
LayoutToLogical::new(position.x, position.y).transform_box(&glyph.rect),
glyph.uv,
glyph.color,
glyph.layer_idx,
is_absolute_position,
);
}
ctx.recorder
.draw_glyphs(&layout, layout_origin, is_absolute_position, scale_factor);
0
}
@@ -123,11 +116,9 @@ pub unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) ->
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let ctx = lua_instance.app_data_ref::<Context>().unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
let line_height = i32_from_stack!(state, -nargs);
let font_type = str_from_stack!(state, -nargs + 1);
let text = str_from_stack!(state, -nargs + 2);
let line_height = i32_from_stack!(state, 1);
let font_type = str_from_stack!(state, 2);
let text = str_from_stack!(state, 3);
let Ok(font_type) = font_type.parse::<PoBFontType>() else {
panic!("Invalid font type");
+100 -21
View File
@@ -17,11 +17,59 @@ fn bad_argument(to: impl Into<String>, pos: usize, cause: &'static str) -> LuaEr
}
}
/// A Lua callback set via `setopt_*function`.
///
/// `context` is set when an object is passed to the callback setter. In that case `function` is
/// the object's method and is invoked as `function(context, data)`.
struct Callback {
function: RegistryKey,
context: Option<RegistryKey>,
}
impl Callback {
fn resolve(&self, lua: &Lua) -> LuaResult<(mlua::Function, Option<mlua::Value>)> {
let function = lua.registry_value(&self.function)?;
let context = self
.context
.as_ref()
.map(|key| lua.registry_value::<mlua::Value>(key))
.transpose()?;
Ok((function, context))
}
fn remove(self, lua: &Lua) -> LuaResult<()> {
lua.remove_registry_value(self.function)?;
if let Some(key) = self.context {
lua.remove_registry_value(key)?;
}
Ok(())
}
}
/// Interprets write/header callback return values like Lua-cURL does.
fn callback_size(data_len: usize, results: &mlua::MultiValue) -> usize {
let Some(value) = results.front() else {
return data_len;
};
match value {
mlua::Value::Nil => 0,
mlua::Value::Integer(n) => (*n).max(0) as usize,
mlua::Value::Number(n) if *n >= 0.0 => *n as usize,
mlua::Value::Number(_) => 0,
mlua::Value::Boolean(false) => 0,
_ => data_len,
}
}
#[derive(Default)]
pub struct EasyHandle {
easy: Option<Easy>,
write_callback: Option<RegistryKey>,
header_callback: Option<RegistryKey>,
write_callback: Option<Callback>,
header_callback: Option<Callback>,
}
impl EasyHandle {
@@ -40,12 +88,12 @@ impl EasyHandle {
}
pub fn close(&mut self, lua: &Lua) -> LuaResult<()> {
if let Some(key) = self.write_callback.take() {
lua.remove_registry_value(key)?;
if let Some(callback) = self.write_callback.take() {
callback.remove(lua)?;
}
if let Some(key) = self.header_callback.take() {
lua.remove_registry_value(key)?;
if let Some(callback) = self.header_callback.take() {
callback.remove(lua)?;
}
self.easy = None;
@@ -160,20 +208,37 @@ impl EasyHandle {
fn set_callback(
lua: &Lua,
slot: &mut Option<RegistryKey>,
slot: &mut Option<Callback>,
value: mlua::Value,
method: &str,
) -> LuaResult<()> {
let new_key = match value {
let new_callback = match value {
mlua::Value::Nil => None,
mlua::Value::Function(f) => Some(lua.create_registry_value(f)?),
mlua::Value::Function(function) => Some(Callback {
function: lua.create_registry_value(function)?,
context: None,
}),
// Lua-cURL can also accept objects with a method of the given name,
// e.g. a file handle returned by `io.open` with a `write` method.
// looks a bit awkwards but it works...
value @ (mlua::Value::Table(_) | mlua::Value::UserData(_)) => {
let function: mlua::Function = lua
.load("local object, key = ...; return object[key]")
.call((value.clone(), method))?;
Some(Callback {
function: lua.create_registry_value(function)?,
context: Some(lua.create_registry_value(value)?),
})
}
_ => return Err(LuaError::runtime("invalid object type")),
};
if let Some(old_key) = slot.take() {
lua.remove_registry_value(old_key)?;
if let Some(old_callback) = slot.take() {
old_callback.remove(lua)?;
}
*slot = new_key;
*slot = new_callback;
Ok(())
}
@@ -182,41 +247,55 @@ impl EasyHandle {
let write_fn = self
.write_callback
.as_ref()
.map(|key| lua.registry_value::<mlua::Function>(key))
.map(|callback| callback.resolve(lua))
.transpose()?;
let header_fn = self
.header_callback
.as_ref()
.map(|key| lua.registry_value::<mlua::Function>(key))
.map(|callback| callback.resolve(lua))
.transpose()?;
let transfer_result = {
let mut transfer = self.curl()?.transfer();
if let Some(function) = write_fn {
if let Some((function, context)) = write_fn {
transfer
.write_function(move |data| {
let Ok(argument) = lua.create_string(data) else {
return Ok(0);
};
match function.call::<()>(argument) {
Ok(()) => Ok(data.len()),
let result = match &context {
Some(context) => {
function.call::<mlua::MultiValue>((context.clone(), argument))
}
None => function.call::<mlua::MultiValue>(argument),
};
match result {
Ok(results) => Ok(callback_size(data.len(), &results)),
Err(_) => Ok(0),
}
})
.map_err(LuaError::external)?;
}
if let Some(function) = header_fn {
if let Some((function, context)) = header_fn {
transfer
.header_function(move |data| {
let Ok(argument) = lua.create_string(data) else {
return false;
};
function.call::<bool>(argument).unwrap_or(false)
match &context {
Some(context) => {
function.call::<mlua::MultiValue>((context.clone(), argument))
}
None => function.call::<mlua::MultiValue>(argument),
}
.map(|results| callback_size(data.len(), &results) == data.len())
.unwrap_or(false)
})
.map_err(LuaError::external)?;
}
@@ -272,11 +351,11 @@ impl UserData for EasyHandle {
});
methods.add_method_mut("setopt_writefunction", |lua, this, value: mlua::Value| {
Self::set_callback(lua, &mut this.write_callback, value)
Self::set_callback(lua, &mut this.write_callback, value, "write")
});
methods.add_method_mut("setopt_headerfunction", |lua, this, value: mlua::Value| {
Self::set_callback(lua, &mut this.header_callback, value)
Self::set_callback(lua, &mut this.header_callback, value, "header")
});
methods.add_method_mut("perform", |lua, this, ()| this.perform(lua));
+10
View File
@@ -3,6 +3,8 @@ use std::sync::Arc;
use winit::window::Window;
use crate::{
args::Game,
chooser::Chooser,
dpi::{PhysicalPoint, PhysicalSize, ScaleFactor},
draw_commands::DrawCommand,
input::{Key, ModifiersState, MouseButton},
@@ -27,6 +29,7 @@ pub enum StageEvent {
}
pub enum StageTransition {
StartGame(Game),
ToMain,
ToShutdown,
}
@@ -39,6 +42,7 @@ pub struct StageFrameOutput {
}
pub enum ActiveStage {
Chooser(Box<Chooser>),
Startup(Installer),
Main(PathOfBuilding),
}
@@ -46,6 +50,7 @@ pub enum ActiveStage {
impl ActiveStage {
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
match self {
Self::Chooser(s) => s.update(),
Self::Startup(s) => s.update(),
Self::Main(s) => s.update(),
}
@@ -53,6 +58,7 @@ impl ActiveStage {
pub fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
match self {
Self::Chooser(s) => s.frame(),
Self::Startup(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>> {
match self {
Self::Chooser(s) => s.handle_event(event),
Self::Startup(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>) {
match self {
Self::Chooser(s) => s.set_window(window),
Self::Startup(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 {
match self {
Self::Chooser(_) => true,
Self::Startup(_) => true,
Self::Main(s) => s.can_exit(),
}
@@ -81,6 +90,7 @@ impl ActiveStage {
pub fn clear_pressed(&mut self) {
match self {
Self::Chooser(s) => s.clear_pressed(),
Self::Startup(_) => {}
Self::Main(s) => s.clear_pressed(),
}