Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67cc995f78 | ||
|
|
534788f027 | ||
|
|
a57e0afda0 | ||
|
|
91ddf5696a | ||
|
|
08260cabd2 | ||
|
|
4316366f87 | ||
|
|
01697e32bd | ||
|
|
3e065a8838 | ||
|
|
1aa0aa128f | ||
|
|
098c967206 | ||
|
|
1bb0fdf056 | ||
|
|
9a341cfb39 | ||
|
|
5465544eb2 | ||
|
|
75c88af778 | ||
|
|
4db36c1382 | ||
|
|
9b925feb90 | ||
|
|
17bb3c6b39 | ||
|
|
ce62fe64e1 | ||
|
|
4b997447b5 |
No files matched your search
+8
-49
@@ -8,57 +8,16 @@
|
||||
|
||||
## Contributing code
|
||||
|
||||
- Get familiar with the code base before you start. I'll try to add more documentation providing a high-level overview of the architecture in the future. Until then, feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
|
||||
- If you intend to work on the API functions, also check out the [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) code base. A great place to ask questions about it is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
|
||||
- Get familiar with the code base before you start. Feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
|
||||
- Make sure the [API](https://github.com/meehl/rusty-path-of-building/blob/main/src/pob/api.rs) functions stay compatible with [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) (SG). A great place to ask questions about SG is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
|
||||
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
|
||||
|
||||
## macOS Development Setup
|
||||
## Code Ownership and AI-Assisted Contributions
|
||||
|
||||
### 1. Install Lua runtime dependencies
|
||||
Contributors are responsible for every line of code they submit, regardless of how it was written. Make sure to:
|
||||
|
||||
The application requires several Lua C libraries at runtime. Install them using LuaRocks with the LuaJIT backend:
|
||||
- **Understand your code** - You must be able to explain how your contribution works and why it is implemented the way it is.
|
||||
- **Review before submitting** - Carefully review all AI-generated code for correctness, security, maintainability, and consistency with the project's conventions.
|
||||
- **Maintain quality** - AI assistance is not an excuse for untested code, unnecessary complexity, duplicated logic, or careless implementations.
|
||||
|
||||
```bash
|
||||
brew install luajit luarocks
|
||||
|
||||
luarocks --lua-version 5.1 install luasocket
|
||||
luarocks --lua-version 5.1 install luautf8
|
||||
luarocks --lua-version 5.1 install lua-curl
|
||||
```
|
||||
|
||||
Build and install `lzip` from the bundled source (requires zlib, which is pre-installed on macOS):
|
||||
|
||||
```bash
|
||||
cd lua/libs/lzip && make LUA_IMPL=luajit install
|
||||
```
|
||||
|
||||
### 2. Configure LUA_CPATH
|
||||
|
||||
Add the following to your shell profile (`~/.zshrc` or `~/.bash_profile`) so the runtime can locate the installed libraries:
|
||||
|
||||
```bash
|
||||
eval $(luarocks --lua-version 5.1 path)
|
||||
```
|
||||
|
||||
Then reload your shell or run `source ~/.bash_profile`.
|
||||
|
||||
### 3. Startup
|
||||
|
||||
```bash
|
||||
cargo run <poe1|poe2>
|
||||
```
|
||||
|
||||
Path of Building files are automatically downloaded to the following directories on first startup:
|
||||
|
||||
- poe1: `~/Library/Application Support/RustyPathOfBuilding1`
|
||||
- poe2: `~/Library/Application Support/RustyPathOfBuilding2`
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
**Build fails with `library 'luajit-5.1' not found`**
|
||||
|
||||
This usually means the build cache points to an old LuaJIT version after a Homebrew upgrade. Run:
|
||||
|
||||
```bash
|
||||
cargo clean && cargo run <poe1|poe2>
|
||||
```
|
||||
If you cannot confidently explain and verify a piece of code, don't submit it.
|
||||
+41
-1
@@ -2,6 +2,41 @@
|
||||
|
||||
## [Unreleased] - ReleaseDate
|
||||
|
||||
## [0.3.5] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix a crash when filtering nodes in the Timeless Jewel Finder
|
||||
|
||||
## [0.3.4] - 2026-11-13
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix blurry text inside viewports with fractional scale factors
|
||||
- Fix crash on macOS
|
||||
|
||||
## [0.3.3] - 2026-10-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix error in built-in updater with new `bundled-lua-modules` feature
|
||||
|
||||
## [0.3.2] - 2026-10-22
|
||||
|
||||
### Changed
|
||||
|
||||
- Refactor surface format selection
|
||||
|
||||
### Fixed
|
||||
|
||||
- Render tab characters as 4 spaces to match SimpleGraphic (#53)
|
||||
|
||||
## [0.3.1] - 2026-10-21
|
||||
|
||||
### Fixed
|
||||
|
||||
- Strip `#@` script headers before loading Lua files to fix syntax error with recent LuaJIT versions
|
||||
|
||||
## [0.3.0] - 2026-10-21
|
||||
|
||||
### Added
|
||||
@@ -230,8 +265,13 @@
|
||||
- First release
|
||||
|
||||
<!-- next-url -->
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.0...HEAD
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.5...HEAD
|
||||
|
||||
[0.3.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.4...v0.3.5
|
||||
[0.3.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.3...v0.3.4
|
||||
[0.3.3]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.2...v0.3.3
|
||||
[0.3.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.1...v0.3.2
|
||||
[0.3.1]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.0...v0.3.1
|
||||
[0.3.0]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.18...v0.3.0
|
||||
[0.2.18]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.17...v0.2.18
|
||||
[0.2.17]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.16...v0.2.17
|
||||
|
||||
Generated
+1
-1
@@ -3502,7 +3502,7 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "rusty-path-of-building"
|
||||
version = "0.3.0"
|
||||
version = "0.3.5"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"anyhow",
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ authors = ["meehl"]
|
||||
description = "Cross-platform runtime for Path of Building"
|
||||
repository = "https://github.com/meehl/rusty-path-of-building"
|
||||
license = "MIT"
|
||||
version = "0.3.0"
|
||||
version = "0.3.5"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
+27
-10
@@ -4,7 +4,8 @@ use ahash::AHasher;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalQuad, LogicalRect, LogicalSize},
|
||||
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, ScaleFactor},
|
||||
fonts::{Layout, LayoutToLogical},
|
||||
math::Size,
|
||||
renderer::textures::TextureId,
|
||||
uv::{UvConstructors, UvQuad, UvRect},
|
||||
@@ -143,20 +144,36 @@ impl DrawCommandRecorder {
|
||||
});
|
||||
}
|
||||
|
||||
pub fn draw_glyph(
|
||||
/// Records a laid-out string whose top-left corner is at `layout_origin`.
|
||||
pub fn draw_glyphs(
|
||||
&mut self,
|
||||
rect: LogicalRect<f32>,
|
||||
layout: &Layout,
|
||||
layout_origin: LogicalPoint<f32>,
|
||||
is_absolute_position: bool,
|
||||
scale_factor: ScaleFactor<f32>,
|
||||
) {
|
||||
// resolve the layout origin to screen space
|
||||
let origin = if is_absolute_position {
|
||||
layout_origin
|
||||
} else {
|
||||
layout_origin + self.current_viewport.min.to_vector()
|
||||
};
|
||||
// align the layout origin with the physical pixel grid to reduce blurriness
|
||||
let origin = (origin * scale_factor).round() / scale_factor;
|
||||
|
||||
for glyph in &layout.glyphs {
|
||||
let rect = LayoutToLogical::new(origin.x, origin.y).transform_box(&glyph.rect);
|
||||
self.draw_glyph(rect, glyph.uv, glyph.color, glyph.layer_idx);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_glyph(
|
||||
&mut self,
|
||||
positions: LogicalRect<f32>,
|
||||
uv: UvRect,
|
||||
color: Srgba,
|
||||
layer_idx: u32,
|
||||
is_absolute_position: bool,
|
||||
) {
|
||||
let positions = if is_absolute_position {
|
||||
rect
|
||||
} else {
|
||||
rect.translate(self.current_viewport.min.to_vector())
|
||||
};
|
||||
|
||||
// cull if outside of viewport
|
||||
if !positions.intersects(&self.current_viewport) {
|
||||
return;
|
||||
|
||||
+48
-13
@@ -91,16 +91,40 @@ impl GraphicsContext {
|
||||
|
||||
let surface_caps = surface.get_capabilities(&adapter);
|
||||
|
||||
// NOTE: PoB incorrectly performs mixing and blending in sRGB space.
|
||||
// To get a similar visual outcome, we need to do the same.
|
||||
// Select a non-sRGB format so that no automatic linear -> sRGB conversion
|
||||
// is performed.
|
||||
let surface_format = surface_caps
|
||||
.formats
|
||||
log::debug!(
|
||||
"surface format capabilities: {:#?}",
|
||||
surface_caps.format_capabilities
|
||||
);
|
||||
|
||||
// NOTE: PoB blends in non-linear space, so we want a plain UNORM format with
|
||||
// no automatic linear -> non-linear conversion to get the same visual result.
|
||||
const PREFERRED: [wgpu::TextureFormat; 2] = [
|
||||
wgpu::TextureFormat::Bgra8Unorm,
|
||||
wgpu::TextureFormat::Rgba8Unorm,
|
||||
];
|
||||
|
||||
let surface_format = PREFERRED
|
||||
.iter()
|
||||
.find(|f| !f.is_srgb() && f.required_features().is_empty())
|
||||
.copied()
|
||||
.unwrap_or(surface_caps.formats[0]);
|
||||
.find(|f| surface_caps.formats.contains(f))
|
||||
.unwrap_or_else(|| {
|
||||
// fallback: any non-sRGB format that isn't floating point
|
||||
surface_caps
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|f| {
|
||||
!f.is_srgb()
|
||||
&& !matches!(
|
||||
f,
|
||||
wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
|
||||
)
|
||||
&& f.required_features().is_empty()
|
||||
})
|
||||
.unwrap_or(surface_caps.formats[0])
|
||||
});
|
||||
|
||||
log::debug!("selected format: {:?}", surface_format);
|
||||
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
@@ -111,7 +135,7 @@ impl GraphicsContext {
|
||||
alpha_mode: surface_caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
color_space: wgpu::SurfaceColorSpace::Auto,
|
||||
color_space: wgpu::SurfaceColorSpace::Srgb,
|
||||
};
|
||||
|
||||
let (blit_texture, blit_texture_view) =
|
||||
@@ -150,7 +174,16 @@ impl GraphicsContext {
|
||||
pub fn render(&mut self, render_job: Option<RenderJob>) -> anyhow::Result<()> {
|
||||
profiling::scope!("render");
|
||||
|
||||
// apply textures delta
|
||||
if let Some(render_job) = &render_job {
|
||||
self.renderer
|
||||
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
|
||||
}
|
||||
|
||||
if !self.is_surface_configured {
|
||||
if let Some(render_job) = &render_job {
|
||||
self.renderer.free_textures(&render_job.textures_delta);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -161,10 +194,16 @@ impl GraphicsContext {
|
||||
| wgpu::CurrentSurfaceTexture::Occluded
|
||||
| wgpu::CurrentSurfaceTexture::Validation => {
|
||||
// Skip frame
|
||||
if let Some(render_job) = &render_job {
|
||||
self.renderer.free_textures(&render_job.textures_delta);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
if let Some(render_job) = &render_job {
|
||||
self.renderer.free_textures(&render_job.textures_delta);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -184,10 +223,6 @@ impl GraphicsContext {
|
||||
if let Some(render_job) = render_job {
|
||||
let screen_size = PhysicalSize::new(self.config.width, self.config.height);
|
||||
|
||||
// upload new textures
|
||||
self.renderer
|
||||
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
|
||||
|
||||
// upload vertex, index, and uniform buffers
|
||||
self.renderer.update_buffers(
|
||||
&self.device,
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@ use crate::{
|
||||
pob::subscript::{NativeMultiValue, SubscriptEvent, SubscriptManager},
|
||||
renderer::textures::TextureManager,
|
||||
stage::{StageEvent, StageFrameOutput, StageTransition},
|
||||
util::{append_lua_package_dir, change_working_directory},
|
||||
util::{append_lua_package_dir, change_working_directory, load_lua_file},
|
||||
window::WindowState,
|
||||
};
|
||||
use std::{
|
||||
@@ -133,7 +133,7 @@ impl PathOfBuilding {
|
||||
/// Loads and runs `Launch.lua`, then calls PoB's `OnInit` handler.
|
||||
fn launch(lua: &Lua, script_dir: &Path) -> LuaResult<()> {
|
||||
change_working_directory(script_dir)?;
|
||||
lua.load(script_dir.join("Launch.lua")).exec()?;
|
||||
load_lua_file(lua, &script_dir.join("Launch.lua"))?.exec()?;
|
||||
{
|
||||
profiling::scope!("OnInit");
|
||||
api::on_init(lua)?;
|
||||
|
||||
+12
-8
@@ -1,4 +1,7 @@
|
||||
use crate::{pob::Context, util::change_working_directory};
|
||||
use crate::{
|
||||
pob::Context,
|
||||
util::{change_working_directory, load_lua_file},
|
||||
};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::env;
|
||||
|
||||
@@ -23,7 +26,7 @@ pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<Mul
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(script_dir.as_path())?;
|
||||
let result = l.load(module_path).call::<MultiValue>(args);
|
||||
let result = load_lua_file(l, &module_path).and_then(|chunk| chunk.call::<MultiValue>(args));
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
@@ -40,12 +43,13 @@ pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> Lua
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(script_dir.as_path())?;
|
||||
let result = match l.load(module_path).call::<MultiValue>(args) {
|
||||
// on success, callers expect a Nil followed by return values
|
||||
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => err.to_string().into_lua_multi(l),
|
||||
};
|
||||
let result =
|
||||
match load_lua_file(l, &module_path).and_then(|chunk| chunk.call::<MultiValue>(args)) {
|
||||
// on success, callers expect a Nil followed by return values
|
||||
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => err.to_string().into_lua_multi(l),
|
||||
};
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
+46
-46
@@ -41,24 +41,24 @@ pub unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_
|
||||
match nargs {
|
||||
// escape_code
|
||||
1 => {
|
||||
let esc_str = str_from_stack!(state, -nargs);
|
||||
let esc_str = str_from_stack!(state, 1);
|
||||
let color = Srgba::from_escape_code(esc_str);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
// rgb
|
||||
3 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let r = f32_from_stack!(state, 1);
|
||||
let g = f32_from_stack!(state, 2);
|
||||
let b = f32_from_stack!(state, 3);
|
||||
let color = Srgba::new_f32(r, g, b, 1.0);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
// rgba
|
||||
4 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let a = f32_from_stack!(state, -nargs + 3);
|
||||
let r = f32_from_stack!(state, 1);
|
||||
let g = f32_from_stack!(state, 2);
|
||||
let b = f32_from_stack!(state, 3);
|
||||
let a = f32_from_stack!(state, 4);
|
||||
let color = Srgba::new_f32(r, g, b, a);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
@@ -91,10 +91,10 @@ pub unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_in
|
||||
match nargs {
|
||||
0 => ctx.set_recorder_viewport_to_window_size(),
|
||||
4 => {
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let w = f32_from_stack!(state, -nargs + 2);
|
||||
let h = f32_from_stack!(state, -nargs + 3);
|
||||
let x = f32_from_stack!(state, 1);
|
||||
let y = f32_from_stack!(state, 2);
|
||||
let w = f32_from_stack!(state, 3);
|
||||
let h = f32_from_stack!(state, 4);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
ctx.recorder.set_viewport(rect);
|
||||
}
|
||||
@@ -113,19 +113,19 @@ pub unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_
|
||||
|
||||
match nargs {
|
||||
1 => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
let layer = i32_from_stack!(state, 1);
|
||||
ctx.recorder.set_draw_layer(layer, 0);
|
||||
}
|
||||
2 => {
|
||||
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
|
||||
let layer = match unsafe { ffi::lua_type(state, 1) } {
|
||||
ffi::LUA_TNIL => None,
|
||||
ffi::LUA_TNUMBER => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
let layer = i32_from_stack!(state, 1);
|
||||
Some(layer)
|
||||
}
|
||||
t => panic!("Expected Nil or Number, got {t:?}"),
|
||||
};
|
||||
let sublayer = i32_from_stack!(state, -nargs + 1);
|
||||
let sublayer = i32_from_stack!(state, 2);
|
||||
if let Some(layer) = layer {
|
||||
ctx.recorder.set_draw_layer(layer, sublayer);
|
||||
} else {
|
||||
@@ -153,22 +153,22 @@ pub unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int
|
||||
let parse_uv = matches!(nargs, 9 | 10);
|
||||
let parse_layer_idx = matches!(nargs, 6 | 10);
|
||||
|
||||
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
|
||||
let texture_id = unsafe { image_handle_texture_id(state, 1) };
|
||||
|
||||
// left, top, width, height
|
||||
let x = f32_from_stack!(state, -nargs + 1);
|
||||
let y = f32_from_stack!(state, -nargs + 2);
|
||||
let w = f32_from_stack!(state, -nargs + 3);
|
||||
let h = f32_from_stack!(state, -nargs + 4);
|
||||
let x = f32_from_stack!(state, 2);
|
||||
let y = f32_from_stack!(state, 3);
|
||||
let w = f32_from_stack!(state, 4);
|
||||
let h = f32_from_stack!(state, 5);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
|
||||
// u1, v1, u2, v2
|
||||
let mut i = 5;
|
||||
let mut i = 6;
|
||||
let uv = if parse_uv {
|
||||
let u1 = f32_from_stack!(state, -nargs + i);
|
||||
let v1 = f32_from_stack!(state, -nargs + i + 1);
|
||||
let u2 = f32_from_stack!(state, -nargs + i + 2);
|
||||
let v2 = f32_from_stack!(state, -nargs + i + 3);
|
||||
let u1 = f32_from_stack!(state, i);
|
||||
let v1 = f32_from_stack!(state, i + 1);
|
||||
let u2 = f32_from_stack!(state, i + 2);
|
||||
let v2 = f32_from_stack!(state, i + 3);
|
||||
i += 4;
|
||||
Some(Rect::new(Point::new(u1, v1), Point::new(u2, v2)))
|
||||
} else {
|
||||
@@ -176,7 +176,7 @@ pub unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
let layer_idx = i32_from_stack!(state, i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
@@ -202,17 +202,17 @@ pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c
|
||||
let parse_uv = matches!(nargs, 17 | 18);
|
||||
let parse_layer_idx = matches!(nargs, 10 | 18);
|
||||
|
||||
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
|
||||
let texture_id = unsafe { image_handle_texture_id(state, 1) };
|
||||
|
||||
// x1, y1, x2, y2, ...
|
||||
let x1 = f32_from_stack!(state, -nargs + 1);
|
||||
let y1 = f32_from_stack!(state, -nargs + 2);
|
||||
let x2 = f32_from_stack!(state, -nargs + 3);
|
||||
let y2 = f32_from_stack!(state, -nargs + 4);
|
||||
let x3 = f32_from_stack!(state, -nargs + 5);
|
||||
let y3 = f32_from_stack!(state, -nargs + 6);
|
||||
let x4 = f32_from_stack!(state, -nargs + 7);
|
||||
let y4 = f32_from_stack!(state, -nargs + 8);
|
||||
let x1 = f32_from_stack!(state, 2);
|
||||
let y1 = f32_from_stack!(state, 3);
|
||||
let x2 = f32_from_stack!(state, 4);
|
||||
let y2 = f32_from_stack!(state, 5);
|
||||
let x3 = f32_from_stack!(state, 6);
|
||||
let y3 = f32_from_stack!(state, 7);
|
||||
let x4 = f32_from_stack!(state, 8);
|
||||
let y4 = f32_from_stack!(state, 9);
|
||||
let quad = Quad::new(
|
||||
Point::new(x1, y1),
|
||||
Point::new(x2, y2),
|
||||
@@ -221,16 +221,16 @@ pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c
|
||||
);
|
||||
|
||||
// u1, v1, u2, v2, ...
|
||||
let mut i = 9;
|
||||
let mut i = 10;
|
||||
let uv = if parse_uv {
|
||||
let u1 = f32_from_stack!(state, -nargs + i);
|
||||
let v1 = f32_from_stack!(state, -nargs + i + 1);
|
||||
let u2 = f32_from_stack!(state, -nargs + i + 2);
|
||||
let v2 = f32_from_stack!(state, -nargs + i + 3);
|
||||
let u3 = f32_from_stack!(state, -nargs + i + 4);
|
||||
let v3 = f32_from_stack!(state, -nargs + i + 5);
|
||||
let u4 = f32_from_stack!(state, -nargs + i + 6);
|
||||
let v4 = f32_from_stack!(state, -nargs + i + 7);
|
||||
let u1 = f32_from_stack!(state, i);
|
||||
let v1 = f32_from_stack!(state, i + 1);
|
||||
let u2 = f32_from_stack!(state, i + 2);
|
||||
let v2 = f32_from_stack!(state, i + 3);
|
||||
let u3 = f32_from_stack!(state, i + 4);
|
||||
let v3 = f32_from_stack!(state, i + 5);
|
||||
let u4 = f32_from_stack!(state, i + 6);
|
||||
let v4 = f32_from_stack!(state, i + 7);
|
||||
i += 8;
|
||||
Some(Quad::new(
|
||||
Point::new(u1, v1),
|
||||
@@ -243,7 +243,7 @@ pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
let layer_idx = i32_from_stack!(state, i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
|
||||
+207
-60
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::LogicalPoint,
|
||||
fonts::{Alignment, FontStyle, LayoutJob, LayoutToLogical},
|
||||
fonts::{Alignment, FontStyle, LayoutJob},
|
||||
math::Point,
|
||||
pob::Context,
|
||||
};
|
||||
@@ -46,14 +46,16 @@ pub unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let alignment = str_from_stack!(state, -nargs + 2);
|
||||
let line_height = i32_from_stack!(state, -nargs + 3);
|
||||
let font_type = str_from_stack!(state, -nargs + 4);
|
||||
let text = str_from_stack!(state, -nargs + 5);
|
||||
let x = f32_from_stack!(state, 1);
|
||||
let y = f32_from_stack!(state, 2);
|
||||
let alignment = if unsafe { ffi::lua_isnil(state, 3) } != 0 {
|
||||
"LEFT"
|
||||
} else {
|
||||
str_from_stack!(state, 3)
|
||||
};
|
||||
let line_height = i32_from_stack!(state, 4);
|
||||
let font_type = str_from_stack!(state, 5);
|
||||
let text = str_from_stack!(state, 6);
|
||||
|
||||
let Ok(alignment) = alignment.parse::<PoBTextAlignment>() else {
|
||||
panic!("Invalid alignment");
|
||||
@@ -101,19 +103,10 @@ pub unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int
|
||||
let layout = ctx.fonts.borrow_mut().layout(job, scale_factor);
|
||||
|
||||
// apply offset to account for anchor position
|
||||
let position = position + layout.anchor_offset(halign);
|
||||
// align layout anchor with the physical pixel grid to reduce blurriness
|
||||
let position = (position * scale_factor).round() / scale_factor;
|
||||
let layout_origin = position + layout.anchor_offset(halign);
|
||||
|
||||
for glyph in &layout.glyphs {
|
||||
ctx.recorder.draw_glyph(
|
||||
LayoutToLogical::new(position.x, position.y).transform_box(&glyph.rect),
|
||||
glyph.uv,
|
||||
glyph.color,
|
||||
glyph.layer_idx,
|
||||
is_absolute_position,
|
||||
);
|
||||
}
|
||||
ctx.recorder
|
||||
.draw_glyphs(&layout, layout_origin, is_absolute_position, scale_factor);
|
||||
|
||||
0
|
||||
}
|
||||
@@ -123,11 +116,9 @@ pub unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) ->
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let line_height = i32_from_stack!(state, -nargs);
|
||||
let font_type = str_from_stack!(state, -nargs + 1);
|
||||
let text = str_from_stack!(state, -nargs + 2);
|
||||
let line_height = i32_from_stack!(state, 1);
|
||||
let font_type = str_from_stack!(state, 2);
|
||||
let text = str_from_stack!(state, 3);
|
||||
|
||||
let Ok(font_type) = font_type.parse::<PoBFontType>() else {
|
||||
panic!("Invalid font type");
|
||||
@@ -160,11 +151,10 @@ pub fn get_index_at_cur(
|
||||
.borrow_mut()
|
||||
.layout(job, ctx.window_state.scale_factor());
|
||||
|
||||
// `cursor_index_at` returns an offset into the **stripped** text, but PoB expects on offset
|
||||
// into the original, **unstripped** text. A `StrippedToOriginalOffsetMap` is used to do the
|
||||
// conversion.
|
||||
let stripped_index = layout.cursor_index_at(Point::new(cur_x, cur_y));
|
||||
let original_index = offset_map.to_original(stripped_index);
|
||||
// `cursor_index_at` returns an offset into the layout text, but PoB expects an offset into
|
||||
// the original text. A `LayoutTextToOriginalOffsetMap` handles the conversion.
|
||||
let layout_text_index = layout.cursor_index_at(Point::new(cur_x, cur_y));
|
||||
let original_index = offset_map.to_original(layout_text_index);
|
||||
|
||||
// convert to lua's 1-based indexing
|
||||
Ok(original_index + 1)
|
||||
@@ -240,44 +230,106 @@ fn build_layout_job<'a>(
|
||||
original_start: _,
|
||||
} in PoBString(text)
|
||||
{
|
||||
job.append(text, color.unwrap_or(current_color));
|
||||
let color = color.unwrap_or(current_color);
|
||||
for (_, piece) in split_tabs(text) {
|
||||
job.append(piece.layout_text(), color);
|
||||
}
|
||||
}
|
||||
|
||||
job
|
||||
}
|
||||
|
||||
/// Maps byte offset in stripped text back to offset in original text.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct StrippedToOriginalOffsetMap {
|
||||
segments: Vec<(usize, usize)>,
|
||||
/// Tabs are replaced with four spaces to match SimpleGraphic's behavior.
|
||||
const TAB_REPLACEMENT: &str = " ";
|
||||
|
||||
/// A piece of text with tabs split out.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
enum TextPiece<'a> {
|
||||
Text(&'a str),
|
||||
Tab,
|
||||
}
|
||||
|
||||
impl StrippedToOriginalOffsetMap {
|
||||
fn push_segment(&mut self, stripped_start: usize, original_start: usize) {
|
||||
self.segments.push((stripped_start, original_start));
|
||||
impl<'a> TextPiece<'a> {
|
||||
/// Returns the text that is passed to the layout
|
||||
fn layout_text(self) -> &'a str {
|
||||
match self {
|
||||
Self::Text(text) => text,
|
||||
Self::Tab => TAB_REPLACEMENT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits `text` at tab characters. Yields each piece alongside its byte offset into `text`.
|
||||
fn split_tabs(text: &str) -> impl Iterator<Item = (usize, TextPiece<'_>)> {
|
||||
let mut offset = 0;
|
||||
text.split('\t').enumerate().flat_map(move |(i, piece)| {
|
||||
// every piece after the first one is preceded by a tab
|
||||
let tab = (i > 0).then(|| (offset - 1, TextPiece::Tab));
|
||||
let text_piece = (offset, TextPiece::Text(piece));
|
||||
offset += piece.len() + 1;
|
||||
tab.into_iter().chain(std::iter::once(text_piece))
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct OffsetSegment {
|
||||
layout_text_start: usize,
|
||||
original_start: usize,
|
||||
is_tab: bool,
|
||||
}
|
||||
|
||||
/// Maps a byte offset in the layout text back to an offset in the original text.
|
||||
///
|
||||
/// The layout text is the text passed to `parley`, i.e. without color escapes and with tabs
|
||||
/// replaced by spaces.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct LayoutTextToOriginalOffsetMap {
|
||||
segments: Vec<OffsetSegment>,
|
||||
}
|
||||
|
||||
impl LayoutTextToOriginalOffsetMap {
|
||||
fn push_segment(&mut self, layout_text_start: usize, original_start: usize) {
|
||||
self.segments.push(OffsetSegment {
|
||||
layout_text_start,
|
||||
original_start,
|
||||
is_tab: false,
|
||||
});
|
||||
}
|
||||
|
||||
fn to_original(&self, stripped_index: usize) -> usize {
|
||||
fn push_tab(&mut self, layout_text_start: usize, original_start: usize) {
|
||||
self.segments.push(OffsetSegment {
|
||||
layout_text_start,
|
||||
original_start,
|
||||
is_tab: true,
|
||||
});
|
||||
}
|
||||
|
||||
fn to_original(&self, layout_text_index: usize) -> usize {
|
||||
assert!(!self.segments.is_empty());
|
||||
let i = self
|
||||
.segments
|
||||
.partition_point(|&(stripped_start, _)| stripped_start <= stripped_index);
|
||||
let (stripped_start, original_start) = self.segments[i - 1];
|
||||
original_start + (stripped_index - stripped_start)
|
||||
.partition_point(|seg| seg.layout_text_start <= layout_text_index);
|
||||
let seg = self.segments[i - 1];
|
||||
if seg.is_tab {
|
||||
// map any cursor position within a tab to the start of it like SG
|
||||
seg.original_start
|
||||
} else {
|
||||
seg.original_start + (layout_text_index - seg.layout_text_start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `StrippedToOriginalOffsetMap` alongside the `LayoutJob`.
|
||||
/// Returns a `LayoutTextToOriginalOffsetMap` alongside the `LayoutJob`.
|
||||
fn build_layout_job_with_offsets<'a>(
|
||||
text: &'a str,
|
||||
current_color: Srgba,
|
||||
font_type: PoBFontType,
|
||||
line_height: i32,
|
||||
alignment: Option<Alignment>,
|
||||
) -> (LayoutJob<'a>, StrippedToOriginalOffsetMap) {
|
||||
) -> (LayoutJob<'a>, LayoutTextToOriginalOffsetMap) {
|
||||
let mut job = new_layout_job(font_type, line_height, alignment);
|
||||
let mut offset_map = StrippedToOriginalOffsetMap::default();
|
||||
let mut stripped_offset = 0;
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
let mut layout_text_offset = 0;
|
||||
|
||||
for ColoredSegment {
|
||||
color,
|
||||
@@ -285,9 +337,18 @@ fn build_layout_job_with_offsets<'a>(
|
||||
original_start,
|
||||
} in PoBString(text)
|
||||
{
|
||||
offset_map.push_segment(stripped_offset, original_start);
|
||||
job.append(text, color.unwrap_or(current_color));
|
||||
stripped_offset += text.len();
|
||||
let color = color.unwrap_or(current_color);
|
||||
for (offset, piece) in split_tabs(text) {
|
||||
match piece {
|
||||
TextPiece::Text(_) => {
|
||||
offset_map.push_segment(layout_text_offset, original_start + offset);
|
||||
}
|
||||
TextPiece::Tab => offset_map.push_tab(layout_text_offset, original_start + offset),
|
||||
}
|
||||
let layout_text = piece.layout_text();
|
||||
job.append(layout_text, color);
|
||||
layout_text_offset += layout_text.len();
|
||||
}
|
||||
}
|
||||
|
||||
(job, offset_map)
|
||||
@@ -317,7 +378,7 @@ impl<'a> IntoIterator for PoBString<'a> {
|
||||
pub struct ColoredSegment<'a> {
|
||||
pub color: Option<Srgba>,
|
||||
pub text: &'a str,
|
||||
/// The byte offset of `text` within the **original**, unstripped string.
|
||||
/// The byte offset of `text` within the **original** string.
|
||||
pub original_start: usize,
|
||||
}
|
||||
|
||||
@@ -525,7 +586,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_empty() {
|
||||
let mut offset_map = StrippedToOriginalOffsetMap::default();
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
for seg in PoBString("") {
|
||||
offset_map.push_segment(0, seg.original_start);
|
||||
}
|
||||
@@ -534,11 +595,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_no_escape() {
|
||||
let mut offset_map = StrippedToOriginalOffsetMap::default();
|
||||
let mut stripped_offset = 0;
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
let mut layout_text_offset = 0;
|
||||
for seg in PoBString("Hello, World!") {
|
||||
offset_map.push_segment(stripped_offset, seg.original_start);
|
||||
stripped_offset += seg.text.len();
|
||||
offset_map.push_segment(layout_text_offset, seg.original_start);
|
||||
layout_text_offset += seg.text.len();
|
||||
}
|
||||
assert_eq!(offset_map.to_original(0), 0);
|
||||
assert_eq!(offset_map.to_original(3), 3);
|
||||
@@ -547,15 +608,101 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn cursor_offset() {
|
||||
let mut offset_map = StrippedToOriginalOffsetMap::default();
|
||||
let mut stripped_offset = 0;
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
let mut layout_text_offset = 0;
|
||||
for seg in PoBString("^1Hello^xFF0000World^3!") {
|
||||
offset_map.push_segment(stripped_offset, seg.original_start);
|
||||
stripped_offset += seg.text.len();
|
||||
offset_map.push_segment(layout_text_offset, seg.original_start);
|
||||
layout_text_offset += seg.text.len();
|
||||
}
|
||||
assert_eq!(offset_map.to_original(0), 2);
|
||||
assert_eq!(offset_map.to_original(3), 5);
|
||||
assert_eq!(offset_map.to_original(6), 16);
|
||||
assert_eq!(offset_map.to_original(11), 23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_tabs_no_tabs() {
|
||||
assert_eq!(
|
||||
split_tabs("Hello").collect::<Vec<_>>(),
|
||||
vec![(0, TextPiece::Text("Hello"))]
|
||||
);
|
||||
assert_eq!(
|
||||
split_tabs("").collect::<Vec<_>>(),
|
||||
vec![(0, TextPiece::Text(""))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_tabs_with_tabs() {
|
||||
assert_eq!(
|
||||
split_tabs("a\tbc\t\td\t").collect::<Vec<_>>(),
|
||||
vec![
|
||||
(0, TextPiece::Text("a")),
|
||||
(1, TextPiece::Tab),
|
||||
(2, TextPiece::Text("bc")),
|
||||
(4, TextPiece::Tab),
|
||||
(5, TextPiece::Text("")),
|
||||
(5, TextPiece::Tab),
|
||||
(6, TextPiece::Text("d")),
|
||||
(7, TextPiece::Tab),
|
||||
(8, TextPiece::Text("")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn layout_text(job: &LayoutJob) -> String {
|
||||
job.segments.iter().map(|s| s.text).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_replaced_with_spaces() {
|
||||
let job = build_layout_job("^1a\tb^2\tc", Srgba::WHITE, PoBFontType::Var, 16, None);
|
||||
assert_eq!(layout_text(&job), "a b c");
|
||||
|
||||
// tabs keep the color of the segment they're in
|
||||
let red = Srgba::from_rgb(255, 0, 0);
|
||||
let green = Srgba::from_rgb(0, 255, 0);
|
||||
let colors: Vec<_> = job.segments.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, vec![red, red, red, green, green, green]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_with_tabs() {
|
||||
let (job, offset_map) =
|
||||
build_layout_job_with_offsets("^1a\tb\t", Srgba::WHITE, PoBFontType::Var, 16, None);
|
||||
assert_eq!(layout_text(&job), "a b ");
|
||||
|
||||
// 'a'
|
||||
assert_eq!(offset_map.to_original(0), 2);
|
||||
// first tab: any position within the tab maps to the tab start
|
||||
assert_eq!(offset_map.to_original(1), 3);
|
||||
assert_eq!(offset_map.to_original(2), 3);
|
||||
assert_eq!(offset_map.to_original(4), 3);
|
||||
// 'b'
|
||||
assert_eq!(offset_map.to_original(5), 4);
|
||||
// trailing tab: any position within the tab maps to the tab start
|
||||
assert_eq!(offset_map.to_original(6), 5);
|
||||
assert_eq!(offset_map.to_original(9), 5);
|
||||
// end of text is after the trailing tab
|
||||
assert_eq!(offset_map.to_original(10), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_with_consecutive_tabs() {
|
||||
let (job, offset_map) =
|
||||
build_layout_job_with_offsets("a\t\tb", Srgba::WHITE, PoBFontType::Var, 16, None);
|
||||
assert_eq!(layout_text(&job), "a b");
|
||||
assert_eq!(offset_map.to_original(0), 0);
|
||||
|
||||
// first tab
|
||||
for layout_text_index in 1..=4 {
|
||||
assert_eq!(offset_map.to_original(layout_text_index), 1);
|
||||
}
|
||||
|
||||
// second tab, which starts immediately after the first one
|
||||
for layout_text_index in 5..=8 {
|
||||
assert_eq!(offset_map.to_original(layout_text_index), 2);
|
||||
}
|
||||
assert_eq!(offset_map.to_original(9), 3);
|
||||
}
|
||||
}
|
||||
+100
-21
@@ -17,11 +17,59 @@ fn bad_argument(to: impl Into<String>, pos: usize, cause: &'static str) -> LuaEr
|
||||
}
|
||||
}
|
||||
|
||||
/// A Lua callback set via `setopt_*function`.
|
||||
///
|
||||
/// `context` is set when an object is passed to the callback setter. In that case `function` is
|
||||
/// the object's method and is invoked as `function(context, data)`.
|
||||
struct Callback {
|
||||
function: RegistryKey,
|
||||
context: Option<RegistryKey>,
|
||||
}
|
||||
|
||||
impl Callback {
|
||||
fn resolve(&self, lua: &Lua) -> LuaResult<(mlua::Function, Option<mlua::Value>)> {
|
||||
let function = lua.registry_value(&self.function)?;
|
||||
let context = self
|
||||
.context
|
||||
.as_ref()
|
||||
.map(|key| lua.registry_value::<mlua::Value>(key))
|
||||
.transpose()?;
|
||||
|
||||
Ok((function, context))
|
||||
}
|
||||
|
||||
fn remove(self, lua: &Lua) -> LuaResult<()> {
|
||||
lua.remove_registry_value(self.function)?;
|
||||
|
||||
if let Some(key) = self.context {
|
||||
lua.remove_registry_value(key)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Interprets write/header callback return values like Lua-cURL does.
|
||||
fn callback_size(data_len: usize, results: &mlua::MultiValue) -> usize {
|
||||
let Some(value) = results.front() else {
|
||||
return data_len;
|
||||
};
|
||||
|
||||
match value {
|
||||
mlua::Value::Nil => 0,
|
||||
mlua::Value::Integer(n) => (*n).max(0) as usize,
|
||||
mlua::Value::Number(n) if *n >= 0.0 => *n as usize,
|
||||
mlua::Value::Number(_) => 0,
|
||||
mlua::Value::Boolean(false) => 0,
|
||||
_ => data_len,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct EasyHandle {
|
||||
easy: Option<Easy>,
|
||||
write_callback: Option<RegistryKey>,
|
||||
header_callback: Option<RegistryKey>,
|
||||
write_callback: Option<Callback>,
|
||||
header_callback: Option<Callback>,
|
||||
}
|
||||
|
||||
impl EasyHandle {
|
||||
@@ -40,12 +88,12 @@ impl EasyHandle {
|
||||
}
|
||||
|
||||
pub fn close(&mut self, lua: &Lua) -> LuaResult<()> {
|
||||
if let Some(key) = self.write_callback.take() {
|
||||
lua.remove_registry_value(key)?;
|
||||
if let Some(callback) = self.write_callback.take() {
|
||||
callback.remove(lua)?;
|
||||
}
|
||||
|
||||
if let Some(key) = self.header_callback.take() {
|
||||
lua.remove_registry_value(key)?;
|
||||
if let Some(callback) = self.header_callback.take() {
|
||||
callback.remove(lua)?;
|
||||
}
|
||||
|
||||
self.easy = None;
|
||||
@@ -160,20 +208,37 @@ impl EasyHandle {
|
||||
|
||||
fn set_callback(
|
||||
lua: &Lua,
|
||||
slot: &mut Option<RegistryKey>,
|
||||
slot: &mut Option<Callback>,
|
||||
value: mlua::Value,
|
||||
method: &str,
|
||||
) -> LuaResult<()> {
|
||||
let new_key = match value {
|
||||
let new_callback = match value {
|
||||
mlua::Value::Nil => None,
|
||||
mlua::Value::Function(f) => Some(lua.create_registry_value(f)?),
|
||||
mlua::Value::Function(function) => Some(Callback {
|
||||
function: lua.create_registry_value(function)?,
|
||||
context: None,
|
||||
}),
|
||||
// Lua-cURL can also accept objects with a method of the given name,
|
||||
// e.g. a file handle returned by `io.open` with a `write` method.
|
||||
// looks a bit awkwards but it works...
|
||||
value @ (mlua::Value::Table(_) | mlua::Value::UserData(_)) => {
|
||||
let function: mlua::Function = lua
|
||||
.load("local object, key = ...; return object[key]")
|
||||
.call((value.clone(), method))?;
|
||||
|
||||
Some(Callback {
|
||||
function: lua.create_registry_value(function)?,
|
||||
context: Some(lua.create_registry_value(value)?),
|
||||
})
|
||||
}
|
||||
_ => return Err(LuaError::runtime("invalid object type")),
|
||||
};
|
||||
|
||||
if let Some(old_key) = slot.take() {
|
||||
lua.remove_registry_value(old_key)?;
|
||||
if let Some(old_callback) = slot.take() {
|
||||
old_callback.remove(lua)?;
|
||||
}
|
||||
|
||||
*slot = new_key;
|
||||
*slot = new_callback;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -182,41 +247,55 @@ impl EasyHandle {
|
||||
let write_fn = self
|
||||
.write_callback
|
||||
.as_ref()
|
||||
.map(|key| lua.registry_value::<mlua::Function>(key))
|
||||
.map(|callback| callback.resolve(lua))
|
||||
.transpose()?;
|
||||
|
||||
let header_fn = self
|
||||
.header_callback
|
||||
.as_ref()
|
||||
.map(|key| lua.registry_value::<mlua::Function>(key))
|
||||
.map(|callback| callback.resolve(lua))
|
||||
.transpose()?;
|
||||
|
||||
let transfer_result = {
|
||||
let mut transfer = self.curl()?.transfer();
|
||||
|
||||
if let Some(function) = write_fn {
|
||||
if let Some((function, context)) = write_fn {
|
||||
transfer
|
||||
.write_function(move |data| {
|
||||
let Ok(argument) = lua.create_string(data) else {
|
||||
return Ok(0);
|
||||
};
|
||||
|
||||
match function.call::<()>(argument) {
|
||||
Ok(()) => Ok(data.len()),
|
||||
let result = match &context {
|
||||
Some(context) => {
|
||||
function.call::<mlua::MultiValue>((context.clone(), argument))
|
||||
}
|
||||
None => function.call::<mlua::MultiValue>(argument),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(results) => Ok(callback_size(data.len(), &results)),
|
||||
Err(_) => Ok(0),
|
||||
}
|
||||
})
|
||||
.map_err(LuaError::external)?;
|
||||
}
|
||||
|
||||
if let Some(function) = header_fn {
|
||||
if let Some((function, context)) = header_fn {
|
||||
transfer
|
||||
.header_function(move |data| {
|
||||
let Ok(argument) = lua.create_string(data) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
function.call::<bool>(argument).unwrap_or(false)
|
||||
match &context {
|
||||
Some(context) => {
|
||||
function.call::<mlua::MultiValue>((context.clone(), argument))
|
||||
}
|
||||
None => function.call::<mlua::MultiValue>(argument),
|
||||
}
|
||||
.map(|results| callback_size(data.len(), &results) == data.len())
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map_err(LuaError::external)?;
|
||||
}
|
||||
@@ -272,11 +351,11 @@ impl UserData for EasyHandle {
|
||||
});
|
||||
|
||||
methods.add_method_mut("setopt_writefunction", |lua, this, value: mlua::Value| {
|
||||
Self::set_callback(lua, &mut this.write_callback, value)
|
||||
Self::set_callback(lua, &mut this.write_callback, value, "write")
|
||||
});
|
||||
|
||||
methods.add_method_mut("setopt_headerfunction", |lua, this, value: mlua::Value| {
|
||||
Self::set_callback(lua, &mut this.header_callback, value)
|
||||
Self::set_callback(lua, &mut this.header_callback, value, "header")
|
||||
});
|
||||
|
||||
methods.add_method_mut("perform", |lua, this, ()| this.perform(lua));
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::{pob::modules, util::append_lua_package_dir};
|
||||
use crate::{
|
||||
pob::modules,
|
||||
util::{append_lua_package_dir, fix_script_header},
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{Integer, IntoLuaMulti, Lua, MultiValue, Number, Value};
|
||||
use std::{
|
||||
@@ -184,6 +187,8 @@ impl Subscript {
|
||||
)?;
|
||||
}
|
||||
|
||||
let mut script_text = script_text.into_bytes();
|
||||
fix_script_header(&mut script_text);
|
||||
let result = lua.load(script_text).call::<MultiValue>(arguments)?;
|
||||
result.try_into()
|
||||
});
|
||||
|
||||
+32
-2
@@ -1,7 +1,7 @@
|
||||
use ahash::AHasher;
|
||||
use mlua::{Lua, Result as LuaResult, Table};
|
||||
use mlua::{Lua, Result as LuaResult, Table, chunk::Chunk};
|
||||
use std::{
|
||||
env,
|
||||
env, fs,
|
||||
hash::{Hash, Hasher},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
@@ -79,3 +79,33 @@ pub fn append_lua_package_dir(lua: &Lua, path: &Path) -> LuaResult<()> {
|
||||
append_lua_package_path(lua, &format!("{path}/?/init.lua"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites PoB's `#@ <label>` script header into a Lua comment.
|
||||
///
|
||||
/// Some Path of Building scripts start with a line such as `#@ <optional_text>`. Recent LuaJIT
|
||||
/// versions interpret a leading `#` as a line number directive and reject this header so we
|
||||
/// replace them with a comment.
|
||||
///
|
||||
/// commit that introduced changes to the lexer to enable parsing of line number directives:
|
||||
/// <https://github.com/LuaJIT/LuaJIT/commit/c41d727dbffa5ec4f346dd9be0f4c64740f124aa>
|
||||
pub fn fix_script_header(source: &mut [u8]) {
|
||||
// skip utf8-bom
|
||||
let start = if source.starts_with(b"\xEF\xBB\xBF") {
|
||||
3
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if source[start..].starts_with(b"#@") {
|
||||
source[start..start + 2].copy_from_slice(b"--");
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads a Lua script from `path` and applies `fix_script_header`.
|
||||
///
|
||||
/// The chunk name is set to `@<path>` to match `Lua::load`'s behavior for paths, so error messages
|
||||
/// keep referring to the file.
|
||||
pub fn load_lua_file<'lua>(lua: &'lua Lua, path: &Path) -> LuaResult<Chunk<'lua>> {
|
||||
let mut source = fs::read(path)?;
|
||||
fix_script_header(&mut source);
|
||||
Ok(lua.load(source).set_name(format!("@{}", path.display())))
|
||||
}
|
||||
Reference in new issue
Block a user