Compare commits

..
75 Commits
Author SHA1 Message Date
meehl 3ca5f984de chore: Release rusty-path-of-building version 0.2.17
Release / create-release (push) Successful in 8s
2026-05-24 09:29:31 +02:00
meehl 6dbf6c0e3c Update CHANGELOG 2026-05-24 09:29:09 +02:00
meehl 6a05d86801 Adjust index to account for color escape sequences
get_text_index_at_cursor() returns an index into the stripped string,
but PoB expects an index into the original unstripped text. Accumulate
the total length of all escape sequences preceding the cursor position
and add it to the returned index.

Fixes #45
2026-05-14 10:42:26 +02:00
meehl 068dfce7ca Use correct font names to register generic font families
Fixes #48
2026-05-13 15:37:54 +02:00
Game Monster 28a9089443 Add macOS development setup guide to CONTRIBUTING 2026-04-08 15:23:38 +02:00
Game Monster e42776a2c8 Improve macOS compatibility
Enables wgpu's metal backend and restricts usage of smithay-clipboard, which provides access to the Wayland clipboard, to linux systems.
2026-04-08 14:48:21 +02:00
meehl c8bda4b76f chore: Release rusty-path-of-building version 0.2.16
Release / create-release (push) Successful in 4s
2026-03-23 08:54:23 +01:00
meehl fe10962c4b Update CHANGELOG 2026-03-23 08:53:54 +01:00
meehl 4dc8db6921 Fix tar extraction 2026-03-23 08:49:59 +01:00
meehl 716add6d76 chore: Release rusty-path-of-building version 0.2.15
Release / create-release (push) Successful in 7s
2026-03-22 22:53:27 +01:00
meehl 98af75c725 Update CHANGELOG 2026-03-22 22:52:54 +01:00
meehl 88bd3fa403 Installer refactor
Uses reqwest instead of ureq for better IPv6 handling.
2026-03-22 22:45:48 +01:00
meehl b16f7f528d chore: cargo update and bump fast_image_resize to v6.0.0 2026-03-22 10:22:45 +01:00
meehl e2c0f2fffc chore: Release rusty-path-of-building version 0.2.14
Release / create-release (push) Successful in 6s
2026-03-14 10:35:33 +01:00
meehl a6be413190 Update CHANGELOG 2026-03-14 10:35:21 +01:00
AiSatan 8034eef8c7 fix removing build directory 2026-03-11 16:48:11 +01:00
meehl 3b0d5295d3 installer: only install release versions
This prevents the installer from trying to download a beta version which
leads to a 404.
2026-03-10 16:07:54 +01:00
meehl ff46a570fc chore: Release rusty-path-of-building version 0.2.13
Release / create-release (push) Successful in 4s
2026-03-09 18:17:47 +01:00
meehl 7db64e337d Update CHANGELOG 2026-03-09 18:17:33 +01:00
meehl 522ab489cd Fix ascendancy flavour text size. 2026-03-09 18:13:58 +01:00
meehl 8217aca6f2 chore: Release rusty-path-of-building version 0.2.12
Release / create-release (push) Successful in 4s
2026-03-09 16:35:19 +01:00
meehl 249116af52 Update CHANGELOG 2026-03-09 16:35:06 +01:00
meehl c47bf48556 Add more fine-grained logging and UI feedback to installer 2026-03-09 16:30:00 +01:00
meehl 1f89e31f30 Set global timeout for ureq requests 2026-03-09 16:30:00 +01:00
AiSatan 913d2127d8 Fix to enable "Save changes" popup 2026-03-09 14:10:30 +01:00
meehl 1c99e9fabc chore: Release rusty-path-of-building version 0.2.11
Release / create-release (push) Successful in 4s
2026-03-05 08:50:53 +01:00
meehl 12fc773958 Update CHANGELOG 2026-03-05 08:50:34 +01:00
meehl ef4f86eac8 Track state and forward events for logical keys.
Using physical key codes leads to unexpected bevahior on different
keyboard layouts. Use logical keys like SimpleGraphic.

Closes #27
2026-03-05 08:30:56 +01:00
Ac5000 966363a859 Added method to InputState to clear pressed keys, mods, and mouse. Call method on window focus loss. 2026-02-28 10:23:56 +01:00
Ac5000 9d33a7704c Added documentation to src/input.rs 2026-02-28 10:23:56 +01:00
Ac5000 3a66f15b49 Added documentation. 2026-02-28 10:23:56 +01:00
meehl 7d02ca098c Use repology to display packaging status 2025-12-17 12:19:40 +01:00
meehl a858af2c38 chore: Release rusty-path-of-building version 0.2.10
Release / create-release (push) Successful in 4s
2025-12-15 23:20:27 +01:00
meehl 7fc3e340e7 Implement GetDrawColor 2025-12-15 17:56:52 +01:00
meehl dadf5c8804 Remove leftover dbg statement 2025-12-15 17:25:46 +01:00
meehl 031df6ed9c Store script directory in app context
This enables easier testing of the dev branch by providing a custom
script directory. Additionally, a Launch file is now searched for
in nearby locations and if found, used to determine a custom script
directory.
2025-12-15 17:18:56 +01:00
meehl e395e729e8 Add link to nixpkgs 2025-12-05 13:30:23 +01:00
meehl 76b5449bad installer: Write checksum of modified update script to manifest
This prevent having to perform a redundant update on first startup.
2025-12-05 13:03:11 +01:00
meehl f9f05aad08 Fix variable name 2025-12-03 23:09:03 +01:00
meehl 3eacd43837 chore: Release rusty-path-of-building version 0.2.9
Release / create-release (push) Successful in 6s
2025-12-03 16:10:25 +01:00
meehl 523d5ffe29 Update CHANGELOG 2025-12-03 16:09:53 +01:00
meehl e18623edb4 Update README 2025-11-30 11:22:18 +01:00
meehl 1812edcbe9 Implement UI scale overriding
Closes #16
2025-11-30 11:16:04 +01:00
meehl df06c8f9c6 installer: Download highest supported version instead of latest version
Closes #17
2025-11-30 10:05:43 +01:00
meehl ae6a24f82c Reduce CPU usage while window is unfocused and not hovered over
Only render if window is focused, hovered, subscript is running,
or coroutine is active.

Closes #18
2025-11-28 18:30:25 +01:00
meehl 0066a05e13 Register AbortSubscript function under right name 2025-11-27 10:54:43 +01:00
meehl 3d8143c4d1 Add help text to import url argument 2025-11-27 10:54:43 +01:00
meehl a3ef4b39d0 Remove unneeded 'return' statement 2025-11-27 10:54:43 +01:00
meehl f48ab50633 Create CONTRIBUTING.md 2025-11-23 20:51:17 +01:00
meehl b86486d5aa Move config.yml into right directory 2025-11-23 18:05:05 +01:00
meehl 1f1a331cc2 Create config.yml 2025-11-23 18:01:45 +01:00
meehl 27b93c4a9d Update issue templates 2025-11-23 17:48:35 +01:00
meehl c95514036f Fix compiler warning caused by uninitialized variable 2025-11-22 13:48:13 +01:00
meehl 37bc3c5dbb chore: Release rusty-path-of-building version 0.2.8
Release / create-release (push) Successful in 5s
2025-11-07 07:55:07 +01:00
meehl 56155d066a Remove note about clipboard support in known issues section of README 2025-11-07 01:00:06 +01:00
meehl f27e83b467 Use smithay-clipboard crate for clipboard support on Wayland
Fixes #8
2025-11-07 00:59:37 +01:00
meehl 50d4b4b09c Replace non-ASCII characters in text input with '?'
This matches `SimpleGraphics` behavior and prevents a crash that can
happen if PoB tries to delete a non-ASCII character.

Fixes #9.
2025-11-06 16:55:31 +01:00
meehl 51e6881cb0 Simplify input event handling 2025-11-06 16:30:24 +01:00
meehl 8a69d15b49 Set app_id only on platforms that support it.
This fixes a build error on windows.
2025-11-03 13:26:03 +01:00
meehl 3af5e3dccb chore: Release rusty-path-of-building version 0.2.7
Release / create-release (push) Successful in 5s
2025-11-02 17:52:39 +01:00
meehl 76a1b4691d Add missing icon 2025-11-02 17:06:21 +01:00
meehl e877b599c1 Fix UI scaling factor not being applied at startup on X11
On wayland an event it dispatched right after window creation.
 This is not the case on X11 so we need to set it manually.
2025-11-02 15:42:53 +01:00
meehl cc38e31dbb Update known issues section in README 2025-11-02 10:08:44 +01:00
meehl 2739c45181 Use better name for context 2025-11-02 09:53:37 +01:00
meehl 18b05338bf Tweak wording of README 2025-11-02 00:40:33 +01:00
meehl 73ebb1655a Add Flatpak to README
Close #7
2025-11-01 23:40:59 +01:00
meehl 87ff0968d8 Fix missing window title during installation step 2025-10-31 16:39:09 +01:00
meehl 54b454f8b9 chore: Release rusty-path-of-building version 0.2.6
Release / create-release (push) Successful in 7s
2025-10-31 01:06:18 +01:00
meehl 6d0975fe15 Update CHANGELOG 2025-10-31 01:05:49 +01:00
meehl 64960b8c3c Add stubs for DPI scale overrides 2025-10-31 00:17:50 +01:00
meehl cf518a2c40 Add regular variant of Fontin font 2025-10-31 00:07:49 +01:00
meehl bf588528ca chore: Release rusty-path-of-building version 0.2.5
Release / create-release (push) Successful in 5s
2025-10-30 20:18:42 +01:00
meehl db98ba627b Update CHANGELOG for new release 2025-10-30 20:17:50 +01:00
meehl 479b7196cf Add support for "faux italics" 2025-10-30 20:15:02 +01:00
David Truby a338ff02f1 Fix bug accidentally requiring extra features for surface format
On my system, surface_formats() has `Rgba16Unorm` as the first format in
the surface_caps.formats vector that isn't SRGB. However if this format
is used it requires a couple of extra WGPU features that weren't
requested for the device.

This specific format isn't actually required and so the features aren't
required, so instead we can just skip over any formats that require
features when skipping srgb ones. This results in an appropriate format
being selected and gets rid of a potential wgpu crash.
2025-10-30 19:32:31 +01:00
37 changed files with 3234 additions and 1330 deletions

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
# Contributing to Rusty Path Of Building
## Reporting bugs
- Ensure the bug was not already reported by searching through existing [issues](https://github.com/meehl/rusty-path-of-building/issues).
- If the bug can also be reproduced with the official runtime (e.g. by running through wine), please open an issue in the [PoB1](https://github.com/PathOfBuildingCommunity/PathOfBuilding) or [PoB2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2) repo instead. If you're unsure, feel free to just open it here.
- If possible, use the bug report template to create the issue and provide as much information as possible.
## 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.
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
## macOS Development Setup
### 1. Install Lua runtime dependencies
The application requires several Lua C libraries at runtime. Install them using LuaRocks with the LuaJIT backend:
```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>
```
+30
View File
@@ -0,0 +1,30 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A description of what you expected to happen.
**System information:**
- OS: [e.g. Linux, Windows, macOS]
- Desktop Environment/Compositor: [e.g. KDE, Gnome, sway, etc.] (only on Linux)
- Rusty Path of Building Version: [e.g. v0.2.8]
- Path of Building Version: [e.g. PoB1 v2.59.0 or PoB2 v0.12.2]
**Additional context**
Add any other context about the problem here. Feel free to add screenshots or any other info like PoB build codes if relevant.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: yes
contact_links:
- name: GitHub Discussions
url: https://github.com/meehl/rusty-path-of-building/discussions
about: Please ask questions unrelated to actual bugs/issues here.
+2
View File
@@ -1 +1,3 @@
/target/ /target/
*.so
*.so.dSYM
+130 -1
View File
@@ -2,6 +2,122 @@
## [Unreleased] - ReleaseDate ## [Unreleased] - ReleaseDate
## [0.2.17] - 2026-05-24
### Changed
- Improve macOS compatibility
### Fixed
- Fix broken selection and display of colored text
- Fix black screen during installation on nixOS
## [0.2.16] - 2026-03-23
### Fixed
- Fix bug that causes tarball extraction to fail
## [0.2.15] - 2026-03-22
### Changed
- Replace `ureq` crate with `reqwest` for better IPv4/IPv6 dual stack support
- Refactor installer
- Bump dependencies
## [0.2.14] - 2026-03-14
### Fixed
- Fix deletion of character build directories
- Prevent installer from downloading beta versions
## [0.2.13] - 2026-03-09
### Fixed
- Fix size of ascendancy flavour texts
## [0.2.12] - 2026-03-09
### Changed
- Add better logging and UI feedback for initial install
- Set global timeout for network requests
### Fixed
- Fix confirmation dialog not showing on close with unsaved changes
## [0.2.11] - 2026-03-05
### Fixed
- Clear pressed keys on focus loss to avoid stuck keys
- Use logical keys for input handling to fix unexpected behavior with different keyboard layouts
## [0.2.10] - 2025-12-15
### Added
- Implement GetDrawColor
### Fixed
- Avoid redundant update after initial download
## [0.2.9] - 2025-12-03
### Added
- Implement UI scale overriding
### Changed
- Reduce CPU usage while window is unfocused and not hovered over
- Download highest compatible PoB version instead of latest version
### Fixed
- Register `AbortSubscript` function under right name
## [0.2.8] - 2025-11-07
### Changed
- Replace non-ASCII characters in text input with '?'
- Use `smithay-clipboard` crate for clipboard support on Wayland
## [0.2.7] - 2025-11-02
### Added
- Add missing window icon. Note for package maintainers: On Wayland, the name of the `.desktop` file entries needs to match RustyPoB's `app_id`. `app_id` is set to either `rusty-path-of-building-1` or `rusty-path-of-building-2`, depending on the game argument.
### Fixed
- Fix missing window title during installation step
- Fix UI scaling factor not being applied at startup on X11
## [0.2.6] - 2025-10-31
### Added
- Add regular variant of Fontin font
- Add stubs for DPI scale overrides
## [0.2.5] - 2025-10-30
### Added
- Add support for "faux italics"
### Fixed
- Fix crash that occurs due to surface format selection not filtering out formats that require unrequested GPU features
## [0.2.4] - 2025-10-30 ## [0.2.4] - 2025-10-30
### Added ### Added
@@ -83,8 +199,21 @@
- First release - First release
<!-- next-url --> <!-- next-url -->
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.4...HEAD [Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.17...HEAD
[0.2.17]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.16...v0.2.17
[0.2.16]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.15...v0.2.16
[0.2.15]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.14...v0.2.15
[0.2.14]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.13...v0.2.14
[0.2.13]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.12...v0.2.13
[0.2.12]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.11...v0.2.12
[0.2.11]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.10...v0.2.11
[0.2.10]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.9...v0.2.10
[0.2.9]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.8...v0.2.9
[0.2.8]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.7...v0.2.8
[0.2.7]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.6...v0.2.7
[0.2.6]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.5...v0.2.6
[0.2.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.4...v0.2.5
[0.2.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.3...v0.2.4 [0.2.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.3...v0.2.4
[0.2.3]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.2...v0.2.3 [0.2.3]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.2...v0.2.3
[0.2.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.1...v0.2.2 [0.2.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.1...v0.2.2
Generated
+1416 -535
View File
File diff suppressed because it is too large. Load diff
+9 -5
View File
@@ -4,21 +4,21 @@ authors = ["meehl"]
description = "Cross-platform runtime for Path of Building" description = "Cross-platform runtime for Path of Building"
repository = "https://github.com/meehl/rusty-path-of-building" repository = "https://github.com/meehl/rusty-path-of-building"
license = "MIT" license = "MIT"
version = "0.2.4" version = "0.2.17"
edition = "2024" edition = "2024"
publish = false publish = false
[dependencies] [dependencies]
ahash = "0.8.12" ahash = "0.8.12"
anyhow = "1.0" anyhow = "1.0"
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } arboard = { version = "3.6.1", default-features = false }
bytemuck = "1.23.2" bytemuck = "1.23.2"
clap = { version = "4.5.46", features = ["derive"] } clap = { version = "4.5.46", features = ["derive"] }
dds = "0.1.0" dds = "0.1.0"
directories = "6.0.0" directories = "6.0.0"
env_logger = "0.10" env_logger = "0.10"
euclid = { version = "0.22.11", features = ["bytemuck"] } euclid = { version = "0.22.11", features = ["bytemuck"] }
fast_image_resize = { version = "5.3.0", features = ["image"] } fast_image_resize = { version = "6.0.0", features = ["image"] }
flate2 = "1.1.2" flate2 = "1.1.2"
glob = "0.3.3" glob = "0.3.3"
image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png", "webp"] } image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png", "webp"] }
@@ -32,13 +32,17 @@ parley = "0.6.0"
pollster = "0.3" pollster = "0.3"
profiling = "1.0" profiling = "1.0"
puffin_http = { version = "0.16", optional = true } puffin_http = { version = "0.16", optional = true }
raw-window-handle = "0.6.2"
regex = "1.11.2" regex = "1.11.2"
reqwest = { version = "0.13.2", features = ["blocking"] }
swash = "0.2.5" swash = "0.2.5"
tar = "0.4.44" tar = "0.4.44"
ureq = "3.1.2" wgpu = { version = "27.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] }
wgpu = { version = "27.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "wgsl"] }
winit = "0.30" winit = "0.30"
zstd = "0.13.3" zstd = "0.13.3"
[target.'cfg(target_os = "linux")'.dependencies]
smithay-clipboard = "0.7.3"
[features] [features]
profile-with-puffin = ["profiling/profile-with-puffin", "dep:puffin_http"] profile-with-puffin = ["profiling/profile-with-puffin", "dep:puffin_http"]
+6 -6
View File
@@ -1,8 +1,8 @@
# Rusty Path of Building # Rusty Path of Building
Rusty Path of Building is a cross-platform runtime for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). Like the [official runtime](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), it serves as a host environment for PoB by implementing the API used by the application's Lua logic, as well as rendering, window management, and input handling. Rusty Path of Building is a cross-platform runtime environment for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). Like [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), PoB's official runtime environment, it implements the API functions required by PoB's Lua code, handles window management and input, and renders the UI.
This project was primarily created to allow Path of Building to run natively on Linux. It is written in Rust (in case you couldn't already tell from the unimaginative name) and should run on all platforms, though only Linux has been tested so far. The primary goal of this project is to provide native Linux support for Path of Building. It is written in Rust with cross-platform compatibility in mind and also runs on Windows, though testing there has been minimal.
## Usage ## Usage
@@ -12,11 +12,11 @@ rusty-path-of-building [poe1|poe2]
## Installation ## Installation
### Arch (AUR) [![Packaging status](https://repology.org/badge/vertical-allrepos/rusty-path-of-building.svg)](https://repology.org/project/rusty-path-of-building/versions)
[![Stable version badge](https://img.shields.io/aur/version/rusty-path-of-building?style=flat&label=rusty-path-of-building)](https://aur.archlinux.org/packages/rusty-path-of-building) ### Flathub
Please check [the Arch Wiki](https://wiki.archlinux.org/title/Arch_User_Repository) on how to install packages from the AUR. [![Stable version badge](https://img.shields.io/flathub/v/community.pathofbuilding.PathOfBuilding)](https://flathub.org/en/apps/community.pathofbuilding.PathOfBuilding)
### Building from source ### Building from source
@@ -39,4 +39,4 @@ Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.ht
## Known Issues ## Known Issues
- The clipboard doesn't work with Wayland compositors that don't support the data-control extension(s). It is recommended to fall back to `Xwayland` in these cases. This can be done by unsetting `WAYLAND_DISPLAY`. More info here: https://github.com/1Password/arboard?tab=readme-ov-file#backend-support - If automatic updates fail, navigate to `~/.local/share/RustyPathOfBuilding{1,2}/` and delete both the `rpob.version` file and the `Update` directory. This will force a complete re-download of PoB's latest assets and Lua code on the next startup. (Note: Third-party backends, like this project, face challenges supporting PoB's update mechanism. To make it work, fragile workarounds had to be implemented that can break unexpectedly)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.
+1 -1
View File
@@ -646,7 +646,7 @@ static int l_zipFile_Read(lua_State* L)
if (n < 1) { if (n < 1) {
luaL_error(L, "Usage: zipFile:Read(count) or zipFile:read(\"*a\")"); luaL_error(L, "Usage: zipFile:Read(count) or zipFile:read(\"*a\")");
} }
int count; int count = 0;
if (lua_isnumber(L, 1)) { if (lua_isnumber(L, 1)) {
count = lua_tointeger(L, 1); count = lua_tointeger(L, 1);
} else { } else {
+30 -7
View File
@@ -9,13 +9,17 @@ use crate::{
input::{get_cursor_pos, is_key_down}, input::{get_cursor_pos, is_key_down},
lua::{load_module, protected_call, protected_load_module}, lua::{load_module, protected_call, protected_load_module},
paths::{ paths::{
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, set_work_dir, get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, remove_dir,
set_work_dir,
}, },
rendering::PoBString, rendering::PoBString,
search_handle::new_search_handle, search_handle::new_search_handle,
window::{get_screen_scale, get_screen_size, set_foreground, set_window_title}, window::{
get_dpi_scale_override, get_screen_scale, get_screen_size, set_dpi_scale_override,
set_foreground, set_window_title,
},
}, },
lua::ContextSocket, lua::Context,
}; };
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic}; use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -48,6 +52,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?; globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?; globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
globals.set("MakeDir", lua.create_function(make_dir)?)?; globals.set("MakeDir", lua.create_function(make_dir)?)?;
globals.set("RemoveDir", lua.create_function(remove_dir)?)?;
// console // console
globals.set("ConPrintf", lua.create_function(console_printf)?)?; globals.set("ConPrintf", lua.create_function(console_printf)?)?;
@@ -58,6 +63,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
// general // general
globals.set("GetTime", lua.create_function(get_time)?)?; globals.set("GetTime", lua.create_function(get_time)?)?;
globals.set("StripEscapes", lua.create_function(strip_escapes)?)?; globals.set("StripEscapes", lua.create_function(strip_escapes)?)?;
globals.set("Exit", lua.create_function(exit)?)?;
globals.set("Restart", lua.create_function(restart)?)?; globals.set("Restart", lua.create_function(restart)?)?;
globals.set("OpenURL", lua.create_function(open_url)?)?; globals.set("OpenURL", lua.create_function(open_url)?)?;
globals.set("RenderInit", lua.create_function(render_init)?)?; globals.set("RenderInit", lua.create_function(render_init)?)?;
@@ -88,6 +94,14 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?; globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?; globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
globals.set("SetForeground", lua.create_function(set_foreground)?)?; globals.set("SetForeground", lua.create_function(set_foreground)?)?;
globals.set(
"SetDPIScaleOverridePercent",
lua.create_function(set_dpi_scale_override)?,
)?;
globals.set(
"GetDPIScaleOverridePercent",
lua.create_function(get_dpi_scale_override)?,
)?;
// lua // lua
globals.set("PCall", lua.create_function(protected_call)?)?; globals.set("PCall", lua.create_function(protected_call)?)?;
@@ -117,9 +131,18 @@ fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
Ok(PoBString(&text).strip_escapes()) Ok(PoBString(&text).strip_escapes())
} }
fn exit(l: &Lua, exit_msg: Option<String>) -> LuaResult<()> {
if let Some(exit_msg) = exit_msg {
println!("{exit_msg}");
}
let ctx = l.app_data_ref::<&'static Context>().unwrap();
*ctx.should_exit() = true;
Ok(())
}
fn restart(l: &Lua, _: ()) -> LuaResult<()> { fn restart(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
*socket.needs_restart() = true; *ctx.needs_restart() = true;
Ok(()) Ok(())
} }
@@ -131,10 +154,10 @@ fn open_url(l: &Lua, url: String) -> LuaResult<MultiValue> {
} }
fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> { fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
for feature in features { for feature in features {
if feature == "DPI_AWARE" { if feature == "DPI_AWARE" {
*socket.is_dpi_aware() = true; *ctx.is_dpi_aware() = true;
} }
} }
Ok(()) Ok(())
+6 -13
View File
@@ -1,20 +1,13 @@
use crate::lua::ContextSocket; use crate::lua::Context;
use mlua::{Lua, Result as LuaResult}; use mlua::{Lua, Result as LuaResult};
pub fn copy(l: &Lua, text: String) -> LuaResult<()> { pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
socket ctx.window().set_clipboard_text(text);
.clipboard()
.set_text(text)
.map_err(|e| anyhow::anyhow!("{}", e))?;
Ok(()) Ok(())
} }
pub fn paste(l: &Lua, _: ()) -> LuaResult<String> { pub fn paste(l: &Lua, _: ()) -> LuaResult<Option<String>> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let text = socket Ok(ctx.window().get_clipboard_text())
.clipboard()
.get_text()
.map_err(|e| anyhow::anyhow!("{}", e))?;
Ok(text)
} }
+4 -4
View File
@@ -1,5 +1,5 @@
use crate::{ use crate::{
lua::ContextSocket, lua::Context,
renderer::textures::{TextureHandle, TextureOptions}, renderer::textures::{TextureHandle, TextureOptions},
}; };
use mlua::{Lua, MultiValue, Result as LuaResult, UserData}; use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
@@ -56,7 +56,7 @@ fn load(
handle: &mut ImageHandle, handle: &mut ImageHandle,
(image_path, flags): (String, MultiValue), (image_path, flags): (String, MultiValue),
) -> LuaResult<()> { ) -> LuaResult<()> {
let socket = lua.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = lua.app_data_ref::<&'static Context>().unwrap();
let mut is_async = false; let mut is_async = false;
let mut options = TextureOptions::LINEAR_REPEAT; let mut options = TextureOptions::LINEAR_REPEAT;
@@ -76,7 +76,7 @@ fn load(
// replace image data if already allocated // replace image data if already allocated
ImageHandle::Loaded(texture_handle) => { ImageHandle::Loaded(texture_handle) => {
// in case of error, stay loaded with current texture // in case of error, stay loaded with current texture
let _ = socket.texture_manager().update_texture( let _ = ctx.texture_manager().update_texture(
texture_handle.id(), texture_handle.id(),
image_path, image_path,
options, options,
@@ -85,7 +85,7 @@ fn load(
} }
// create new texture handle // create new texture handle
ImageHandle::Unloaded => { ImageHandle::Unloaded => {
if let Ok(tex_handle) = socket if let Ok(tex_handle) = ctx
.texture_manager() .texture_manager()
.load_texture(image_path, options, is_async) .load_texture(image_path, options, is_async)
{ {
+8 -8
View File
@@ -1,22 +1,22 @@
use crate::{ use crate::{
input::{str_as_keycode, str_as_mousebutton}, input::{str_as_key, str_as_mousebutton},
lua::ContextSocket, lua::Context,
}; };
use mlua::{Lua, Result as LuaResult}; use mlua::{Lua, Result as LuaResult};
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let pos = socket.input().mouse_pos(); let pos = ctx.input().mouse_pos();
Ok((pos.x as u32, pos.y as u32)) Ok((pos.x as u32, pos.y as u32))
} }
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> { pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
if let Some(code) = str_as_keycode(&key_name) { if let Some(key) = str_as_key(&key_name) {
Ok(socket.input().key_pressed(code)) Ok(ctx.input().key_pressed(key))
} else if let Some(button) = str_as_mousebutton(&key_name) { } else if let Some(button) = str_as_mousebutton(&key_name) {
Ok(socket.input().mouse_pressed(button)) Ok(ctx.input().mouse_pressed(button))
} else { } else {
Ok(false) Ok(false)
} }
+7 -5
View File
@@ -1,4 +1,4 @@
use crate::{args::Game, util::change_working_directory}; use crate::{lua::Context, util::change_working_directory};
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value}; use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::env; use std::env;
@@ -12,26 +12,28 @@ pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResul
} }
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> { pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::script_dir().join(name); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let mut module_path = ctx.script_dir().join(name);
if module_path.extension().is_none() { if module_path.extension().is_none() {
module_path.set_extension("lua"); module_path.set_extension("lua");
} }
let current_dir = env::current_dir()?; let current_dir = env::current_dir()?;
change_working_directory(Game::script_dir().as_path())?; change_working_directory(ctx.script_dir().as_path())?;
let result = l.load(module_path).call::<MultiValue>(args); let result = l.load(module_path).call::<MultiValue>(args);
change_working_directory(current_dir)?; change_working_directory(current_dir)?;
result result
} }
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> { pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::script_dir().join(name); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let mut module_path = ctx.script_dir().join(name);
if module_path.extension().is_none() { if module_path.extension().is_none() {
module_path.set_extension("lua"); module_path.set_extension("lua");
} }
let current_dir = env::current_dir()?; let current_dir = env::current_dir()?;
change_working_directory(Game::script_dir().as_path())?; change_working_directory(ctx.script_dir().as_path())?;
let result = match l.load(module_path).call::<MultiValue>(args) { let result = match l.load(module_path).call::<MultiValue>(args) {
// on success, callers expect a Nil followed by return values // on success, callers expect a Nil followed by return values
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()), Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
+23 -10
View File
@@ -2,18 +2,19 @@ use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::{fs, path::PathBuf}; use std::{fs, path::PathBuf};
use crate::{ use crate::{
args::Game, lua::Context,
lua::ContextSocket,
util::{change_working_directory, get_executable_dir}, util::{change_working_directory, get_executable_dir},
}; };
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<PathBuf> { pub fn get_user_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::user_data_dir()) let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(ctx.script_dir().join("userdata"))
} }
// parent directory of Launch.lua script // parent directory of Launch.lua script
pub fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> { pub fn get_script_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::script_dir()) let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(ctx.script_dir().to_owned())
} }
// parent directory of executable // parent directory of executable
@@ -25,15 +26,15 @@ pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
} }
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> { pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(socket.current_working_dir().to_path_buf()) Ok(ctx.current_working_dir().to_path_buf())
} }
// NOTE: unused // NOTE: unused
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> { pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
if change_working_directory(&path).is_ok() { if change_working_directory(&path).is_ok() {
*socket.current_working_dir() = path.into(); *ctx.current_working_dir() = path.into();
} }
Ok(()) Ok(())
} }
@@ -46,3 +47,15 @@ pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?), Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
} }
} }
pub fn remove_dir(l: &Lua, (path, recursive): (String, Option<bool>)) -> LuaResult<MultiValue> {
let result = if recursive.unwrap_or(false) {
fs::remove_dir_all(&path)
} else {
fs::remove_dir(&path)
};
match result {
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
}
}
+77 -51
View File
@@ -2,8 +2,8 @@ use crate::{
api::image_handle::ImageHandle, api::image_handle::ImageHandle,
color::Srgba, color::Srgba,
dpi::Uv, dpi::Uv,
fonts::{Alignment, LayoutJob}, fonts::{Alignment, FontStyle, LayoutJob},
lua::ContextSocket, lua::Context,
math::{Point, Quad, Rect, Size}, math::{Point, Quad, Rect, Size},
}; };
use core::ffi::{c_int, c_void}; use core::ffi::{c_int, c_void};
@@ -34,6 +34,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
// thousands of times per frame. C functions are used to get raw access to // thousands of times per frame. C functions are used to get raw access to
// the lua stack without the overhead. // the lua stack without the overhead.
unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? }; unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? };
unsafe { globals.set("GetDrawColor", lua.create_c_function(get_draw_color)?)? };
unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? }; unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? };
unsafe { unsafe {
globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?; globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?;
@@ -127,9 +128,7 @@ unsafe extern "C" fn lua_toimghandle(state: *mut ffi::lua_State, idx: c_int) ->
unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_draw_color"); //profiling::scope!("set_draw_color");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
match nargs { match nargs {
@@ -137,7 +136,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
1 => { 1 => {
let esc_str = str_from_stack!(state, -nargs); let esc_str = str_from_stack!(state, -nargs);
let color = Srgba::from_escape_code(esc_str); let color = Srgba::from_escape_code(esc_str);
socket.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
// rgb // rgb
3 => { 3 => {
@@ -145,7 +144,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
let g = f32_from_stack!(state, -nargs + 1); let g = f32_from_stack!(state, -nargs + 1);
let b = f32_from_stack!(state, -nargs + 2); let b = f32_from_stack!(state, -nargs + 2);
let color = Srgba::new_f32(r, g, b, 1.0); let color = Srgba::new_f32(r, g, b, 1.0);
socket.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
// rgba // rgba
4 => { 4 => {
@@ -154,7 +153,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
let b = f32_from_stack!(state, -nargs + 2); let b = f32_from_stack!(state, -nargs + 2);
let a = f32_from_stack!(state, -nargs + 3); let a = f32_from_stack!(state, -nargs + 3);
let color = Srgba::new_f32(r, g, b, a); let color = Srgba::new_f32(r, g, b, a);
socket.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; };
@@ -162,25 +161,37 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
0 0
} }
unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("get_draw_color");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
let color: [f32; 4] = ctx.layers().get_draw_color().into();
unsafe { ffi::lua_pushnumber(state, color[0] as f64) };
unsafe { ffi::lua_pushnumber(state, color[1] as f64) };
unsafe { ffi::lua_pushnumber(state, color[2] as f64) };
unsafe { ffi::lua_pushnumber(state, color[3] as f64) };
4
}
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_viewport"); //profiling::scope!("set_viewport");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
match nargs { match nargs {
0 => socket 0 => ctx
.layers() .layers()
.set_viewport_from_size(socket.window().logical_size()), .set_viewport_from_size(ctx.window().logical_size()),
4 => { 4 => {
let x = f32_from_stack!(state, -nargs); let x = f32_from_stack!(state, -nargs);
let y = f32_from_stack!(state, -nargs + 1); let y = f32_from_stack!(state, -nargs + 1);
let w = f32_from_stack!(state, -nargs + 2); let w = f32_from_stack!(state, -nargs + 2);
let h = f32_from_stack!(state, -nargs + 3); let h = f32_from_stack!(state, -nargs + 3);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h)); let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
socket.layers().set_viewport(rect); ctx.layers().set_viewport(rect);
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; };
@@ -191,16 +202,14 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_draw_layer"); //profiling::scope!("set_draw_layer");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
match nargs { match nargs {
1 => { 1 => {
let layer = i32_from_stack!(state, -nargs); let layer = i32_from_stack!(state, -nargs);
socket.layers().set_draw_layer(layer, 0); ctx.layers().set_draw_layer(layer, 0);
} }
2 => { 2 => {
let layer = match unsafe { ffi::lua_type(state, -nargs) } { let layer = match unsafe { ffi::lua_type(state, -nargs) } {
@@ -213,9 +222,9 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
}; };
let sublayer = i32_from_stack!(state, -nargs + 1); let sublayer = i32_from_stack!(state, -nargs + 1);
if let Some(layer) = layer { if let Some(layer) = layer {
socket.layers().set_draw_layer(layer, sublayer); ctx.layers().set_draw_layer(layer, sublayer);
} else { } else {
socket.layers().set_draw_sublayer(sublayer); ctx.layers().set_draw_sublayer(sublayer);
} }
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
@@ -227,9 +236,7 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image"); //profiling::scope!("draw_image");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) { if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
@@ -269,7 +276,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
0 0
}; };
socket.layers().draw_rect(texture_id, rect, uv, layer_idx); ctx.layers().draw_rect(texture_id, rect, uv, layer_idx);
0 0
} }
@@ -277,9 +284,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image_quad", format!("args: {:?}", args)); //profiling::scope!("draw_image_quad", format!("args: {:?}", args));
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) { if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
@@ -337,7 +342,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
0 0
}; };
socket.layers().draw_quad(texture_id, quad, uv, layer_idx); ctx.layers().draw_quad(texture_id, quad, uv, layer_idx);
0 0
} }
@@ -345,9 +350,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_string"); //profiling::scope!("draw_string");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
@@ -370,7 +373,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
let mut position = Point::new(x, y); let mut position = Point::new(x, y);
let mut is_absolute_position = false; let mut is_absolute_position = false;
// the position needs to be adjusted for some alignments to match PoBs behavior // the position needs to be adjusted for some alignments to match PoBs behavior
let screen_size = socket.window().logical_size(); let screen_size = ctx.window().logical_size();
let halign = match alignment { let halign = match alignment {
PoBTextAlignment::Left => Alignment::Min, PoBTextAlignment::Left => Alignment::Min,
PoBTextAlignment::Center => { PoBTextAlignment::Center => {
@@ -387,7 +390,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
PoBTextAlignment::RightX => Alignment::Max, PoBTextAlignment::RightX => Alignment::Max,
}; };
let current_draw_color = socket.layers().get_draw_color(); let current_draw_color = ctx.layers().get_draw_color();
let job = build_layout_job( let job = build_layout_job(
text, text,
current_draw_color, current_draw_color,
@@ -399,12 +402,11 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
// NOTE: color escape codes modify the current draw color. // NOTE: color escape codes modify the current draw color.
// set current draw color to color of last segment to match PoB's behavior // set current draw color to color of last segment to match PoB's behavior
if let Some(last_segment) = job.segments.last() { if let Some(last_segment) = job.segments.last() {
socket.layers().set_draw_color(last_segment.color); ctx.layers().set_draw_color(last_segment.color);
} }
let layout = socket.fonts().layout(job, socket.window().scale_factor); let layout = ctx.fonts().layout(job, ctx.window().scale_factor());
socket ctx.layers()
.layers()
.draw_text(position, layout, is_absolute_position); .draw_text(position, layout, is_absolute_position);
0 0
@@ -413,9 +415,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("get_string_width"); //profiling::scope!("get_string_width");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
@@ -429,9 +429,7 @@ unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_in
}; };
let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None); let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None);
let width = socket let width = ctx.fonts().get_text_width(job, ctx.window().scale_factor());
.fonts()
.get_text_width(job, socket.window().scale_factor);
unsafe { ffi::lua_pushnumber(state, width as f64) }; unsafe { ffi::lua_pushnumber(state, width as f64) };
1 1
@@ -442,19 +440,34 @@ fn get_index_at_cur(
(line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32), (line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32),
) -> LuaResult<usize> { ) -> LuaResult<usize> {
//profiling::scope!("get_char_index_at_cur"); //profiling::scope!("get_char_index_at_cur");
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let font_type = font_type.parse::<PoBFontType>()?; let font_type = font_type.parse::<PoBFontType>()?;
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None); let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
let index = socket.fonts().get_text_index_at_cursor( let index_stripped = ctx.fonts().get_text_index_at_cursor(
job, job,
Point::new(cur_x, cur_y), Point::new(cur_x, cur_y),
socket.window().scale_factor, ctx.window().scale_factor(),
); );
// convert to lua's 1-based indexing // build_layout_job() strips all color escape strings from the original string. The
Ok(index + 1) // resulting [`LayoutJob`] is then passed to get_text_index_at_cursor() which returns an
// index into the **stripped* string.
// But PoB expects an index into the **original, unstripped** text. Therefore we need to add
// the length of all color escapes up until the cursor position to return the right value.
//
// TODO: avoid matching and iterating over string twice
let mut color_escapes_total_length = 0;
for capture in ESCAPE_STR_REGEX.find_iter(&text) {
if capture.start() - color_escapes_total_length > index_stripped {
break;
}
color_escapes_total_length += capture.len();
}
// add length of color escapes and convert to lua's 1-based indexing
Ok(index_stripped + color_escapes_total_length + 1)
} }
pub static ESCAPE_STR_REGEX: LazyLock<Regex> = pub static ESCAPE_STR_REGEX: LazyLock<Regex> =
@@ -468,6 +481,7 @@ fn build_layout_job<'a>(
alignment: Option<Alignment>, alignment: Option<Alignment>,
) -> LayoutJob<'a> { ) -> LayoutJob<'a> {
let mut font_weight = None; let mut font_weight = None;
let mut font_style = FontStyle::default();
let font_family = match font_type { let font_family = match font_type {
PoBFontType::Fixed => FontFamily::Named(Cow::Borrowed("Bitstream Vera Sans Mono")), PoBFontType::Fixed => FontFamily::Named(Cow::Borrowed("Bitstream Vera Sans Mono")),
PoBFontType::Var => FontFamily::Named(Cow::Borrowed("Liberation Sans")), PoBFontType::Var => FontFamily::Named(Cow::Borrowed("Liberation Sans")),
@@ -475,16 +489,25 @@ fn build_layout_job<'a>(
font_weight = Some(700.0); font_weight = Some(700.0);
FontFamily::Named(Cow::Borrowed("Liberation Sans")) FontFamily::Named(Cow::Borrowed("Liberation Sans"))
} }
PoBFontType::Fontin => FontFamily::Named(Cow::Borrowed("Fontin")),
PoBFontType::FontinItalic => FontFamily::Named(Cow::Borrowed("Fontin")), PoBFontType::FontinItalic => FontFamily::Named(Cow::Borrowed("Fontin")),
PoBFontType::FontinSmallcaps => FontFamily::Named(Cow::Borrowed("Fontin SmallCaps")), PoBFontType::FontinSmallcaps => FontFamily::Named(Cow::Borrowed("Fontin SmallCaps")),
PoBFontType::FontinSmallcapsItalic => { PoBFontType::FontinSmallcapsItalic => {
// TODO: use regular Smallcaps for now, add "faux italics" later font_style = FontStyle::Italic;
// use regular Smallcaps with "faux italics"
FontFamily::Named(Cow::Borrowed("Fontin SmallCaps")) FontFamily::Named(Cow::Borrowed("Fontin SmallCaps"))
} }
}; };
// TODO: check how PoB determines font size // NOTE: This is just an approximation and was chosen based on how it looks.
let font_size = (line_height - 2).clamp(11, 32) as f32; //
// PoB uses pre-rendered font atlases of discrete sizes and selects the appropriate
// atlas based on the provided height. Rusty-PoB dynamically renders fonts to a
// cached font atlas to support the selection of arbitrary sizes.
//
// TODO: font size in some dropdowns is too small, e.g. socket group selection in
// 'Calcs' tab
let font_size = (line_height - 2).max(1) as f32;
let mut job = LayoutJob::new( let mut job = LayoutJob::new(
font_family, font_family,
@@ -492,6 +515,7 @@ fn build_layout_job<'a>(
line_height as f32, line_height as f32,
alignment, alignment,
font_weight, font_weight,
font_style,
); );
for (color, segment) in PoBString(text).into_iter() { for (color, segment) in PoBString(text).into_iter() {
@@ -631,6 +655,7 @@ enum PoBFontType {
VarBold, VarBold,
FontinSmallcaps, FontinSmallcaps,
FontinSmallcapsItalic, FontinSmallcapsItalic,
Fontin,
FontinItalic, FontinItalic,
} }
@@ -644,6 +669,7 @@ impl std::str::FromStr for PoBFontType {
"VAR BOLD" => Ok(Self::VarBold), "VAR BOLD" => Ok(Self::VarBold),
"FONTIN SC" => Ok(Self::FontinSmallcaps), "FONTIN SC" => Ok(Self::FontinSmallcaps),
"FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic), "FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic),
"FONTIN" => Ok(Self::Fontin),
"FONTIN ITALIC" => Ok(Self::FontinItalic), "FONTIN ITALIC" => Ok(Self::FontinItalic),
_ => Err(anyhow::anyhow!( _ => Err(anyhow::anyhow!(
"'{}' is not a valid TextFontType variant", "'{}' is not a valid TextFontType variant",
+30 -11
View File
@@ -1,34 +1,53 @@
use crate::{ use crate::{
dpi::{LogicalSize, PhysicalSize}, dpi::{LogicalSize, PhysicalSize},
lua::ContextSocket, lua::Context,
}; };
use mlua::{Lua, Result as LuaResult}; use mlua::{Lua, Result as LuaResult};
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let size = if *socket.is_dpi_aware() { let size = if *ctx.is_dpi_aware() {
let PhysicalSize { width, height, .. } = socket.window().size; let PhysicalSize { width, height, .. } = ctx.window().size;
(width, height) (width, height)
} else { } else {
let LogicalSize { width, height, .. } = socket.window().logical_size(); let LogicalSize { width, height, .. } = ctx.window().logical_size();
(width, height) (width, height)
}; };
Ok(size) Ok(size)
} }
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> { pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(socket.window().scale_factor) let scale_factor = ctx.window().scale_factor();
Ok(scale_factor)
} }
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> { pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
socket.window().set_window_title(&title); ctx.window().set_window_title(&title);
Ok(()) Ok(())
} }
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> { pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
socket.window().focus(); ctx.window().focus();
Ok(()) Ok(())
} }
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
let ctx = l.app_data_ref::<&'static Context>().unwrap();
match percent {
0 => ctx.window().scale_factor_override = None,
p if p > 0 => ctx.window().scale_factor_override = Some(p as f32 / 100.0),
_ => {}
}
Ok(())
}
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
let ctx = l.app_data_ref::<&'static Context>().unwrap();
match ctx.window().scale_factor_override {
Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
None => Ok(0),
}
}
+187 -105
View File
@@ -1,4 +1,5 @@
use crate::{ use crate::{
args::Game,
dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize}, dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize},
fonts::{FontData, FontDefinitions, Fonts}, fonts::{FontData, FontDefinitions, Fonts},
gfx::{GraphicsContext, RenderJob}, gfx::{GraphicsContext, RenderJob},
@@ -10,18 +11,16 @@ use crate::{
window::WindowState, window::WindowState,
}; };
use anyhow::Result; use anyhow::Result;
use arboard::Clipboard; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler, event::*, event_loop::ActiveEventLoop,
event::*, platform::modifier_supplement::KeyEventExtModifierSupplement, window::Window,
event_loop::ActiveEventLoop,
keyboard::{ModifiersState, PhysicalKey},
window::Window,
}; };
struct FrameOutput { struct FrameOutput {
pub render_job: RenderJob, pub render_job: RenderJob,
pub should_continue: bool,
} }
pub struct AppState { pub struct AppState {
@@ -29,38 +28,58 @@ pub struct AppState {
pub input: InputState, pub input: InputState,
pub fonts: Fonts, pub fonts: Fonts,
pub texture_manager: WrappedTextureManager, pub texture_manager: WrappedTextureManager,
pub clipboard: Clipboard, pub script_dir: PathBuf,
pub should_exit: bool,
} }
impl AppState { impl AppState {
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) { fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
self.input self.input
.set_mouse_pos(pos.to_logical(self.window.scale_factor)); .set_mouse_pos(pos.to_logical(self.window.scale_factor()));
} }
} }
pub struct App { pub struct App {
gfx_context: Option<GraphicsContext>, gfx_context: Option<GraphicsContext>,
state: AppState, state: AppState,
game: Game,
tessellator: Tessellator, tessellator: Tessellator,
needs_reconfigure: bool,
force_render: bool, force_render: bool,
current_mode: AppMode, current_mode: AppMode,
} }
impl App { impl App {
pub fn new() -> Result<Self> { 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());
let mut state = AppState {
window: WindowState::default(),
input: InputState::default(),
fonts: Fonts::new(pob_font_definitions()),
texture_manager: WrappedTextureManager::new(),
script_dir,
should_exit: false,
};
let current_mode = if uses_custom_script_dir {
// Skip installer if custom script dir is provided.
// Used for local testing
let pob_mode = PoBMode::new(&mut state)?;
AppMode::PoB(pob_mode)
} else {
AppMode::Install(InstallMode::new(game))
};
Ok(Self { Ok(Self {
gfx_context: None, gfx_context: None,
state: AppState { state,
window: WindowState::default(), game,
input: InputState::default(),
fonts: Fonts::new(pob_font_definitions()),
texture_manager: WrappedTextureManager::new(),
clipboard: arboard::Clipboard::new()?,
},
tessellator: Tessellator::default(), tessellator: Tessellator::default(),
force_render: false, needs_reconfigure: true,
current_mode: AppMode::Install(InstallMode::new()), force_render: true,
current_mode,
}) })
} }
@@ -97,12 +116,10 @@ impl App {
{ {
RenderJob::Skip RenderJob::Skip
} else { } else {
self.force_render = false;
let meshes = self.tessellator.convert_clipped_primitives( let meshes = self.tessellator.convert_clipped_primitives(
mode_output.primitives, mode_output.primitives,
font_atlas_size, font_atlas_size,
self.state.window.scale_factor, self.state.window.scale_factor(),
); );
RenderJob::Render { RenderJob::Render {
@@ -111,7 +128,10 @@ impl App {
} }
}; };
Ok(FrameOutput { render_job }) Ok(FrameOutput {
render_job,
should_continue: mode_output.should_continue,
})
} }
fn handle_event(&mut self, event: AppEvent) { fn handle_event(&mut self, event: AppEvent) {
@@ -119,28 +139,46 @@ impl App {
log::error!("{err}"); log::error!("{err}");
} }
} }
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"),
};
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes()
.with_title(title)
.with_window_icon(load_icon());
#[cfg(target_os = "linux")]
{
use winit::platform::wayland::ActiveEventLoopExtWayland;
use winit::platform::x11::ActiveEventLoopExtX11;
if event_loop.is_x11() {
use winit::platform::x11::WindowAttributesExtX11;
window_attributes = window_attributes.with_name(_app_id, _app_id);
} else if event_loop.is_wayland() {
use winit::platform::wayland::WindowAttributesExtWayland;
window_attributes = window_attributes.with_name(_app_id, _app_id);
}
}
let window = event_loop.create_window(window_attributes)?;
let window = Arc::new(window);
self.state.window.set_window(Arc::clone(&window));
self.gfx_context = Some(pollster::block_on(GraphicsContext::new(window))?);
Ok(())
}
} }
impl ApplicationHandler<GraphicsContext> for App { impl ApplicationHandler<GraphicsContext> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) { fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = match event_loop.create_window(Window::default_attributes()) { if let Err(err) = self.create_window(event_loop) {
Ok(window) => Arc::new(window), log::error!("{err}");
Err(err) => { event_loop.exit();
log::error!("{err}");
event_loop.exit();
return;
}
};
self.state.window.set_window(Arc::clone(&window));
self.gfx_context = match pollster::block_on(GraphicsContext::new(window)) {
Ok(gfx) => Some(gfx),
Err(err) => {
log::error!("{err}");
event_loop.exit();
return;
}
} }
} }
@@ -152,8 +190,10 @@ impl ApplicationHandler<GraphicsContext> for App {
) { ) {
match event { match event {
WindowEvent::CloseRequested => { WindowEvent::CloseRequested => {
self.handle_event(AppEvent::Exit); self.state.should_exit = self.current_mode.can_exit(&mut self.state);
event_loop.exit(); if !self.state.should_exit {
self.state.window.request_redraw();
}
} }
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => {
profiling::scope!("RedrawRequested"); profiling::scope!("RedrawRequested");
@@ -164,26 +204,56 @@ impl ApplicationHandler<GraphicsContext> for App {
return; return;
} }
let render_job = match self.frame() { if self.state.should_exit {
Ok(FrameOutput { render_job }) => render_job, self.handle_event(AppEvent::Exit);
Err(err) => { event_loop.exit();
log::error!("{err}"); return;
event_loop.exit(); }
return;
}
};
if let Some(ref mut gfx) = self.gfx_context { if self.needs_reconfigure {
match gfx.render(render_job) { if let Some(ref mut gfx) = self.gfx_context {
Ok(_) => {} let size = gfx.window.inner_size();
// Reconfigure the surface if it's lost or outdated gfx.resize(size.width, size.height);
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => { }
let size = gfx.window.inner_size(); self.needs_reconfigure = false;
gfx.resize(size.width, size.height); // Render at least one frame after reconfigure
self.force_render = true; self.force_render = true;
} }
let is_focused = self.state.window.is_focused;
let is_hovered = self.state.window.is_hovered;
let should_render = is_focused || is_hovered || self.force_render;
if should_render {
let FrameOutput {
render_job,
should_continue,
} = match self.frame() {
Ok(frame_output) => frame_output,
Err(err) => { Err(err) => {
log::error!("Unable to render: {err}"); log::error!("{err}");
event_loop.exit();
return;
}
};
if let Some(ref mut gfx) = self.gfx_context {
match gfx.render(render_job, self.state.window.scale_factor()) {
Ok(_) => {
self.force_render = should_continue;
if is_focused || is_hovered || should_continue {
self.state.window.request_redraw();
}
}
// Reconfigure the surface if it's lost or outdated
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
self.needs_reconfigure = true;
self.state.window.request_redraw();
}
Err(err) => {
log::error!("Unable to render: {err}");
}
} }
} }
} }
@@ -191,53 +261,48 @@ impl ApplicationHandler<GraphicsContext> for App {
profiling::finish_frame!(); profiling::finish_frame!();
} }
WindowEvent::Resized(size) => { WindowEvent::Resized(size) => {
if let Some(ref mut gfx) = self.gfx_context {
gfx.resize(size.width, size.height);
self.force_render = true;
}
self.state.window.size = PhysicalSize::new(size.width, size.height); self.state.window.size = PhysicalSize::new(size.width, size.height);
self.needs_reconfigure = true;
}
WindowEvent::Focused(focused) => {
self.state.window.is_focused = focused;
if focused {
self.state.window.request_redraw();
} else {
// Clear inputs on lost focus to avoid "stuck" keys on Wayland
// systems.
self.state.input.clear_pressed();
}
} }
WindowEvent::ScaleFactorChanged { scale_factor, .. } => { WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
self.state.window.scale_factor = scale_factor as f32; self.state.window.set_scale_factor(scale_factor as f32);
} }
WindowEvent::KeyboardInput { WindowEvent::KeyboardInput { event, .. } => {
event: let state = event.state;
KeyEvent {
physical_key: PhysicalKey::Code(code),
logical_key,
state,
..
},
..
} => {
self.state.input.set_key_pressed(code, state.is_pressed());
let event = match state { // update input state
ElementState::Pressed => AppEvent::KeyDown { code }, self.state
ElementState::Released => AppEvent::KeyUp { code }, .input
.set_key_pressed(event.logical_key.clone(), state.is_pressed());
// forward KeyUp/KeyDown events
let app_event = match state {
ElementState::Pressed => AppEvent::KeyDown {
key: event.logical_key.clone(),
},
ElementState::Released => AppEvent::KeyUp {
key: event.logical_key.clone(),
},
}; };
self.handle_event(event); self.handle_event(app_event);
// handle text input // handle text input
if state.is_pressed() { if let Some(text) = event.text_with_all_modifiers()
match logical_key { && state.is_pressed()
winit::keyboard::Key::Character(text) => { {
// only emit event if no modifier except Shift is pressed. for ch in text.chars() {
let modifiers = self.state.input.key_modifiers; let event = AppEvent::CharacterInput { ch };
if modifiers.difference(ModifiersState::SHIFT).is_empty() { self.handle_event(event);
for ch in text.chars() {
let event = AppEvent::CharacterInput { ch };
self.handle_event(event);
}
}
}
winit::keyboard::Key::Named(named) => {
if named == winit::keyboard::NamedKey::Space {
let event = AppEvent::CharacterInput { ch: ' ' };
self.handle_event(event);
}
}
_ => {}
} }
} }
} }
@@ -263,6 +328,13 @@ impl ApplicationHandler<GraphicsContext> for App {
let pos = PhysicalPoint::new(position.x as f32, position.y as f32); let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
self.state.set_mouse_pos(pos); self.state.set_mouse_pos(pos);
} }
WindowEvent::CursorEntered { .. } => {
self.state.window.is_hovered = true;
self.state.window.request_redraw();
}
WindowEvent::CursorLeft { .. } => {
self.state.window.is_hovered = false;
}
WindowEvent::MouseWheel { delta, .. } => { WindowEvent::MouseWheel { delta, .. } => {
let delta = match delta { let delta = match delta {
MouseScrollDelta::LineDelta(_, y) => y, MouseScrollDelta::LineDelta(_, y) => y,
@@ -299,6 +371,12 @@ fn pob_font_definitions() -> FontDefinitions {
"../fonts/LiberationSans-Bold.ttf" "../fonts/LiberationSans-Bold.ttf"
))), ))),
); );
definitions.font_data.insert(
"fontin-regular".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/fontin-regular.ttf"
))),
);
definitions.font_data.insert( definitions.font_data.insert(
"fontin-italic".to_owned(), "fontin-italic".to_owned(),
Arc::new(FontData::from_static(include_bytes!( Arc::new(FontData::from_static(include_bytes!(
@@ -314,21 +392,25 @@ fn pob_font_definitions() -> FontDefinitions {
definitions.generic_families.insert( definitions.generic_families.insert(
parley::GenericFamily::Monospace, parley::GenericFamily::Monospace,
vec!["bitstream-vera-sans-mono".to_owned()], vec!["Bitstream Vera Sans Mono".to_owned()],
); );
definitions.generic_families.insert( definitions.generic_families.insert(
parley::GenericFamily::SansSerif, parley::GenericFamily::SansSerif,
vec![ vec!["Liberation Sans".to_owned()],
"liberation-sans".to_owned(),
"liberation-sans-bold".to_owned(),
],
); );
definitions.generic_families.insert( definitions.generic_families.insert(
parley::GenericFamily::Serif, parley::GenericFamily::Serif,
vec!["fontin-italic".to_owned(), "fontin-smallcaps".to_owned()], vec!["Fontin".to_owned(), "Fontin SmallCaps".to_owned()],
); );
definitions definitions
} }
fn load_icon() -> Option<winit::window::Icon> {
let image_data = include_bytes!("../assets/icon.png");
let image = image::load_from_memory(image_data).ok()?.into_rgba8();
let (width, height) = image.dimensions();
winit::window::Icon::from_rgba(image.into_raw(), width, height).ok()
}
+23 -20
View File
@@ -1,49 +1,52 @@
//! `args` is used to parse the arguments passed to the program on launch.
//!
//! Normally these are the arguments passed after the `rusty-path-of-building`
//! command from a CLI.
use clap::Parser; use clap::Parser;
use clap::ValueEnum; use clap::ValueEnum;
use directories::BaseDirs; use directories::BaseDirs;
use std::path::PathBuf; use std::path::PathBuf;
/// CLI arguments passed to the application on launch.
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(version, about, long_about = None)] #[command(version, about, long_about = None)]
pub struct Args { pub struct Args {
/// Used to determine which PoB to start. (PoE1 or PoE2)
#[arg(value_enum)] #[arg(value_enum)]
pub game: Game, pub game: Game,
pub build_path: Option<String>, /// Specify a build to load on start using a URL. (Optional)
#[arg(
help = "URL of build to import on startup. Needs to use custom protocol schema, e.g. `pob://pobbin/<id>`"
)]
pub import_url: Option<String>,
} }
#[derive(Debug, Clone, ValueEnum)] /// Enum representing which game (PoE1 or PoE2) the application needs to launch.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Game { pub enum Game {
/// Path of Exile 1
#[value(name = "poe1")] #[value(name = "poe1")]
Poe1, Poe1,
/// Path of Exile 2
#[value(name = "poe2")] #[value(name = "poe2")]
Poe2, Poe2,
} }
static GAME_CONFIG: std::sync::OnceLock<Game> = std::sync::OnceLock::new();
impl Game { impl Game {
pub fn init(game: Game) { /// Returns the path to the user’s data directory based on which `Game` option
GAME_CONFIG.set(game).expect("Game should be uninitialized"); /// was used to start the application.
} pub fn data_dir(&self) -> PathBuf {
let directory_name = match self {
pub fn current() -> &'static Game {
GAME_CONFIG.get().expect("Game should be initialized")
}
pub fn data_dir() -> PathBuf {
let directory_name = match Self::current() {
Game::Poe1 => "RustyPathOfBuilding1", Game::Poe1 => "RustyPathOfBuilding1",
Game::Poe2 => "RustyPathOfBuilding2", Game::Poe2 => "RustyPathOfBuilding2",
}; };
BaseDirs::new().unwrap().data_dir().join(directory_name) BaseDirs::new().unwrap().data_dir().join(directory_name)
} }
pub fn script_dir() -> PathBuf { /// Returns the path to the user's data directory. Calls [`Self::data_dir`].
Game::data_dir() pub fn script_dir(&self) -> PathBuf {
} self.data_dir()
pub fn user_data_dir() -> PathBuf {
Game::data_dir().join("userdata")
} }
} }
+81
View File
@@ -0,0 +1,81 @@
use raw_window_handle::RawDisplayHandle;
/// Abstraction over clipboard crates
///
/// `smithay_clipboard`: Used on wayland
/// `arboard`: All other platforms (check arboard docs for platform support)
pub struct Clipboard {
#[cfg(target_os = "linux")]
smithay: Option<smithay_clipboard::Clipboard>,
arboard: Option<arboard::Clipboard>,
// fallback if everything else fails. only supports intra-application copy/paste
fallback: Option<String>,
}
impl Clipboard {
pub fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self {
Self {
#[cfg(target_os = "linux")]
smithay: create_smithay_clipboard(_raw_display_handle),
arboard: create_arboard_clipboard(),
fallback: None,
}
}
/// Sets the text content of clipboard
pub fn set_text(&mut self, text: String) {
#[cfg(target_os = "linux")]
if let Some(clipboard) = &mut self.smithay {
clipboard.store(text);
return;
}
if let Some(clipboard) = &mut self.arboard {
let _ = clipboard.set_text(text);
return;
}
self.fallback = Some(text);
}
/// Gets the text content of clipboard
pub fn get_text(&mut self) -> Option<String> {
#[cfg(target_os = "linux")]
if let Some(clipboard) = &mut self.smithay {
return clipboard.load().ok();
}
if let Some(clipboard) = &mut self.arboard {
return clipboard.get_text().ok();
}
if let Some(text) = &self.fallback {
return Some(text.clone());
}
None
}
}
#[cfg(target_os = "linux")]
fn create_smithay_clipboard(
raw_display_handle: Option<RawDisplayHandle>,
) -> Option<smithay_clipboard::Clipboard> {
if let Some(RawDisplayHandle::Wayland(handle)) = raw_display_handle {
log::debug!("Creating smithay clipboard...");
Some(unsafe { smithay_clipboard::Clipboard::new(handle.display.as_ptr()) })
} else {
None
}
}
fn create_arboard_clipboard() -> Option<arboard::Clipboard> {
log::debug!("Creating arboard clipboard...");
match arboard::Clipboard::new() {
Ok(clipboard) => Some(clipboard),
Err(err) => {
log::warn!("Failed to create arboard clipboard: {err}");
None
}
}
}
+12
View File
@@ -67,8 +67,20 @@ impl From<Srgba> for image::Rgba<u8> {
} }
} }
impl From<Srgba> for [f32; 4] {
fn from(value: Srgba) -> Self {
value.0.map(u8_to_f32)
}
}
/// f32 [0.0, 1.0] -> u8 [0, 255] /// f32 [0.0, 1.0] -> u8 [0, 255]
#[inline(always)] #[inline(always)]
const fn f32_to_u8(c: f32) -> u8 { const fn f32_to_u8(c: f32) -> u8 {
((c * 255.0) + 0.5) as u8 ((c * 255.0) + 0.5) as u8
} }
/// u8 [0, 255] -> f32 [0.0, 1.0]
#[inline(always)]
const fn u8_to_f32(c: u8) -> f32 {
c as f32 / 255.0
}
+7 -1
View File
@@ -16,7 +16,7 @@ use parley::{
use std::sync::Arc; use std::sync::Arc;
pub use atlas::FontAtlasSize; pub use atlas::FontAtlasSize;
pub use layout::{Alignment, Layout, LayoutJob}; pub use layout::{Alignment, FontStyle, Layout, LayoutJob};
mod atlas; mod atlas;
mod glyph_key; mod glyph_key;
@@ -124,18 +124,21 @@ impl Fonts {
font_size, font_size,
FontFamily::Generic(GenericFamily::Monospace), FontFamily::Generic(GenericFamily::Monospace),
None, None,
parley::FontStyle::Normal,
); );
self.preload_text( self.preload_text(
&common_chars, &common_chars,
font_size, font_size,
FontFamily::Generic(GenericFamily::SansSerif), FontFamily::Generic(GenericFamily::SansSerif),
None, None,
parley::FontStyle::Normal,
); );
self.preload_text( self.preload_text(
&common_chars, &common_chars,
font_size, font_size,
FontFamily::Generic(GenericFamily::SansSerif), FontFamily::Generic(GenericFamily::SansSerif),
Some(FontWeight::BOLD), Some(FontWeight::BOLD),
parley::FontStyle::Normal,
); );
} }
@@ -145,12 +148,14 @@ impl Fonts {
font_size: f32, font_size: f32,
font_family: FontFamily, font_family: FontFamily,
font_weight: Option<FontWeight>, font_weight: Option<FontWeight>,
font_style: parley::FontStyle,
) { ) {
profiling::scope!("preload_text"); profiling::scope!("preload_text");
let style = TextStyle { let style = TextStyle {
font_stack: FontStack::Single(font_family), font_stack: FontStack::Single(font_family),
font_weight: font_weight.unwrap_or(FontWeight::NORMAL), font_weight: font_weight.unwrap_or(FontWeight::NORMAL),
font_style,
font_size, font_size,
..Default::default() ..Default::default()
}; };
@@ -202,6 +207,7 @@ impl Fonts {
.font_weight .font_weight
.map(|w| parley::FontWeight::new(w.into())) .map(|w| parley::FontWeight::new(w.into()))
.unwrap_or(default_style.font_weight), .unwrap_or(default_style.font_weight),
font_style: job.font_style.into(),
..default_style ..default_style
}; };
+22 -1
View File
@@ -2,13 +2,30 @@ use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph}
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
use parley::FontFamily; use parley::FontFamily;
#[derive(Copy, Clone, Debug, Hash)] #[derive(Copy, Clone, Default, Debug, Hash, PartialEq)]
pub enum Alignment { pub enum Alignment {
#[default]
Min, Min,
Center, Center,
Max, Max,
} }
#[derive(Copy, Clone, Default, Debug, Hash, PartialEq)]
pub enum FontStyle {
#[default]
Normal,
Italic,
}
impl From<FontStyle> for parley::FontStyle {
fn from(value: FontStyle) -> Self {
match value {
FontStyle::Normal => parley::FontStyle::Normal,
FontStyle::Italic => parley::FontStyle::Italic,
}
}
}
#[derive(Clone, Debug, Hash)] #[derive(Clone, Debug, Hash)]
pub struct LayoutSegment<'s> { pub struct LayoutSegment<'s> {
pub text: &'s str, pub text: &'s str,
@@ -23,6 +40,7 @@ pub struct LayoutJob<'s> {
pub line_height: OrderedFloat<f32>, pub line_height: OrderedFloat<f32>,
pub alignment: Option<Alignment>, pub alignment: Option<Alignment>,
pub font_weight: Option<OrderedFloat<f32>>, pub font_weight: Option<OrderedFloat<f32>>,
pub font_style: FontStyle,
} }
impl<'s> LayoutJob<'s> { impl<'s> LayoutJob<'s> {
@@ -32,6 +50,7 @@ impl<'s> LayoutJob<'s> {
line_height: f32, line_height: f32,
alignment: Option<Alignment>, alignment: Option<Alignment>,
font_weight: Option<f32>, font_weight: Option<f32>,
font_style: FontStyle,
) -> Self { ) -> Self {
Self { Self {
segments: Vec::new(), segments: Vec::new(),
@@ -40,6 +59,7 @@ impl<'s> LayoutJob<'s> {
line_height: line_height.into(), line_height: line_height.into(),
alignment, alignment,
font_weight: font_weight.map(OrderedFloat), font_weight: font_weight.map(OrderedFloat),
font_style,
} }
} }
@@ -63,6 +83,7 @@ impl std::hash::Hash for LayoutJob<'_> {
self.line_height.hash(state); self.line_height.hash(state);
self.alignment.hash(state); self.alignment.hash(state);
self.font_weight.hash(state); self.font_weight.hash(state);
self.font_style.hash(state);
} }
} }
+23 -4
View File
@@ -14,6 +14,7 @@ use image::GenericImage;
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
use parley::{FontData, GlyphRun}; use parley::{FontData, GlyphRun};
use std::borrow::Cow; use std::borrow::Cow;
use swash::zeno;
type FontBlobId = u64; type FontBlobId = u64;
type FontIndex = u32; type FontIndex = u32;
@@ -25,14 +26,21 @@ struct StyleKey<'a> {
font_blob_id: FontBlobId, font_blob_id: FontBlobId,
font_size: OrderedFloat<f32>, font_size: OrderedFloat<f32>,
normalized_coords: Cow<'a, [i16]>, normalized_coords: Cow<'a, [i16]>,
skew: i8,
} }
impl<'a> StyleKey<'a> { impl<'a> StyleKey<'a> {
fn new(font_blob_id: FontBlobId, font_size: f32, normalized_coords: &'a [i16]) -> Self { fn new(
font_blob_id: FontBlobId,
font_size: f32,
normalized_coords: &'a [i16],
skew: i8,
) -> Self {
Self { Self {
font_blob_id, font_blob_id,
font_size: font_size.into(), font_size: font_size.into(),
normalized_coords: Cow::Borrowed(normalized_coords), normalized_coords: Cow::Borrowed(normalized_coords),
skew,
} }
} }
@@ -135,8 +143,9 @@ impl GlyphRasterizer {
font_data: &FontData, font_data: &FontData,
font_size: f32, font_size: f32,
norm_coords: &[i16], norm_coords: &[i16],
skew: i8,
) -> StyleId { ) -> StyleId {
let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords); let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords, skew);
match self.style_ids.get(&style_key) { match self.style_ids.get(&style_key) {
Some(key) => *key, Some(key) => *key,
None => *self None => *self
@@ -164,9 +173,16 @@ impl GlyphRasterizer {
let color = glyph_run.style().brush; let color = glyph_run.style().brush;
let font_size = run.font_size() * pixels_per_point; let font_size = run.font_size() * pixels_per_point;
let normalized_coords = run.normalized_coords(); let normalized_coords = run.normalized_coords();
let skew = run.synthesis().skew(); // skew angle for faux italic
let font_ref = self.get_font_ref(run.font()); let font_ref = self.get_font_ref(run.font());
let style_id = self.get_style_id(run.font(), font_size, normalized_coords); let style_id = self.get_style_id(
run.font(),
font_size,
normalized_coords,
// parley stores skew as i8 internally so this conversion is ok
skew.unwrap_or_default() as i8,
);
let mut scaler = self let mut scaler = self
.scale_context .scale_context
@@ -198,7 +214,10 @@ impl GlyphRasterizer {
swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit), swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
swash::scale::Source::Outline, swash::scale::Source::Outline,
]) ])
.format(swash::zeno::Format::Alpha) .format(zeno::Format::Alpha)
.transform(skew.map(|skew| {
zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)
}))
.offset(fract_offset) .offset(fract_offset)
.render_into(&mut scaler, glyph.id as u16, image); .render_into(&mut scaler, glyph.id as u16, image);
+9 -8
View File
@@ -95,7 +95,7 @@ impl GraphicsContext {
let surface_format = surface_caps let surface_format = surface_caps
.formats .formats
.iter() .iter()
.find(|f| !f.is_srgb()) .find(|f| !f.is_srgb() && f.required_features().is_empty())
.copied() .copied()
.unwrap_or(surface_caps.formats[0]); .unwrap_or(surface_caps.formats[0]);
@@ -144,11 +144,13 @@ impl GraphicsContext {
} }
} }
pub fn render(&mut self, render_job: RenderJob) -> Result<(), wgpu::SurfaceError> { pub fn render(
&mut self,
render_job: RenderJob,
scale_factor: f32,
) -> Result<(), wgpu::SurfaceError> {
profiling::scope!("render"); profiling::scope!("render");
self.window.request_redraw();
if !self.is_surface_configured { if !self.is_surface_configured {
return Ok(()); return Ok(());
} }
@@ -174,7 +176,6 @@ impl GraphicsContext {
} = render_job } = render_job
{ {
let screen_size = PhysicalSize::new(self.config.width, self.config.height); let screen_size = PhysicalSize::new(self.config.width, self.config.height);
let pixels_per_point = self.window.as_ref().scale_factor() as f32;
// upload new textures // upload new textures
self.renderer self.renderer
@@ -186,7 +187,7 @@ impl GraphicsContext {
&self.queue, &self.queue,
&meshes, &meshes,
screen_size, screen_size,
pixels_per_point, scale_factor,
); );
let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -214,10 +215,10 @@ impl GraphicsContext {
&mut rpass.forget_lifetime(), &mut rpass.forget_lifetime(),
&meshes, &meshes,
screen_size, screen_size,
pixels_per_point, scale_factor,
); );
self.renderer.free_textures(&textures_delta) self.renderer.free_textures(&textures_delta);
} }
{ {
+167 -182
View File
@@ -1,33 +1,45 @@
//! Module to handle user inputs like keyboard keys and mouse buttons.
use crate::dpi::LogicalPoint; use crate::dpi::LogicalPoint;
use ahash::{HashMap, HashSet}; use ahash::{HashMap, HashSet};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use winit::{ use winit::{
event::MouseButton, event::MouseButton,
keyboard::{KeyCode, ModifiersState}, keyboard::{Key, ModifiersState, NamedKey, SmolStr},
}; };
/// Current state of various keyboard and mouse inputs for the application.
#[derive(Default)] #[derive(Default)]
pub struct InputState { pub struct InputState {
/// Current state(s) of modifier keys. (Shift, Control, Alt, Super)
pub key_modifiers: ModifiersState, pub key_modifiers: ModifiersState,
keys_pressed: HashSet<KeyCode>, /// HashSet of currently pressed keyboard keys.
keys_pressed: HashSet<Key>,
/// HashSet of currently pressed mouse buttons.
mouse_pressed: HashSet<MouseButton>, mouse_pressed: HashSet<MouseButton>,
/// HashMap of mouse buttons (keys) with the last time they were pressed.
mouse_last_pressed: HashMap<MouseButton, Instant>, mouse_last_pressed: HashMap<MouseButton, Instant>,
/// Current cursor position relative to the top-left corner of the window.
cursor_pos: LogicalPoint<f32>, cursor_pos: LogicalPoint<f32>,
} }
impl InputState { impl InputState {
pub fn set_key_pressed(&mut self, code: KeyCode, is_pressed: bool) { /// Updates [`Self::keys_pressed`] based on `is_pressed`.
pub fn set_key_pressed(&mut self, key: Key, is_pressed: bool) {
if is_pressed { if is_pressed {
self.keys_pressed.insert(code); self.keys_pressed.insert(key);
} else { } else {
self.keys_pressed.remove(&code); self.keys_pressed.remove(&key);
} }
} }
pub fn key_pressed(&self, code: KeyCode) -> bool { /// Returns if the key is pressed (`true`) or not pressed (`false`).
self.keys_pressed.contains(&code) pub fn key_pressed(&self, key: Key) -> bool {
self.keys_pressed.contains(&key)
} }
/// Updates [`Self::mouse_pressed`](field@Self::mouse_pressed) based on provided
/// `button` and `is_pressed`.
pub fn set_mouse_pressed(&mut self, button: MouseButton, is_pressed: bool) -> bool { pub fn set_mouse_pressed(&mut self, button: MouseButton, is_pressed: bool) -> bool {
if is_pressed { if is_pressed {
self.mouse_pressed.insert(button); self.mouse_pressed.insert(button);
@@ -50,202 +62,171 @@ impl InputState {
} }
} }
/// Returns `true` if the `button` was pressed and no release has been seen.
pub fn mouse_pressed(&self, button: MouseButton) -> bool { pub fn mouse_pressed(&self, button: MouseButton) -> bool {
self.mouse_pressed.contains(&button) self.mouse_pressed.contains(&button)
} }
/// Returns the last known cursor position.
pub fn mouse_pos(&self) -> LogicalPoint<f32> { pub fn mouse_pos(&self) -> LogicalPoint<f32> {
self.cursor_pos self.cursor_pos
} }
/// Sets [`Self::cursor_pos`] to the provided `pos`.
pub fn set_mouse_pos(&mut self, pos: LogicalPoint<f32>) { pub fn set_mouse_pos(&mut self, pos: LogicalPoint<f32>) {
self.cursor_pos = pos; self.cursor_pos = pos;
} }
/// Clears all pressed keys, buttons, and modifier states. Used when the
/// application loses focus to avoid keys being "stuck" on/pressed.
pub fn clear_pressed(&mut self) {
self.keys_pressed.clear();
self.mouse_pressed.clear();
self.key_modifiers = ModifiersState::empty();
}
} }
pub fn str_as_keycode(s: &str) -> Option<KeyCode> { /// Attempts to convert the provided string `s` to a [winit::keyboard::Key].
/// Returns [None] if no matching Key found.
pub fn str_as_key(s: &str) -> Option<Key> {
Some(match s.to_uppercase().as_str() { Some(match s.to_uppercase().as_str() {
// Letters "A" => Key::Character(SmolStr::new_static("A")),
"A" => KeyCode::KeyA, "B" => Key::Character(SmolStr::new_static("B")),
"B" => KeyCode::KeyB, "C" => Key::Character(SmolStr::new_static("C")),
"C" => KeyCode::KeyC, "D" => Key::Character(SmolStr::new_static("D")),
"D" => KeyCode::KeyD, "E" => Key::Character(SmolStr::new_static("E")),
"E" => KeyCode::KeyE, "F" => Key::Character(SmolStr::new_static("F")),
"F" => KeyCode::KeyF, "G" => Key::Character(SmolStr::new_static("G")),
"G" => KeyCode::KeyG, "H" => Key::Character(SmolStr::new_static("H")),
"H" => KeyCode::KeyH, "I" => Key::Character(SmolStr::new_static("I")),
"I" => KeyCode::KeyI, "J" => Key::Character(SmolStr::new_static("J")),
"J" => KeyCode::KeyJ, "K" => Key::Character(SmolStr::new_static("K")),
"K" => KeyCode::KeyK, "L" => Key::Character(SmolStr::new_static("L")),
"L" => KeyCode::KeyL, "M" => Key::Character(SmolStr::new_static("M")),
"M" => KeyCode::KeyM, "N" => Key::Character(SmolStr::new_static("N")),
"N" => KeyCode::KeyN, "O" => Key::Character(SmolStr::new_static("O")),
"O" => KeyCode::KeyO, "P" => Key::Character(SmolStr::new_static("P")),
"P" => KeyCode::KeyP, "Q" => Key::Character(SmolStr::new_static("Q")),
"Q" => KeyCode::KeyQ, "R" => Key::Character(SmolStr::new_static("R")),
"R" => KeyCode::KeyR, "S" => Key::Character(SmolStr::new_static("S")),
"S" => KeyCode::KeyS, "T" => Key::Character(SmolStr::new_static("T")),
"T" => KeyCode::KeyT, "U" => Key::Character(SmolStr::new_static("U")),
"U" => KeyCode::KeyU, "V" => Key::Character(SmolStr::new_static("V")),
"V" => KeyCode::KeyV, "W" => Key::Character(SmolStr::new_static("W")),
"W" => KeyCode::KeyW, "X" => Key::Character(SmolStr::new_static("X")),
"X" => KeyCode::KeyX, "Y" => Key::Character(SmolStr::new_static("Y")),
"Y" => KeyCode::KeyY, "Z" => Key::Character(SmolStr::new_static("Z")),
"Z" => KeyCode::KeyZ,
// Digits "0" => Key::Character(SmolStr::new_static("0")),
"0" => KeyCode::Digit0, "1" => Key::Character(SmolStr::new_static("1")),
"1" => KeyCode::Digit1, "2" => Key::Character(SmolStr::new_static("2")),
"2" => KeyCode::Digit2, "3" => Key::Character(SmolStr::new_static("3")),
"3" => KeyCode::Digit3, "4" => Key::Character(SmolStr::new_static("4")),
"4" => KeyCode::Digit4, "5" => Key::Character(SmolStr::new_static("5")),
"5" => KeyCode::Digit5, "6" => Key::Character(SmolStr::new_static("6")),
"6" => KeyCode::Digit6, "7" => Key::Character(SmolStr::new_static("7")),
"7" => KeyCode::Digit7, "8" => Key::Character(SmolStr::new_static("8")),
"8" => KeyCode::Digit8, "9" => Key::Character(SmolStr::new_static("9")),
"9" => KeyCode::Digit9,
// Modifiers "SHIFT" => Key::Named(NamedKey::Shift),
"SHIFT" => KeyCode::ShiftLeft, "CTRL" => Key::Named(NamedKey::Control),
"CTRL" => KeyCode::ControlLeft, "ALT" => Key::Named(NamedKey::Alt),
"ALT" => KeyCode::AltLeft,
// F Keys "F1" => Key::Named(NamedKey::F1),
"F1" => KeyCode::F1, "F2" => Key::Named(NamedKey::F2),
"F2" => KeyCode::F2, "F3" => Key::Named(NamedKey::F3),
"F3" => KeyCode::F3, "F4" => Key::Named(NamedKey::F4),
"F4" => KeyCode::F4, "F5" => Key::Named(NamedKey::F5),
"F5" => KeyCode::F5, "F6" => Key::Named(NamedKey::F6),
"F6" => KeyCode::F6, "F7" => Key::Named(NamedKey::F7),
"F7" => KeyCode::F7, "F8" => Key::Named(NamedKey::F8),
"F8" => KeyCode::F8, "F9" => Key::Named(NamedKey::F9),
"F9" => KeyCode::F9, "F10" => Key::Named(NamedKey::F10),
"F10" => KeyCode::F10, "F11" => Key::Named(NamedKey::F11),
"F11" => KeyCode::F11, "F12" => Key::Named(NamedKey::F12),
"F12" => KeyCode::F12,
// Rest " " => Key::Named(NamedKey::Space),
" " => KeyCode::Space, "BACK" => Key::Named(NamedKey::Backspace),
"BACK" => KeyCode::Backspace, "TAB" => Key::Named(NamedKey::Tab),
"TAB" => KeyCode::Tab, "RETURN" => Key::Named(NamedKey::Enter),
"RETURN" => KeyCode::Enter, "ESCAPE" => Key::Named(NamedKey::Escape),
"ESCAPE" => KeyCode::Escape, "PAUSE" => Key::Named(NamedKey::Pause),
"PAUSE" => KeyCode::Pause, "PAGEUP" => Key::Named(NamedKey::PageUp),
"PAGEUP" => KeyCode::PageUp, "PAGEDOWN" => Key::Named(NamedKey::PageDown),
"PAGEDOWN" => KeyCode::PageDown, "END" => Key::Named(NamedKey::End),
"END" => KeyCode::End, "HOME" => Key::Named(NamedKey::Home),
"HOME" => KeyCode::Home, "PRINTSCREEN" => Key::Named(NamedKey::PrintScreen),
"PRINTSCREEN" => KeyCode::PrintScreen, "INSERT" => Key::Named(NamedKey::Insert),
"INSERT" => KeyCode::Insert, "DELETE" => Key::Named(NamedKey::Delete),
"DELETE" => KeyCode::Delete, "UP" => Key::Named(NamedKey::ArrowUp),
"UP" => KeyCode::ArrowUp, "DOWN" => Key::Named(NamedKey::ArrowDown),
"DOWN" => KeyCode::ArrowDown, "LEFT" => Key::Named(NamedKey::ArrowLeft),
"LEFT" => KeyCode::ArrowLeft, "RIGHT" => Key::Named(NamedKey::ArrowRight),
"RIGHT" => KeyCode::ArrowRight, "NUMLOCK" => Key::Named(NamedKey::NumLock),
"NUMLOCK" => KeyCode::NumLock, "SCROLL" => Key::Named(NamedKey::ScrollLock),
"SCROLL" => KeyCode::ScrollLock,
_ => return None, _ => return None,
}) })
} }
pub fn keycode_as_str(code: KeyCode) -> Option<&'static str> { /// Attempts to convert the provided [winit::keyboard::Key] `key` to a string
Some(match code { /// representation that PoB recognizes.
// Letters ///
KeyCode::KeyA => "a", /// Returns [None] if no matching string found.
KeyCode::KeyB => "b", pub fn key_as_str(key: Key) -> Option<SmolStr> {
KeyCode::KeyC => "c", Some(match key {
KeyCode::KeyD => "d", Key::Character(ch) => {
KeyCode::KeyE => "e", if ch == "=" {
KeyCode::KeyF => "f", SmolStr::new("+") // This is what PoB does
KeyCode::KeyG => "g", } else {
KeyCode::KeyH => "h", ch
KeyCode::KeyI => "i", }
KeyCode::KeyJ => "j", }
KeyCode::KeyK => "k", Key::Named(named) => SmolStr::new(match named {
KeyCode::KeyL => "l", NamedKey::Shift => "SHIFT",
KeyCode::KeyM => "m", NamedKey::Control => "CTRL",
KeyCode::KeyN => "n", NamedKey::Alt => "ALT",
KeyCode::KeyO => "o", NamedKey::F1 => "F1",
KeyCode::KeyP => "p", NamedKey::F2 => "F2",
KeyCode::KeyQ => "q", NamedKey::F3 => "F3",
KeyCode::KeyR => "r", NamedKey::F4 => "F4",
KeyCode::KeyS => "s", NamedKey::F5 => "F5",
KeyCode::KeyT => "t", NamedKey::F6 => "F6",
KeyCode::KeyU => "u", NamedKey::F7 => "F7",
KeyCode::KeyV => "v", NamedKey::F8 => "F8",
KeyCode::KeyW => "w", NamedKey::F9 => "F9",
KeyCode::KeyX => "x", NamedKey::F10 => "F10",
KeyCode::KeyY => "y", NamedKey::F11 => "F11",
KeyCode::KeyZ => "z", NamedKey::F12 => "F12",
NamedKey::Space => " ",
// Digits NamedKey::Backspace => "BACK",
KeyCode::Digit0 => "0", NamedKey::Tab => "TAB",
KeyCode::Digit1 => "1", NamedKey::Enter => "RETURN",
KeyCode::Digit2 => "2", NamedKey::Escape => "ESCAPE",
KeyCode::Digit3 => "3", NamedKey::Pause => "PAUSE",
KeyCode::Digit4 => "4", NamedKey::PageUp => "PAGEUP",
KeyCode::Digit5 => "5", NamedKey::PageDown => "PAGEDOWN",
KeyCode::Digit6 => "6", NamedKey::End => "END",
KeyCode::Digit7 => "7", NamedKey::Home => "HOME",
KeyCode::Digit8 => "8", NamedKey::PrintScreen => "PRINTSCREEN",
KeyCode::Digit9 => "9", NamedKey::Insert => "INSERT",
NamedKey::Delete => "DELETE",
// Modifiers NamedKey::ArrowUp => "UP",
KeyCode::ShiftLeft => "SHIFT", NamedKey::ArrowDown => "DOWN",
KeyCode::ControlLeft => "CTRL", NamedKey::ArrowLeft => "LEFT",
KeyCode::AltLeft => "ALT", NamedKey::ArrowRight => "RIGHT",
NamedKey::NumLock => "NUMLOCK",
// F Keys NamedKey::ScrollLock => "SCROLL",
KeyCode::F1 => "F1", _ => return None,
KeyCode::F2 => "F2", }),
KeyCode::F3 => "F3",
KeyCode::F4 => "F4",
KeyCode::F5 => "F5",
KeyCode::F6 => "F6",
KeyCode::F7 => "F7",
KeyCode::F8 => "F8",
KeyCode::F9 => "F9",
KeyCode::F10 => "F10",
KeyCode::F11 => "F11",
KeyCode::F12 => "F12",
// Rest
KeyCode::Space => " ",
KeyCode::Backspace => "BACK",
KeyCode::Tab => "TAB",
KeyCode::Enter => "RETURN",
KeyCode::Escape => "ESCAPE",
KeyCode::Pause => "PAUSE",
KeyCode::PageUp => "PAGEUP",
KeyCode::PageDown => "PAGEDOWN",
KeyCode::End => "END",
KeyCode::Home => "HOME",
KeyCode::PrintScreen => "PRINTSCREEN",
KeyCode::Insert => "INSERT",
KeyCode::Delete => "DELETE",
KeyCode::ArrowUp => "UP",
KeyCode::ArrowDown => "DOWN",
KeyCode::ArrowLeft => "LEFT",
KeyCode::ArrowRight => "RIGHT",
KeyCode::NumLock => "NUMLOCK",
KeyCode::ScrollLock => "SCROLL",
KeyCode::Equal => "+", // This is what PoB does
KeyCode::Minus => "-",
KeyCode::Comma => ",",
KeyCode::Period => ".",
KeyCode::Slash => "/",
KeyCode::NumpadAdd => "+",
KeyCode::NumpadSubtract => "-",
KeyCode::NumpadEnter => "RETURN",
KeyCode::Numpad0 => "0",
_ => return None, _ => return None,
}) })
} }
/// Attempts to convert the provided [&str] `s` from the PoB Lua Backend to a
/// [MouseButton].
///
/// Returns [None] if no matching string found.
pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> { pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
Some(match s.to_uppercase().as_str() { Some(match s.to_uppercase().as_str() {
"LEFTBUTTON" => MouseButton::Left, "LEFTBUTTON" => MouseButton::Left,
@@ -257,13 +238,17 @@ pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
}) })
} }
pub fn mousebutton_as_str(button: MouseButton) -> Option<&'static str> { /// Attempts to convert the provided [MouseButton] to a [SmolStr] that the PoB Lua
/// backend recognizes.
///
/// Returns [None] if no matching [MouseButton] was found.
pub fn mousebutton_as_str(button: MouseButton) -> Option<SmolStr> {
Some(match button { Some(match button {
MouseButton::Left => "LEFTBUTTON", MouseButton::Left => SmolStr::new("LEFTBUTTON"),
MouseButton::Right => "RIGHTBUTTON", MouseButton::Right => SmolStr::new("RIGHTBUTTON"),
MouseButton::Middle => "MIDDLEBUTTON", MouseButton::Middle => SmolStr::new("MIDDLEBUTTON"),
MouseButton::Back => "MOUSE4", MouseButton::Back => SmolStr::new("MOUSE4"),
MouseButton::Forward => "MOUSE5", MouseButton::Forward => SmolStr::new("MOUSE5"),
_ => return None, _ => return None,
}) })
} }
+335 -258
View File
@@ -3,67 +3,66 @@ use crate::{
args::Game, args::Game,
color::Srgba, color::Srgba,
dpi::{LogicalPoint, LogicalRect}, dpi::{LogicalPoint, LogicalRect},
fonts::{Alignment, LayoutJob}, fonts::{Alignment, FontStyle, LayoutJob},
installer::download::{
DownloadEvent, ExtractionRule, build_client, download_and_extract_tarball,
download_file_to_disk, fetch_file_contents,
},
mode::{AppEvent, ModeFrameOutput, ModeTransition}, mode::{AppEvent, ModeFrameOutput, ModeTransition},
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive}, renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
util::replace_in_matching_lines,
}; };
use anyhow::bail;
use flate2::read::GzDecoder;
use parley::{FontFamily, GenericFamily}; use parley::{FontFamily, GenericFamily};
use regex::Regex; use regex::Regex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{ use std::{
fs::{self}, fs,
io::copy, path::Path,
path::{Path, PathBuf}, sync::{
sync::mpsc::{self, Receiver, TryRecvError}, LazyLock,
mpsc::{self, Receiver, TryRecvError},
},
thread, thread,
}; };
use ureq::http::Response;
const REPO_NAME: &str = "meehl/rusty-pob-manifest"; mod download;
enum DownloadProgress { const COMPAT_REPO: &str = "meehl/rusty-pob-manifest";
Percentage(f32), // percentage of total size (between 0 and 1)
TotalBytes(u64), // amount of bytes downloaded static VERSION_RE: LazyLock<Regex> =
} LazyLock::new(|| Regex::new(r"^(\d+)\.(\d+)\.(\d+)$").unwrap());
static MANIFEST_VERSION_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<Version").unwrap());
enum Progress { enum Progress {
Download(DownloadProgress), Status(String),
Complete, Complete,
Error(anyhow::Error), Error(anyhow::Error),
} }
enum CurrentProgress { /// Execution mode in which initial installation of PoB is performed.
Starting,
Download(DownloadProgress),
}
/// Execution mode in which PoB's assets are downloaded if they don't exist yet.
/// ///
/// Immediately transitions into PoB mode if assets already exist. Otherwise, /// Immediately transitions into PoB mode if already installed.
/// it downloads them to the user directory and displays the download progress.
pub struct InstallMode { pub struct InstallMode {
progress_rx: Option<Receiver<Progress>>, progress_rx: Option<Receiver<Progress>>,
current_progress: CurrentProgress, status: String,
} }
impl InstallMode { impl InstallMode {
pub fn new() -> Self { pub fn new(game: Game) -> Self {
let script_dir = Game::script_dir(); let script_dir = game.script_dir();
let (progress_tx, progress_rx) = mpsc::channel(); let (progress_tx, progress_rx) = mpsc::channel();
thread::spawn(move || { thread::spawn(move || {
if let Err(err) = install(script_dir.as_path(), &progress_tx) { if let Err(err) = install(script_dir.as_path(), game, &progress_tx) {
progress_tx.send(Progress::Error(err)).unwrap(); let _ = progress_tx.send(Progress::Error(err));
return; return;
} }
progress_tx.send(Progress::Complete).unwrap(); let _ = progress_tx.send(Progress::Complete);
}); });
Self { Self {
progress_rx: Some(progress_rx), progress_rx: Some(progress_rx),
current_progress: CurrentProgress::Starting, status: String::from("Starting installation..."),
} }
} }
@@ -73,6 +72,7 @@ impl InstallMode {
Ok(ModeFrameOutput { Ok(ModeFrameOutput {
primitives, primitives,
can_elide: false, can_elide: false,
should_continue: true,
}) })
} }
@@ -80,17 +80,13 @@ impl InstallMode {
if let Some(progress_rx) = &self.progress_rx { if let Some(progress_rx) = &self.progress_rx {
loop { loop {
match progress_rx.try_recv() { match progress_rx.try_recv() {
Ok(Progress::Download(progress)) => { Ok(Progress::Status(msg)) => self.status = msg,
self.current_progress = CurrentProgress::Download(progress); Ok(Progress::Complete) => return Ok(Some(ModeTransition::PoB)),
}
Ok(Progress::Complete) => {
return Ok(Some(ModeTransition::PoB));
}
Ok(Progress::Error(err)) => { Ok(Progress::Error(err)) => {
return Err(anyhow::anyhow!("Download failed: {}", err)); return Err(anyhow::anyhow!("Installation failed: {err}"));
} }
Err(TryRecvError::Disconnected) => { Err(TryRecvError::Disconnected) => {
return Err(anyhow::anyhow!("Download thread disconnected!")); return Err(anyhow::anyhow!("Install thread disconnected unexpectedly"));
} }
Err(TryRecvError::Empty) => { Err(TryRecvError::Empty) => {
break; break;
@@ -120,25 +116,13 @@ impl InstallMode {
34.0, 34.0,
Some(Alignment::Center), Some(Alignment::Center),
Some(700.0), Some(700.0),
FontStyle::Normal,
); );
let progress_text = match &self.current_progress { job.append(&self.status, Srgba::WHITE);
CurrentProgress::Starting => String::from("Starting download..."),
CurrentProgress::Download(progress) => match progress {
DownloadProgress::Percentage(progress) => {
let percent = (progress * 100.0) as u32;
format!("Downloading assets... ({})", percent)
}
DownloadProgress::TotalBytes(total_bytes) => {
format!("Downloading assets... ({})", format_bytes(*total_bytes))
}
},
};
job.append(&progress_text, Srgba::WHITE);
let layout = app_state.fonts.layout(job, app_state.window.scale_factor); let layout = app_state.fonts.layout(job, app_state.window.scale_factor());
// center text vertically and horizontally
let screen_size = app_state.window.logical_size().cast::<f32>(); let screen_size = app_state.window.logical_size().cast::<f32>();
let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0); let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0);
@@ -149,171 +133,243 @@ impl InstallMode {
primitive: DrawPrimitive::Text(primitive), primitive: DrawPrimitive::Text(primitive),
}; };
let primitives = vec![clipped_primitive]; Box::new(vec![clipped_primitive].into_iter())
Box::new(primitives.into_iter())
} }
} }
// Helper function for writing status to both the message channel and the log
fn report(tx: &mpsc::Sender<Progress>, msg: impl Into<String>) {
let msg = msg.into();
log::info!("{msg}");
let _ = tx.send(Progress::Status(msg));
}
/// Performs full installation of PoB assets into `target_dir`.
///
/// Skips installation if `rpob.version` already exists.
///
/// Steps:
/// 1. Fetch the compatibility table to determine which PoB version is
/// supported by the current Rusty PoB version.
/// 2. Download and extract the PoB release tarball into `target_dir`.
/// 3. Replace `UpdateCheck.lua` with a patched version and update its
/// checksum in `manifest.xml`. This is needed to support PoB native updater.
/// 4. Set the branch and platform fields in `manifest.xml`.
/// 5. Write `rpob.version` to mark the installation as complete.
fn install<P: AsRef<Path>>( fn install<P: AsRef<Path>>(
target_dir: P, target_dir: P,
game: Game,
progress_tx: &mpsc::Sender<Progress>, progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
// Skip installation if version file exists let target_dir = target_dir.as_ref();
let version_file_path = target_dir.as_ref().join("rpob.version"); let client = build_client()?;
if version_file_path.exists() {
let old_version = fs::read_to_string(&version_file_path).unwrap();
let current_version = env!("CARGO_PKG_VERSION");
let version_file_path = target_dir.join("rpob.version");
let current_version = env!("CARGO_PKG_VERSION");
if version_file_path.exists() {
let old_version = fs::read_to_string(&version_file_path)?;
if old_version != current_version { if old_version != current_version {
log::info!("New version detected: {old_version} -> {current_version}"); log::info!("Version changed: {old_version} -> {current_version}");
fs::write(&version_file_path, current_version).unwrap(); fs::write(&version_file_path, current_version).unwrap();
} }
return Ok(()); return Ok(());
} }
download_path_of_building(&target_dir, progress_tx)?; report(progress_tx, "Fetching compatibility info...");
replace_updatecheck(&target_dir)?; let compat_info = fetch_compatibility_info(&client, game)?;
set_branch_and_platform(&target_dir)?; let pob_version = highest_supported_pob_version(&compat_info, current_version)
.ok_or_else(|| anyhow::anyhow!("Unable to determine supported PoB version"))?;
log::info!("Using PoB version: {pob_version}");
// write version file report(progress_tx, "Downloading assets...");
fs::write(&version_file_path, env!("CARGO_PKG_VERSION")).unwrap(); download_pob(&client, target_dir, game, pob_version, progress_tx)?;
report(progress_tx, "Finalizing installation...");
replace_updatecheck(&client, target_dir)?;
set_branch_and_platform(target_dir)?;
fs::write(&version_file_path, current_version)?;
log::info!("Installation complete.");
Ok(()) Ok(())
} }
/// Downloads latest release of Path of Building #[derive(Debug)]
fn download_path_of_building<P: AsRef<Path>>( struct VersionReq {
pob_ver: String,
min_rpob_ver: String,
}
/// Fetches compatibility info
fn fetch_compatibility_info(
client: &reqwest::blocking::Client,
game: Game,
) -> anyhow::Result<Vec<VersionReq>> {
let file_name = match game {
Game::Poe1 => "Compatibility_pob1.lua",
Game::Poe2 => "Compatibility_pob2.lua",
};
let compatibility_info_file = fetch_file_contents(client, COMPAT_REPO, file_name)?;
// Load and evaluate compatibility file contents as Lua code
let lua = mlua::Lua::new();
let compatibility_table = lua.load(compatibility_info_file).eval::<mlua::Table>()?;
// Compatibility table maps PoB version to minimum required Rusty PoB version.
// Beta versions have a non-semver suffix and are filtered out by the regex.
Ok(compatibility_table
.pairs::<String, String>()
.filter_map(|p| p.ok())
.filter(|(pob_version, _)| VERSION_RE.is_match(pob_version))
.map(|(pob_version, min_req_rpob_ver)| VersionReq {
pob_ver: pob_version,
min_rpob_ver: min_req_rpob_ver,
})
.collect())
}
/// Determines the highest PoB version supported by the given Rusty PoB version.
fn highest_supported_pob_version<'a>(
compatibility_info: &'a [VersionReq],
rpob_version: &str,
) -> Option<&'a str> {
let mut highest: Option<&str> = None;
for VersionReq {
pob_ver,
min_rpob_ver,
} in compatibility_info
{
if is_higher_version(min_rpob_ver, rpob_version).unwrap_or(false) {
match highest {
Some(h) if !is_higher_version(h, pob_ver).unwrap_or(false) => {}
_ => highest = Some(pob_ver.as_str()),
}
}
}
highest
}
fn download_pob<P: AsRef<Path>>(
client: &reqwest::blocking::Client,
target_dir: P, target_dir: P,
game: Game,
pob_version: &str,
progress_tx: &mpsc::Sender<Progress>, progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
log::info!("Downloading Path of Building assets..."); let target_dir = target_dir.as_ref();
let repo = match Game::current() { let pob_repo = match game {
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding", Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2", Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2",
}; };
let url = format!(
"https://github.com/{}/archive/refs/heads/master.tar.gz",
repo
);
let mut response = http_get_with_backoff(&url)?; let rules = vec![
let total_size = response ExtractionRule::File {
.headers() tarball_path: "manifest.xml".into(),
.get("Content-Length") dest_path: target_dir.join("manifest.xml"),
.and_then(|s| s.to_str().ok()?.parse::<u64>().ok()); },
ExtractionRule::File {
tarball_path: "help.txt".into(),
dest_path: target_dir.join("help.txt"),
},
ExtractionRule::File {
tarball_path: "changelog.txt".into(),
dest_path: target_dir.join("changelog.txt"),
},
ExtractionRule::File {
tarball_path: "LICENSE.md".into(),
dest_path: target_dir.join("LICENSE.md"),
},
ExtractionRule::RewritePrefix {
prefix: "src/".into(),
dest_dir: target_dir.to_path_buf(),
},
ExtractionRule::RewritePrefix {
prefix: "runtime/lua/".into(),
dest_dir: target_dir.join("lua"),
},
];
let body_reader = response.body_mut().as_reader(); download_and_extract_tarball(
let mut archive = tar::Archive::new(GzDecoder::new(body_reader)); &client,
let mut downloaded = 0u64; pob_repo,
&format!("v{pob_version}"),
for file in archive.entries()? { &rules,
let mut file = file?; 5,
let file_path = file.path()?; &mut |event| {
let components: Vec<_> = file_path.components().collect(); let msg = match event {
DownloadEvent::Progress {
let target_path = match components.len() { downloaded,
0..=1 => None, total: Some(total),
// put these into target_dir/ } => {
2 => { let pct = (downloaded as f32 / total as f32 * 100.0) as u32;
let filename = components[1].as_os_str(); format!("Downloading assets... ({pct}%)")
if filename == "manifest.xml"
|| filename == "help.txt"
|| filename == "changelog.txt"
|| filename == "LICENSE.md"
{
Some(target_dir.as_ref().join(filename))
} else {
None
} }
} DownloadEvent::Progress {
// put lua runtime files into target_dir/lua/ downloaded,
3.. => { total: None,
if components[1].as_os_str() == "src" } => {
|| (components[1].as_os_str() == "runtime" format!("Downloading assets... ({})", format_bytes(downloaded))
&& components[2].as_os_str() == "lua")
{
Some(
target_dir
.as_ref()
.join(components[2..].iter().collect::<PathBuf>()),
)
} else {
None
} }
} DownloadEvent::Retrying { attempt } => {
}; format!("Retrying... (Attempt {})", attempt)
}
// create needed directories and extract };
if let Some(target_path) = target_path { let _ = progress_tx.send(Progress::Status(msg));
if let Some(parent) = target_path.parent() { },
fs::create_dir_all(parent)?; )?;
}
file.unpack(&target_path)?;
}
downloaded += file.size();
if let Some(total) = total_size {
let progress = downloaded as f32 / total as f32;
progress_tx.send(Progress::Download(DownloadProgress::Percentage(progress)))?;
} else {
progress_tx.send(Progress::Download(DownloadProgress::TotalBytes(downloaded)))?;
}
}
Ok(()) Ok(())
} }
/// Replaces UpdateCheck with rusty-path-of-building's custom version of it. /// Replaces UpdateCheck.lua with rusty-path-of-building's modified version and
fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> { /// updates its checksum in manifest.xml.
log::info!("Downloading custom UpdateCheck.lua script..."); fn replace_updatecheck<P: AsRef<Path>>(
client: &reqwest::blocking::Client,
target_dir: P,
) -> anyhow::Result<()> {
let target_dir = target_dir.as_ref();
let file_name = "UpdateCheck.lua";
download_file( download_file_to_disk(client, COMPAT_REPO, file_name, target_dir.join(file_name))?;
&format!(
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}", // .sha1 file format: "<checksum> UpdateCheck.lua" - we only need the checksum.
"UpdateCheck.lua" let sha1_contents = fetch_file_contents(client, COMPAT_REPO, "UpdateCheck.lua.sha1")?;
), let new_checksum = sha1_contents
target_dir.as_ref().join("UpdateCheck.lua"), .split_whitespace()
)?; .next()
.ok_or_else(|| anyhow::anyhow!("Invalid checksum file format"))?;
let manifest_path = target_dir.join("manifest.xml");
let manifest = fs::read_to_string(&manifest_path)?;
let new_manifest = replace_in_matching_lines(
&manifest,
r#"name="UpdateCheck.lua""#,
r#"sha1="([0-9A-Za-z]+)""#,
&format!(r#"sha1="{new_checksum}""#),
);
fs::write(&manifest_path, &new_manifest)?;
Ok(()) Ok(())
} }
/// Sets branch and platform in manifest.xml /// Sets branch and platform in manifest.xml
fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> { fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
let filename = target_dir.as_ref().join("manifest.xml"); let path = target_dir.as_ref().join("manifest.xml");
let manifest = fs::read_to_string(&filename)?; let manifest = fs::read_to_string(&path)?;
#[cfg(not(target_os = "windows"))]
let platform = std::env::consts::OS;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let platform = "win32"; let platform = "win32";
#[cfg(not(target_os = "windows"))]
let platform = std::env::consts::OS;
let new_version = format!(r#"<Version branch="master" platform="{}""#, platform); let replacement = format!(r#"<Version branch="master" platform="{platform}""#);
let new_manifest = MANIFEST_VERSION_RE.replace(&manifest, replacement);
let version_regex = Regex::new(r"<Version").unwrap(); fs::write(&path, new_manifest.as_ref())?;
let new_manifest = version_regex.replace(&manifest, new_version);
fs::write(&filename, new_manifest.as_ref())?;
Ok(()) Ok(())
} }
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
let mut response = http_get_with_backoff(url)?;
if response.status().is_success() {
let body = response.body_mut();
let mut file = fs::File::create(file_path)?;
copy(&mut body.as_reader(), &mut file)?;
Ok(())
} else {
bail!("Unable to download: {}", url);
}
}
fn format_bytes(size_in_bytes: u64) -> String { fn format_bytes(size_in_bytes: u64) -> String {
const KB: u64 = 1024; const KB: u64 = 1024;
const MB: u64 = KB * 1024; const MB: u64 = KB * 1024;
@@ -326,108 +382,129 @@ fn format_bytes(size_in_bytes: u64) -> String {
} else if size_in_bytes >= KB { } else if size_in_bytes >= KB {
format!("{:.2} KB", size_in_bytes as f64 / KB as f64) format!("{:.2} KB", size_in_bytes as f64 / KB as f64)
} else { } else {
format!("{} bytes", size_in_bytes) format!("{size_in_bytes} bytes")
} }
} }
/// Calculates wait time based on rate limit headers or falls back to default backoff. /// Returns true if `v2` is greater than or equal to `v1`.
fn calculate_wait_time(resp: &Response<ureq::Body>, default_backoff: u64) -> u64 { fn is_higher_version(v1: &str, v2: &str) -> anyhow::Result<bool> {
let headers = resp.headers(); let parse_version = |v: &str| -> anyhow::Result<(u32, u32, u32)> {
let caps = VERSION_RE
.captures(v)
.ok_or_else(|| anyhow::anyhow!("Invalid semver format: {}", v))?;
// Wait for time specified in retry-after response header if present let major = caps[1].parse::<u32>().unwrap();
if let Some(retry_after) = headers let minor = caps[2].parse::<u32>().unwrap();
.get("retry-after") let patch = caps[3].parse::<u32>().unwrap();
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
return retry_after;
}
// The number of requests remaining in the current rate limit window Ok((major, minor, patch))
let remaining = headers };
.get("x-ratelimit-remaining")
.and_then(|v| v.to_str().ok());
if remaining == Some("0") { let (major1, minor1, patch1) = parse_version(v1)?;
// Calculate time until rate limit reset let (major2, minor2, patch2) = parse_version(v2)?;
if let Some(reset_epoch) = headers
.get("x-ratelimit-reset")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
let now_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if reset_epoch > now_epoch { Ok(major2 > major1
return reset_epoch - now_epoch; || (major2 == major1 && minor2 > minor1)
} || (major2 == major1 && minor2 == minor1 && patch2 >= patch1))
}
}
default_backoff
} }
/// Performs a GET request with exponential backoff aware of GitHub rate limit headers. #[cfg(test)]
fn http_get_with_backoff(url: &str) -> anyhow::Result<Response<ureq::Body>> { mod tests {
const MAX_ATTEMPTS: usize = 6; use super::*;
const MAX_BACKOFF_SECS: u64 = 60;
let mut attempt = 0;
let mut backoff_secs: u64 = 2;
loop { #[test]
attempt += 1; fn test_major_version() {
let resp_result = ureq::get(url) assert!(is_higher_version("1.0.0", "2.0.0").unwrap());
.header("User-Agent", "rusty-path-of-building") assert!(!is_higher_version("2.0.0", "1.0.0").unwrap());
.call(); }
let resp = match resp_result { #[test]
Ok(r) => r, fn test_minor_version() {
Err(err) => { assert!(is_higher_version("1.5.0", "1.6.0").unwrap());
log::warn!( assert!(!is_higher_version("1.10.0", "1.9.0").unwrap());
"Transport error: {} (attempt {}/{})", }
err,
attempt,
MAX_ATTEMPTS
);
if attempt >= MAX_ATTEMPTS {
return Err(anyhow::Error::new(err));
}
thread::sleep(Duration::from_secs(backoff_secs));
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
continue;
}
};
let status = resp.status(); #[test]
if status == 403 || status == 429 { fn test_patch_version() {
let wait = calculate_wait_time(&resp, backoff_secs); assert!(is_higher_version("1.0.3", "1.0.4").unwrap());
assert!(!is_higher_version("1.0.10", "1.0.9").unwrap());
}
log::warn!( #[test]
"Rate limited (status {}). Waiting {}s before retry (attempt {}/{})", fn test_same_version() {
status, assert!(is_higher_version("1.5.3", "1.5.3").unwrap());
wait, }
attempt,
MAX_ATTEMPTS
);
if attempt >= MAX_ATTEMPTS {
return Err(anyhow::anyhow!(
"HTTP {} after {} attempts for {}",
status,
attempt,
url
));
}
thread::sleep(Duration::from_secs(wait));
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
continue;
}
if status.is_client_error() || status.is_server_error() { #[test]
return Err(anyhow::anyhow!("http status: {} for {}", status, url)); fn test_invalid_semver_format() {
} assert!(is_higher_version("1.0", "2.0.0").is_err());
assert!(is_higher_version("1.0.0", "2.0").is_err());
assert!(is_higher_version("invalid", "2.0.0").is_err());
assert!(is_higher_version("1.0.0", "a.bb.ccc").is_err());
}
return Ok(resp); #[test]
fn test_highest_supported_pob_ver() {
let compat_info = vec![
VersionReq {
pob_ver: "2.56.0".into(),
min_rpob_ver: "0.1.0".into(),
},
// compat info might not be sorted by pob_version
VersionReq {
pob_ver: "2.58.0".into(),
min_rpob_ver: "0.2.6".into(),
},
VersionReq {
pob_ver: "2.57.0".into(),
min_rpob_ver: "0.2.6".into(),
},
VersionReq {
pob_ver: "2.58.1".into(),
min_rpob_ver: "0.2.8".into(),
},
VersionReq {
pob_ver: "2.59.0".into(),
min_rpob_ver: "0.2.9".into(),
},
VersionReq {
pob_ver: "2.59.1".into(),
min_rpob_ver: "0.2.10".into(),
},
VersionReq {
pob_ver: "2.59.2".into(),
min_rpob_ver: "0.2.10".into(),
},
];
assert_eq!(highest_supported_pob_version(&compat_info, "0.0.2"), None);
assert_eq!(highest_supported_pob_version(&compat_info, "a.b.c"), None);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.1.0"),
Some("2.56.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.0"),
Some("2.56.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.6"),
Some("2.58.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.7"),
Some("2.58.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.8"),
Some("2.58.1")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.9"),
Some("2.59.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.10"),
Some("2.59.2")
);
} }
} }
+266
View File
@@ -0,0 +1,266 @@
use std::{
fmt,
fs::{self, File},
io::{self, Read, Write},
path::{Path, PathBuf},
thread,
time::{Duration, Instant},
};
use flate2::read::GzDecoder;
use reqwest::blocking::{Client, Response};
use tar::Archive;
#[derive(Debug)]
pub enum DownloadEvent {
Progress { downloaded: u64, total: Option<u64> },
Retrying { attempt: u32 },
}
/// Build a reqwest blocking client
pub fn build_client() -> Result<Client, reqwest::Error> {
Client::builder().timeout(Duration::from_secs(60)).build()
}
// Rate-limit-aware GET.
//
// `raw.githubusercontent.com` doesn't seem to use `x-ratelimit-reset` and
// `x-ratelimit-remaining` headers like the API so only the status code is checked.
fn get_checked(client: &Client, url: &str) -> Result<Response, GithubError> {
let response = client.get(url).send()?;
let status = response.status();
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
let retry_after_secs = response
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(60);
return Err(GithubError::RateLimited {
retry_after_s: retry_after_secs,
});
}
if !status.is_success() {
return Err(GithubError::Http {
status: status.as_u16(),
url: url.to_string(),
});
}
Ok(response)
}
/// Wrapper to retry `f` up to `max_retries` times
pub fn with_retry<T, F>(max_retries: u32, base_delay: Duration, mut f: F) -> Result<T, GithubError>
where
F: FnMut(u32) -> Result<T, GithubError>,
{
let mut attempt = 0;
loop {
match f(attempt) {
Err(GithubError::RateLimited {
retry_after_s: retry_after_secs,
}) if attempt < max_retries => {
log::warn!("Rate limited – sleeping {retry_after_secs}s (attempt {attempt})");
thread::sleep(Duration::from_secs(retry_after_secs));
attempt += 1;
}
Err(GithubError::Network(e)) if attempt < max_retries => {
let delay = base_delay * (attempt + 1);
log::warn!("Network error on attempt {attempt}: {e}. Retrying in {delay:?}");
thread::sleep(delay);
attempt += 1;
}
other => return other,
}
}
}
/// Download file contents from raw.githubusercontent.com into a `String`.
pub fn fetch_file_contents(
client: &Client,
repo: &str,
file_name: &str,
) -> Result<String, GithubError> {
let url = format!("https://raw.githubusercontent.com/{repo}/main/{file_name}");
let response = get_checked(client, &url)?;
Ok(response.text()?)
}
/// Download a file from raw.githubusercontent.com and write it to `dest_path`.
pub fn download_file_to_disk<P: AsRef<Path>>(
client: &Client,
repo: &str,
file_name: &str,
dest_path: P,
) -> Result<(), GithubError> {
let dest_path = dest_path.as_ref();
let url = format!("https://raw.githubusercontent.com/{repo}/main/{file_name}");
let mut response = get_checked(client, &url)?;
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
let mut file = File::create(dest_path)?;
io::copy(&mut response, &mut file)?;
Ok(())
}
/// A rule describing how to map tarball entries to destination paths.
///
/// The root prefix is automatically striped and doesn't need to be specified.
pub enum ExtractionRule {
/// Map a single file to an exact destination path.
File {
tarball_path: String,
dest_path: PathBuf,
},
/// Strip prefix from matching entries and place the remainder under `dest_dir`.
RewritePrefix { prefix: String, dest_dir: PathBuf },
}
/// Download a GitHub release tarball and extract entries to specified destinations.
pub fn download_and_extract_tarball(
client: &Client,
repo_name: &str,
tag: &str,
rules: &[ExtractionRule],
max_retries: u32,
on_progress: &mut impl FnMut(DownloadEvent),
) -> Result<(), GithubError> {
let url = format!("https://github.com/{repo_name}/archive/refs/tags/{tag}.tar.gz");
let tmp_path =
std::env::temp_dir().join(format!("gh-{}-{}.tar.gz", repo_name.replace('/', "-"), tag));
// Download to temp file
with_retry(max_retries, Duration::from_secs(5), |attempt| {
if attempt > 0 {
on_progress(DownloadEvent::Retrying { attempt });
}
let response = get_checked(client, &url)?;
let content_length = response.content_length();
let mut tmp_file = File::create(&tmp_path)?;
const CHUNK_SIZE: usize = 512 * 1024;
let mut chunk = vec![0u8; CHUNK_SIZE];
let mut downloaded: u64 = 0;
let mut body = response;
let mut last_progress = Instant::now();
const PROGRESS_INTERVAL: Duration = Duration::from_millis(50);
loop {
let n = body.read(&mut chunk)?;
if n == 0 {
break;
}
tmp_file.write_all(&chunk[..n])?;
downloaded += n as u64;
if last_progress.elapsed() >= PROGRESS_INTERVAL {
on_progress(DownloadEvent::Progress {
downloaded,
total: content_length,
});
last_progress = Instant::now();
}
}
on_progress(DownloadEvent::Progress {
downloaded,
total: content_length,
});
Ok(())
})?;
// Extract tarball to destination based on extract rules
let tmp_file = File::open(&tmp_path)?;
let gz = GzDecoder::new(io::BufReader::new(tmp_file));
let mut archive = Archive::new(gz);
for entry_result in archive.entries()? {
let mut entry = entry_result?;
let entry_path = entry.path()?.to_path_buf();
let entry_str = entry_path.to_string_lossy();
// Skip directory entries
if entry_str.ends_with('/') {
continue;
}
// Strip root folder before matching against rules
let relative = match entry_str.split_once('/') {
Some((_, rest)) => rest,
None => continue,
};
let dest: Option<PathBuf> = rules.iter().find_map(|rule| match rule {
ExtractionRule::File {
tarball_path,
dest_path,
} => (tarball_path == relative).then(|| dest_path.clone()),
ExtractionRule::RewritePrefix { prefix, dest_dir } => relative
.strip_prefix(prefix)
.map(|tail| dest_dir.join(tail)),
});
if let Some(dest_path) = dest {
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
let mut dest_file = File::create(&dest_path)?;
io::copy(&mut entry, &mut dest_file)?;
}
}
fs::remove_file(&tmp_path)?;
Ok(())
}
#[derive(Debug)]
pub enum GithubError {
Http { status: u16, url: String },
RateLimited { retry_after_s: u64 },
Network(reqwest::Error),
Io(io::Error),
}
impl fmt::Display for GithubError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Http { status, url } => write!(f, "HTTP error {status}: {url}"),
Self::RateLimited { retry_after_s } => {
write!(f, "Rate limited – retry after {retry_after_s}s")
}
Self::Network(e) => write!(f, "Network error: {e}"),
Self::Io(e) => write!(f, "I/O error: {e}"),
}
}
}
impl std::error::Error for GithubError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Network(e) => Some(e),
Self::Io(e) => Some(e),
_ => None,
}
}
}
impl From<reqwest::Error> for GithubError {
fn from(e: reqwest::Error) -> Self {
Self::Network(e)
}
}
impl From<io::Error> for GithubError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
+98 -57
View File
@@ -1,5 +1,4 @@
use crate::{ use crate::{
Game,
api::{self, get_callback}, api::{self, get_callback},
app::AppState, app::AppState,
args::Args, args::Args,
@@ -12,16 +11,16 @@ use crate::{
util::change_working_directory, util::change_working_directory,
window::WindowState, window::WindowState,
}; };
use arboard::Clipboard;
use clap::Parser; use clap::Parser;
use mlua::{Lua, Result as LuaResult, Table}; use mlua::{Function, Lua, Result as LuaResult, Table, ThreadStatus};
use std::{ use std::{
cell::{Cell, RefCell}, cell::{Cell, RefCell},
path::PathBuf, path::PathBuf,
rc::Rc, rc::Rc,
}; };
use winit::keyboard::SmolStr;
macro_rules! socket_accessor { macro_rules! ctx_accessor {
($field:ident: & $ty:ty) => { ($field:ident: & $ty:ty) => {
pub fn $field(&self) -> &$ty { pub fn $field(&self) -> &$ty {
let ptr = self.$field.get(); let ptr = self.$field.get();
@@ -42,77 +41,82 @@ macro_rules! socket_accessor {
/// A collection of pointers needed by the API funtions. /// A collection of pointers needed by the API funtions.
/// ///
/// Before executing any lua code, we need to "plug" the [`PoBContext`] into /// Before executing any lua code, we need to "plug" the references into
/// the ContextSocket and "unplug" them afterwards. /// the Context and "unplug" them afterwards.
pub struct ContextSocket { pub struct Context {
window: Cell<*const WindowState>, window: Cell<*mut WindowState>,
input: Cell<*const InputState>, input: Cell<*const InputState>,
fonts: Cell<*mut Fonts>, fonts: Cell<*mut Fonts>,
texture_manager: Cell<*mut WrappedTextureManager>, texture_manager: Cell<*mut WrappedTextureManager>,
clipboard: Cell<*mut Clipboard>, script_dir: Cell<*const PathBuf>,
current_working_dir: Cell<*mut PathBuf>, current_working_dir: Cell<*mut PathBuf>,
layers: Cell<*mut Layers>, layers: Cell<*mut Layers>,
needs_restart: Cell<*mut bool>, needs_restart: Cell<*mut bool>,
should_exit: Cell<*mut bool>,
is_dpi_aware: Cell<*mut bool>, is_dpi_aware: Cell<*mut bool>,
} }
impl ContextSocket { impl Context {
pub fn new() -> &'static Self { pub fn new() -> &'static Self {
Box::leak(Box::new(Self { Box::leak(Box::new(Self {
window: Cell::new(std::ptr::null()), window: Cell::new(std::ptr::null_mut()),
input: Cell::new(std::ptr::null()), input: Cell::new(std::ptr::null()),
fonts: Cell::new(std::ptr::null_mut()), fonts: Cell::new(std::ptr::null_mut()),
texture_manager: Cell::new(std::ptr::null_mut()), texture_manager: Cell::new(std::ptr::null_mut()),
clipboard: Cell::new(std::ptr::null_mut()), script_dir: Cell::new(std::ptr::null()),
current_working_dir: Cell::new(std::ptr::null_mut()), current_working_dir: Cell::new(std::ptr::null_mut()),
layers: Cell::new(std::ptr::null_mut()), layers: Cell::new(std::ptr::null_mut()),
needs_restart: Cell::new(std::ptr::null_mut()), needs_restart: Cell::new(std::ptr::null_mut()),
should_exit: Cell::new(std::ptr::null_mut()),
is_dpi_aware: Cell::new(std::ptr::null_mut()), is_dpi_aware: Cell::new(std::ptr::null_mut()),
})) }))
} }
pub fn set(&self, ctx: &mut PoBContext) { pub fn set(&self, ctx: &mut PoBContext) {
self.window.set(&ctx.app.window); self.window.set(&mut ctx.app.window);
self.input.set(&ctx.app.input); self.input.set(&ctx.app.input);
self.fonts.set(&mut ctx.app.fonts); self.fonts.set(&mut ctx.app.fonts);
self.texture_manager.set(&mut ctx.app.texture_manager); self.texture_manager.set(&mut ctx.app.texture_manager);
self.clipboard.set(&mut ctx.app.clipboard); self.script_dir.set(&mut ctx.app.script_dir);
self.current_working_dir self.current_working_dir
.set(&mut ctx.pob.current_working_dir); .set(&mut ctx.pob.current_working_dir);
self.layers.set(&mut ctx.pob.layers); self.layers.set(&mut ctx.pob.layers);
self.needs_restart.set(&mut ctx.pob.needs_restart); self.needs_restart.set(&mut ctx.pob.needs_restart);
self.should_exit.set(&mut ctx.app.should_exit);
self.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware); self.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware);
} }
pub fn clear(&self) { pub fn clear(&self) {
self.window.set(std::ptr::null()); self.window.set(std::ptr::null_mut());
self.input.set(std::ptr::null()); self.input.set(std::ptr::null());
self.fonts.set(std::ptr::null_mut()); self.fonts.set(std::ptr::null_mut());
self.texture_manager.set(std::ptr::null_mut()); self.texture_manager.set(std::ptr::null_mut());
self.clipboard.set(std::ptr::null_mut()); self.script_dir.set(std::ptr::null());
self.current_working_dir.set(std::ptr::null_mut()); self.current_working_dir.set(std::ptr::null_mut());
self.layers.set(std::ptr::null_mut()); self.layers.set(std::ptr::null_mut());
self.needs_restart.set(std::ptr::null_mut()); self.needs_restart.set(std::ptr::null_mut());
self.should_exit.set(std::ptr::null_mut());
self.is_dpi_aware.set(std::ptr::null_mut()); self.is_dpi_aware.set(std::ptr::null_mut());
} }
socket_accessor!(window: &WindowState); ctx_accessor!(window: &mut WindowState);
socket_accessor!(input: &InputState); ctx_accessor!(input: &InputState);
socket_accessor!(fonts: &mut Fonts); ctx_accessor!(fonts: &mut Fonts);
socket_accessor!(texture_manager: &mut WrappedTextureManager); ctx_accessor!(texture_manager: &mut WrappedTextureManager);
socket_accessor!(clipboard: &mut Clipboard); ctx_accessor!(script_dir: &PathBuf);
socket_accessor!(current_working_dir: &mut PathBuf); ctx_accessor!(current_working_dir: &mut PathBuf);
socket_accessor!(layers: &mut Layers); ctx_accessor!(layers: &mut Layers);
socket_accessor!(needs_restart: &mut bool); ctx_accessor!(needs_restart: &mut bool);
socket_accessor!(is_dpi_aware: &mut bool); ctx_accessor!(should_exit: &mut bool);
ctx_accessor!(is_dpi_aware: &mut bool);
} }
pub enum PoBEvent { pub enum PoBEvent {
Init, Init,
Exit, Exit,
Frame, Frame,
KeyDown(&'static str, bool), KeyDown(SmolStr, bool),
KeyUp(&'static str), KeyUp(SmolStr),
Char(char), Char(char),
SubFinished { SubFinished {
id: u64, id: u64,
@@ -160,10 +164,10 @@ pub struct LuaInstance {
} }
impl LuaInstance { impl LuaInstance {
pub fn new() -> anyhow::Result<Self> { pub fn new(script_dir: &PathBuf) -> anyhow::Result<Self> {
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new())); let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new(script_dir.to_owned())));
let lua = Self::create_lua_state()?; let lua = Self::create_lua_state(script_dir)?;
register_subscript_globals(&lua, &subscript_manager)?; register_subscript_globals(&lua, &subscript_manager)?;
Ok(Self { Ok(Self {
@@ -172,20 +176,20 @@ impl LuaInstance {
}) })
} }
fn create_lua_state() -> LuaResult<Lua> { fn create_lua_state(script_dir: &PathBuf) -> LuaResult<Lua> {
// SAFETY: use `unsafe_new` to allow loading of C modules // SAFETY: use `unsafe_new` to allow loading of C modules
let lua = unsafe { Lua::unsafe_new() }; let lua = unsafe { Lua::unsafe_new() };
// expose build arg to lua // expose import url to lua
let args = Args::parse(); let args = Args::parse();
let args_table = lua.create_sequence_from(std::iter::once(args.build_path))?; let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
lua.globals().set("arg", args_table)?; lua.globals().set("arg", args_table)?;
Self::register_package_paths(&lua)?; Self::register_package_paths(&lua, script_dir)?;
// register "socket" // register context
let socket = ContextSocket::new(); let ctx = Context::new();
lua.set_app_data(socket); lua.set_app_data(ctx);
// register callbacks // register callbacks
api::register_globals(&lua)?; api::register_globals(&lua)?;
@@ -194,52 +198,90 @@ impl LuaInstance {
} }
/// Loads and executes PoB's Launch.lua script /// Loads and executes PoB's Launch.lua script
pub fn launch(&self, ctx: &mut PoBContext) -> LuaResult<()> { pub fn launch(&self, pob_ctx: &mut PoBContext) -> LuaResult<()> {
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
socket.set(ctx); ctx.set(pob_ctx);
let script_dir = Game::script_dir(); let script_dir = pob_ctx.app.script_dir.as_path();
change_working_directory(script_dir.as_path())?; change_working_directory(script_dir)?;
self.load(script_dir.join("Launch.lua")).exec()?; self.load(script_dir.join("Launch.lua")).exec()?;
socket.clear(); ctx.clear();
Ok(()) Ok(())
} }
pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> { pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> {
self.lua = Self::create_lua_state()?; self.lua = Self::create_lua_state(&ctx.app.script_dir)?;
register_subscript_globals(&self.lua, &self.subscript_manager)?; register_subscript_globals(&self.lua, &self.subscript_manager)?;
self.launch(ctx)?; self.launch(ctx)?;
Ok(()) Ok(())
} }
/// Run functions for subscripts and handle their completion/failure. /// Run functions for subscripts and handle their completion/failure.
pub fn handle_subscripts(&self, ctx: &mut PoBContext) { pub fn handle_subscripts(&self, pob_ctx: &mut PoBContext) {
profiling::scope!("handle_subscripts"); profiling::scope!("handle_subscripts");
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
ctx.set(pob_ctx);
let subscript_events = self.subscript_manager.borrow_mut().process(self); let subscript_events = self.subscript_manager.borrow_mut().process(self);
ctx.clear();
// Handle finished/errored subscripts. // Handle finished/errored subscripts.
for event in subscript_events { for event in subscript_events {
match event { match event {
SubscriptResult::SubscriptFinished { id, return_values } => { SubscriptResult::SubscriptFinished { id, return_values } => {
self.handle_event(PoBEvent::SubFinished { id, return_values }, ctx) self.handle_event(PoBEvent::SubFinished { id, return_values }, pob_ctx)
.unwrap(); .unwrap();
} }
SubscriptResult::SubscriptError { id, error } => { SubscriptResult::SubscriptError { id, error } => {
self.handle_event(PoBEvent::SubError { id, error }, ctx) self.handle_event(PoBEvent::SubError { id, error }, pob_ctx)
.unwrap(); .unwrap();
} }
} }
} }
} }
pub fn handle_event(&self, event: PoBEvent, ctx: &mut PoBContext) -> LuaResult<()> { pub fn has_running_subscripts(&self) -> bool {
self.subscript_manager.borrow().has_running_subscripts()
}
pub fn has_active_coroutine(&self) -> bool {
self.get_coroutines().is_ok_and(|coroutines| {
coroutines.pairs::<mlua::Thread, bool>().any(|pair| {
pair.is_ok_and(|(thread, _)| {
matches!(
thread.status(),
ThreadStatus::Resumable | ThreadStatus::Running
)
})
})
})
}
fn get_coroutines(&self) -> LuaResult<Table> {
let coroutine_module: Table = self.lua.globals().get("coroutine")?;
let list_func: Function = coroutine_module.get("_list")?;
list_func.call::<Table>(())
}
pub fn can_exit(&self, pob_ctx: &mut PoBContext) -> bool {
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
ctx.set(pob_ctx);
let can_exit = get_callback(&self.lua, "CanExit")
.and_then(|f| f.call(()))
.unwrap_or(true);
ctx.clear();
can_exit
}
pub fn handle_event(&self, event: PoBEvent, pob_ctx: &mut PoBContext) -> LuaResult<()> {
profiling::scope!("handle_event", format!("{}", event)); profiling::scope!("handle_event", format!("{}", event));
// "Plug" references into "socket" // "Plug" references into context
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
socket.set(ctx); ctx.set(pob_ctx);
// Call event handler in PoB application code // Call event handler in PoB application code
let handler_result = match event { let handler_result = match event {
@@ -247,9 +289,9 @@ impl LuaInstance {
PoBEvent::Exit => get_callback(&self.lua, "OnExit")?.call::<()>(()), PoBEvent::Exit => get_callback(&self.lua, "OnExit")?.call::<()>(()),
PoBEvent::Frame => get_callback(&self.lua, "OnFrame")?.call::<()>(()), PoBEvent::Frame => get_callback(&self.lua, "OnFrame")?.call::<()>(()),
PoBEvent::KeyDown(key, double_click) => { PoBEvent::KeyDown(key, double_click) => {
get_callback(&self.lua, "OnKeyDown")?.call::<()>((key, double_click)) get_callback(&self.lua, "OnKeyDown")?.call::<()>((key.as_str(), double_click))
} }
PoBEvent::KeyUp(key) => get_callback(&self.lua, "OnKeyUp")?.call::<()>(key), PoBEvent::KeyUp(key) => get_callback(&self.lua, "OnKeyUp")?.call::<()>(key.as_str()),
PoBEvent::Char(ch) => get_callback(&self.lua, "OnChar")?.call::<()>(ch), PoBEvent::Char(ch) => get_callback(&self.lua, "OnChar")?.call::<()>(ch),
PoBEvent::SubFinished { id, return_values } => { PoBEvent::SubFinished { id, return_values } => {
get_callback(&self.lua, "OnSubFinished")?.call::<()>((id, return_values)) get_callback(&self.lua, "OnSubFinished")?.call::<()>((id, return_values))
@@ -259,15 +301,14 @@ impl LuaInstance {
} }
}; };
// "Unplug" references from "socket" // "Unplug" references from context
socket.clear(); ctx.clear();
handler_result handler_result
} }
/// Adds "${script_dir}/lua" to package path /// Adds "${script_dir}/lua" to package path
pub fn register_package_paths(lua: &Lua) -> LuaResult<()> { pub fn register_package_paths(lua: &Lua, script_dir: &PathBuf) -> LuaResult<()> {
let script_dir = Game::script_dir();
let package: Table = lua.globals().get("package")?; let package: Table = lua.globals().get("package")?;
let mut package_path: String = package.get("path")?; let mut package_path: String = package.get("path")?;
package_path.push(';'); package_path.push(';');
+26 -6
View File
@@ -1,13 +1,12 @@
use crate::{ use crate::{app::App, args::Args};
app::App,
args::{Args, Game},
};
use clap::Parser; use clap::Parser;
use std::path::{Path, PathBuf};
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
mod api; mod api;
mod app; mod app;
mod args; mod args;
mod clipboard;
mod color; mod color;
mod dpi; mod dpi;
mod fonts; mod fonts;
@@ -39,12 +38,33 @@ fn main() -> anyhow::Result<()> {
}; };
let args = Args::parse(); let args = Args::parse();
Game::init(args.game); let script_dir = find_nearby_launch_script();
let mut app = App::new()?; let mut app = App::new(args.game, script_dir)?;
let event_loop = EventLoop::with_user_event().build()?; let event_loop = EventLoop::with_user_event().build()?;
event_loop.run_app(&mut app)?; event_loop.run_app(&mut app)?;
Ok(()) Ok(())
} }
/// Search for the Launch.lua file in nearby locations
fn find_nearby_launch_script() -> Option<PathBuf> {
let mut candidates = vec![Path::new("Launch.lua"), Path::new("src/Launch.lua")];
if let Ok(cwd) = std::env::current_dir()
&& cwd.ends_with("runtime")
{
candidates.push(Path::new("../src/Launch.lua"));
}
for candidate in candidates {
if candidate.try_exists().is_ok_and(|exists| exists) {
if let Some(Ok(candidate)) = candidate.parent().map(Path::canonicalize) {
return Some(candidate);
}
}
}
None
}
+13 -3
View File
@@ -1,14 +1,14 @@
use crate::{ use crate::{
app::AppState, installer::InstallMode, pob::PoBMode, renderer::primitives::ClippedPrimitive, app::AppState, installer::InstallMode, pob::PoBMode, renderer::primitives::ClippedPrimitive,
}; };
use winit::{event::MouseButton, keyboard::KeyCode}; use winit::{event::MouseButton, keyboard::Key};
pub enum AppEvent { pub enum AppEvent {
KeyDown { KeyDown {
code: KeyCode, key: Key,
}, },
KeyUp { KeyUp {
code: KeyCode, key: Key,
}, },
MouseDown { MouseDown {
button: MouseButton, button: MouseButton,
@@ -34,6 +34,9 @@ pub enum ModeTransition {
pub struct ModeFrameOutput { pub struct ModeFrameOutput {
pub primitives: Box<dyn Iterator<Item = ClippedPrimitive>>, pub primitives: Box<dyn Iterator<Item = ClippedPrimitive>>,
pub can_elide: bool, pub can_elide: bool,
/// Indicates that this should be redrawn again next frame even if user is not interacting with
/// window
pub should_continue: bool,
} }
pub enum AppMode { pub enum AppMode {
@@ -62,4 +65,11 @@ impl AppMode {
AppMode::PoB(mode) => mode.handle_event(state, event), AppMode::PoB(mode) => mode.handle_event(state, event),
} }
} }
pub fn can_exit(&mut self, state: &mut AppState) -> bool {
match self {
AppMode::Install(_) => true,
AppMode::PoB(mode) => mode.can_exit(state),
}
}
} }
+21 -10
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
app::AppState, app::AppState,
dpi::{LogicalRect, LogicalSize}, dpi::{LogicalRect, LogicalSize},
input::{keycode_as_str, mousebutton_as_str}, input::{key_as_str, mousebutton_as_str},
layers::Layers, layers::Layers,
lua::{LuaInstance, PoBContext, PoBEvent}, lua::{LuaInstance, PoBContext, PoBEvent},
mode::{AppEvent, ModeFrameOutput, ModeTransition}, mode::{AppEvent, ModeFrameOutput, ModeTransition},
@@ -34,7 +34,7 @@ impl PoBMode {
is_dpi_aware: false, is_dpi_aware: false,
}; };
let lua_instance = LuaInstance::new()?; let lua_instance = LuaInstance::new(&app_state.script_dir)?;
let mut pob_ctx = PoBContext::new(app_state, &mut state); let mut pob_ctx = PoBContext::new(app_state, &mut state);
lua_instance.launch(&mut pob_ctx)?; lua_instance.launch(&mut pob_ctx)?;
@@ -68,9 +68,14 @@ impl PoBMode {
let identical = layers_hash == self.previous_layers_hash; let identical = layers_hash == self.previous_layers_hash;
self.previous_layers_hash = layers_hash; self.previous_layers_hash = layers_hash;
let has_active_subscript = self.lua_instance.has_running_subscripts();
let has_active_coroutine = self.lua_instance.has_active_coroutine();
let should_continue = has_active_subscript || has_active_coroutine;
Ok(ModeFrameOutput { Ok(ModeFrameOutput {
primitives: self.state.layers.consume_layers(), primitives: self.state.layers.consume_layers(),
can_elide: identical, can_elide: identical,
should_continue,
}) })
} }
@@ -92,14 +97,14 @@ impl PoBMode {
let mut ctx = PoBContext::new(app_state, &mut self.state); let mut ctx = PoBContext::new(app_state, &mut self.state);
match event { match event {
AppEvent::KeyDown { code } => { AppEvent::KeyDown { key } => {
if let Some(key_string) = keycode_as_str(code) { if let Some(key_string) = key_as_str(key) {
let pob_event = PoBEvent::KeyDown(key_string, false); let pob_event = PoBEvent::KeyDown(key_string, false);
self.lua_instance.handle_event(pob_event, &mut ctx)?; self.lua_instance.handle_event(pob_event, &mut ctx)?;
} }
} }
AppEvent::KeyUp { code } => { AppEvent::KeyUp { key } => {
if let Some(key_string) = keycode_as_str(code) { if let Some(key_string) = key_as_str(key) {
let pob_event = PoBEvent::KeyUp(key_string); let pob_event = PoBEvent::KeyUp(key_string);
self.lua_instance.handle_event(pob_event, &mut ctx)?; self.lua_instance.handle_event(pob_event, &mut ctx)?;
} }
@@ -122,17 +127,18 @@ impl PoBMode {
AppEvent::MouseWheel { delta } => { AppEvent::MouseWheel { delta } => {
if delta > 0.0 { if delta > 0.0 {
self.lua_instance self.lua_instance
.handle_event(PoBEvent::KeyDown("WHEELUP", false), &mut ctx)?; .handle_event(PoBEvent::KeyDown("WHEELUP".into(), false), &mut ctx)?;
self.lua_instance self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELUP"), &mut ctx)?; .handle_event(PoBEvent::KeyUp("WHEELUP".into()), &mut ctx)?;
} else if delta < 0.0 { } else if delta < 0.0 {
self.lua_instance self.lua_instance
.handle_event(PoBEvent::KeyDown("WHEELDOWN", false), &mut ctx)?; .handle_event(PoBEvent::KeyDown("WHEELDOWN".into(), false), &mut ctx)?;
self.lua_instance self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELDOWN"), &mut ctx)?; .handle_event(PoBEvent::KeyUp("WHEELDOWN".into()), &mut ctx)?;
} }
} }
AppEvent::CharacterInput { ch } => { AppEvent::CharacterInput { ch } => {
let ch = if ch.is_ascii() { ch } else { '?' };
self.lua_instance self.lua_instance
.handle_event(PoBEvent::Char(ch), &mut ctx)?; .handle_event(PoBEvent::Char(ch), &mut ctx)?;
} }
@@ -141,6 +147,11 @@ impl PoBMode {
Ok(()) Ok(())
} }
pub fn can_exit(&mut self, app_state: &mut AppState) -> bool {
let mut ctx = PoBContext::new(app_state, &mut self.state);
self.lua_instance.can_exit(&mut ctx)
}
fn reset_viewport(&mut self, size: LogicalSize<u32>) { fn reset_viewport(&mut self, size: LogicalSize<u32>) {
self.state self.state
.layers .layers
+21 -13
View File
@@ -1,14 +1,14 @@
use std::cell::RefCell; use crate::{api::get_callback, lua::LuaInstance};
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use std::{collections::VecDeque, sync::mpsc::channel, thread::JoinHandle};
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use mlua::{Function, IntoLuaMulti, Lua, Value}; use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Result as LuaResult, Value};
use mlua::{Integer, MultiValue, Number, Result as LuaResult}; use std::{
cell::RefCell,
use crate::api::get_callback; collections::VecDeque,
use crate::lua::LuaInstance; path::PathBuf,
rc::Rc,
sync::mpsc::{Receiver, Sender, TryRecvError, channel},
thread::JoinHandle,
};
#[derive(Debug)] #[derive(Debug)]
pub enum SubscriptResult { pub enum SubscriptResult {
@@ -25,13 +25,15 @@ pub enum SubscriptResult {
pub struct SubscriptManager { pub struct SubscriptManager {
current_id: u64, current_id: u64,
scripts: Vec<Subscript>, scripts: Vec<Subscript>,
script_dir: PathBuf,
} }
impl SubscriptManager { impl SubscriptManager {
pub fn new() -> Self { pub fn new(script_dir: PathBuf) -> Self {
Self { Self {
current_id: 0, current_id: 0,
scripts: Vec::new(), scripts: Vec::new(),
script_dir,
} }
} }
@@ -51,6 +53,7 @@ impl SubscriptManager {
blocking_calls, blocking_calls,
nonblocking_calls, nonblocking_calls,
arguments, arguments,
self.script_dir.clone(),
); );
self.scripts.push(subscript); self.scripts.push(subscript);
id id
@@ -74,6 +77,10 @@ impl SubscriptManager {
results results
} }
pub fn has_running_subscripts(&self) -> bool {
!self.scripts.is_empty()
}
} }
enum SubscriptCall { enum SubscriptCall {
@@ -115,6 +122,7 @@ impl Subscript {
blocking_calls: Vec<String>, blocking_calls: Vec<String>,
nonblocking_calls: Vec<String>, nonblocking_calls: Vec<String>,
arguments: NativeMultiValue, arguments: NativeMultiValue,
script_dir: PathBuf,
) -> Self { ) -> Self {
let (tx, rx) = channel(); let (tx, rx) = channel();
@@ -125,7 +133,7 @@ impl Subscript {
let lua = unsafe { Lua::unsafe_new() }; let lua = unsafe { Lua::unsafe_new() };
// add ./lua to package.path and package.cpath // add ./lua to package.path and package.cpath
LuaInstance::register_package_paths(&lua)?; LuaInstance::register_package_paths(&lua, &script_dir)?;
for function_name in blocking_calls { for function_name in blocking_calls {
let thread_tx = tx.clone(); let thread_tx = tx.clone();
@@ -305,7 +313,7 @@ pub fn register_subscript_globals(
"IsSubScriptRunning", "IsSubScriptRunning",
lua.create_function(is_subscript_running)?, lua.create_function(is_subscript_running)?,
)?; )?;
globals.set("IsSubScriptRunning", lua.create_function(abort_subscript)?)?; globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?;
Ok(()) Ok(())
} }
+25
View File
@@ -27,3 +27,28 @@ pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
t.hash(&mut state); t.hash(&mut state);
state.finish() state.finish()
} }
/// Performs replacement only in lines that match a given pattern
pub fn replace_in_matching_lines(
input: &str,
match_pattern: &str,
replace_pattern: &str,
replacement_text: &str,
) -> String {
let match_re = regex::Regex::new(match_pattern).expect("Invalid match regex");
let replace_re = regex::Regex::new(replace_pattern).expect("Invalid replace regex");
let mut output = String::new();
for line in input.lines() {
if match_re.is_match(line) {
// if line matches the pattern, replace
let replaced_line = replace_re.replace_all(line, replacement_text);
output.push_str(&replaced_line);
} else {
// otherwise, keep original line
output.push_str(line);
}
output.push('\n');
}
output
}
+50 -5
View File
@@ -1,14 +1,21 @@
use crate::{
clipboard::Clipboard,
dpi::{ConvertToLogical, LogicalSize, PhysicalSize},
};
use raw_window_handle::HasDisplayHandle;
use std::sync::Arc; use std::sync::Arc;
use winit::window::Window; use winit::window::Window;
use crate::dpi::{ConvertToLogical, LogicalSize, PhysicalSize};
pub struct WindowState { pub struct WindowState {
// NOTE: clipboard needs to be destroyed before window
clipboard: Option<Clipboard>,
pub window: Option<Arc<Window>>, pub window: Option<Arc<Window>>,
pub size: PhysicalSize<u32>, pub size: PhysicalSize<u32>,
pub scale_factor: f32, scale_factor: f32,
pub scale_factor_override: Option<f32>,
pending_window_title: std::cell::Cell<Option<String>>, pending_window_title: std::cell::Cell<Option<String>>,
pub is_hovered: bool,
pub is_focused: bool,
} }
impl Default for WindowState { impl Default for WindowState {
@@ -17,7 +24,11 @@ impl Default for WindowState {
window: None, window: None,
size: Default::default(), size: Default::default(),
scale_factor: 1.0, scale_factor: 1.0,
scale_factor_override: None,
pending_window_title: std::cell::Cell::new(None), pending_window_title: std::cell::Cell::new(None),
clipboard: None,
is_hovered: true,
is_focused: true,
} }
} }
} }
@@ -28,6 +39,12 @@ impl WindowState {
window.set_title(&title); window.set_title(&title);
} }
let winit::dpi::PhysicalSize { width, height } = window.inner_size();
self.size = PhysicalSize::new(width, height);
self.scale_factor = window.scale_factor() as f32;
let raw_display_handle = window.display_handle().ok().map(|h| h.as_raw());
self.clipboard = Some(Clipboard::new(raw_display_handle));
self.window = Some(window); self.window = Some(window);
} }
@@ -40,7 +57,15 @@ impl WindowState {
} }
pub fn logical_size(&self) -> LogicalSize<u32> { pub fn logical_size(&self) -> LogicalSize<u32> {
self.size.to_logical(self.scale_factor) self.size.to_logical(self.scale_factor())
}
pub fn scale_factor(&self) -> f32 {
self.scale_factor_override.unwrap_or(self.scale_factor)
}
pub fn set_scale_factor(&mut self, scale_factor: f32) {
self.scale_factor = scale_factor;
} }
pub fn focus(&self) { pub fn focus(&self) {
@@ -48,4 +73,24 @@ impl WindowState {
window.focus_window(); window.focus_window();
} }
} }
pub fn set_clipboard_text(&mut self, text: String) {
if let Some(clipboard) = &mut self.clipboard {
clipboard.set_text(text);
}
}
pub fn get_clipboard_text(&mut self) -> Option<String> {
if let Some(clipboard) = &mut self.clipboard {
clipboard.get_text()
} else {
None
}
}
pub fn request_redraw(&self) {
if let Some(ref window) = self.window {
window.request_redraw();
}
}
} }