This commit is contained in:
meehl committed 2026-08-12 20:46:43 +02:00
1 parent 99fc9f608e
commit e43da1b9e8
25 files changed
+110 -135

No files matched your search

+1 -1
View File
@@ -79,7 +79,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?; globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
// image handle // image handle
register_image_handle_api(&lua)?; register_image_handle_api(lua)?;
// clipboard // clipboard
globals.set("Copy", lua.create_function(copy)?)?; globals.set("Copy", lua.create_function(copy)?)?;
+8 -9
View File
@@ -12,16 +12,15 @@ pub fn get_callback(lua: &Lua, name: &str) -> LuaResult<Function> {
if callback_function.is_function() { if callback_function.is_function() {
// function defined through `SetCallback` // function defined through `SetCallback`
return Ok(callback_function.as_function().unwrap().clone()); return Ok(callback_function.as_function().unwrap().clone());
} else {
// look for function in `MainObject`
let main_object: Table = callback_table.get("MainObject")?;
let callback_function: Value = main_object.get(name)?;
if callback_function.is_function() {
// these functions expect `MainObject` as first argument so we bind it here
return callback_function.as_function().unwrap().bind(main_object);
}
} }
Err(anyhow::anyhow!("Function '{}' not found", name).into()) // look for function in `MainObject`
let main_object: Table = callback_table.get("MainObject")?;
let callback_function: Value = main_object.get(name)?;
if callback_function.is_function() {
// these functions expect `MainObject` as first argument so we bind it here
return callback_function.as_function().unwrap().bind(main_object);
}
Err(anyhow::anyhow!("Function '{name}' not found").into())
} }
pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> { pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> {
+2 -2
View File
@@ -34,9 +34,9 @@ fn print_table(table: &Table, indent: usize, recursive: bool) -> LuaResult<()> {
let (key, value) = pair?; let (key, value) = pair?;
if key.is_string() { if key.is_string() {
write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?,)?; write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?)?;
} else { } else {
write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?,)?; write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?)?;
} }
if value.is_table() { if value.is_table() {
+3 -3
View File
@@ -74,7 +74,7 @@ unsafe fn push_image_handle(state: *mut ffi::lua_State) -> *mut ImageHandle {
ptr ptr
} }
/// Puts ImageHandle on the Lua stack /// Puts `ImageHandle` on the Lua stack
unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_int {
unsafe { unsafe {
push_image_handle(state); push_image_handle(state);
@@ -87,7 +87,7 @@ unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_in
1 1
} }
/// Get an ImageHandle from the Lua stack. /// Gets an `ImageHandle` from the Lua stack.
#[inline] #[inline]
unsafe fn get_image_handle(state: *mut ffi::lua_State, index: c_int) -> *mut ImageHandle { unsafe fn get_image_handle(state: *mut ffi::lua_State, index: c_int) -> *mut ImageHandle {
unsafe { unsafe {
@@ -114,7 +114,7 @@ pub unsafe fn image_handle_texture_id(
unsafe { (*ptr).texture_id() } unsafe { (*ptr).texture_id() }
} }
// Drops the ImageHandle // Drops the `ImageHandle`
unsafe extern "C-unwind" fn image_handle_gc(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn image_handle_gc(state: *mut ffi::lua_State) -> c_int {
let ptr = unsafe { ffi::lua_touserdata(state, 1) } as *mut ImageHandle; let ptr = unsafe { ffi::lua_touserdata(state, 1) } as *mut ImageHandle;
+1 -1
View File
@@ -27,7 +27,7 @@ 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 ctx = l.app_data_ref::<&'static Context>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(ctx.current_working_dir().to_path_buf()) Ok(ctx.current_working_dir().clone())
} }
// NOTE: unused // NOTE: unused
+12 -21
View File
@@ -108,7 +108,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
ctx.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; }
0 0
} }
@@ -146,7 +146,7 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
ctx.layers().set_viewport(rect); ctx.layers().set_viewport(rect);
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; }
0 0
} }
@@ -180,7 +180,7 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
} }
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; }
0 0
} }
@@ -313,13 +313,11 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
let font_type = str_from_stack!(state, -nargs + 4); let font_type = str_from_stack!(state, -nargs + 4);
let text = str_from_stack!(state, -nargs + 5); let text = str_from_stack!(state, -nargs + 5);
let alignment = match alignment.parse::<PoBTextAlignment>() { let Ok(alignment) = alignment.parse::<PoBTextAlignment>() else {
Ok(alignment) => alignment, panic!("Invalid alignment");
Err(_) => panic!("Invalid alignment"),
}; };
let font_type = match font_type.parse::<PoBFontType>() { let Ok(font_type) = font_type.parse::<PoBFontType>() else {
Ok(font_type) => font_type, panic!("Invalid font type");
Err(_) => panic!("Invalid font type"),
}; };
let mut position = Point::new(x, y); let mut position = Point::new(x, y);
@@ -375,9 +373,8 @@ unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_in
let font_type = str_from_stack!(state, -nargs + 1); let font_type = str_from_stack!(state, -nargs + 1);
let text = str_from_stack!(state, -nargs + 2); let text = str_from_stack!(state, -nargs + 2);
let font_type = match font_type.parse::<PoBFontType>() { let Ok(font_type) = font_type.parse::<PoBFontType>() else {
Ok(font_type) => font_type, panic!("Invalid font type");
Err(_) => panic!("Invalid font type"),
}; };
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);
@@ -478,7 +475,7 @@ fn build_layout_job<'a>(
font_style, font_style,
); );
for (color, segment) in PoBString(text).into_iter() { for (color, segment) in PoBString(text) {
job.append(segment, color.unwrap_or(current_color)); job.append(segment, color.unwrap_or(current_color));
} }
@@ -600,10 +597,7 @@ impl std::str::FromStr for PoBTextAlignment {
"RIGHT" => Ok(Self::Right), "RIGHT" => Ok(Self::Right),
"CENTER_X" => Ok(Self::CenterX), "CENTER_X" => Ok(Self::CenterX),
"RIGHT_X" => Ok(Self::RightX), "RIGHT_X" => Ok(Self::RightX),
_ => Err(anyhow::anyhow!( _ => Err(anyhow::anyhow!("'{s}' is not a valid TextFontType variant")),
"'{}' is not a valid TextFontType variant",
s
)),
} }
} }
} }
@@ -631,10 +625,7 @@ impl std::str::FromStr for PoBFontType {
"FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic), "FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic),
"FONTIN" => Ok(Self::Fontin), "FONTIN" => Ok(Self::Fontin),
"FONTIN ITALIC" => Ok(Self::FontinItalic), "FONTIN ITALIC" => Ok(Self::FontinItalic),
_ => Err(anyhow::anyhow!( _ => Err(anyhow::anyhow!("'{s}' is not a valid TextFontType variant")),
"'{}' is not a valid TextFontType variant",
s
)),
} }
} }
} }
+1 -1
View File
@@ -19,7 +19,7 @@ pub fn new_search_handle(
if handle.current.is_some() { if handle.current.is_some() {
return handle.into_lua(l); return handle.into_lua(l);
} }
}; }
Ok(Value::Nil) Ok(Value::Nil)
} }
+1 -4
View File
@@ -72,15 +72,12 @@ impl std::hash::Hash for LayoutJob<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) { fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.segments.hash(state); self.segments.hash(state);
match &self.font_family { match &self.font_family {
FontFamily::Single(FontFamilyName::Named(cow)) => { FontFamily::Single(FontFamilyName::Named(cow)) | FontFamily::Source(cow) => {
cow.hash(state); cow.hash(state);
} }
FontFamily::Single(FontFamilyName::Generic(generic_family)) => { FontFamily::Single(FontFamilyName::Generic(generic_family)) => {
generic_family.hash(state); generic_family.hash(state);
} }
FontFamily::Source(cow) => {
cow.hash(state);
}
FontFamily::List(cow) => { FontFamily::List(cow) => {
for name in cow.iter() { for name in cow.iter() {
match name { match name {
+1 -1
View File
@@ -118,7 +118,7 @@ impl GlyphRasterizer {
self.cached_glyphs.clear(); self.cached_glyphs.clear();
} }
/// Gets a swash::FontRef from FontData /// Gets a [`swash::FontRef`] from [`FontData`]
fn get_font_ref<'a>(&mut self, font: &'a FontData) -> swash::FontRef<'a> { fn get_font_ref<'a>(&mut self, font: &'a FontData) -> swash::FontRef<'a> {
let font_blob_id = font.data.id(); let font_blob_id = font.data.id();
+7 -7
View File
@@ -22,11 +22,11 @@ struct MousePressState {
pub struct InputState { pub struct InputState {
/// Current state(s) of modifier keys. (Shift, Control, Alt, Super) /// Current state(s) of modifier keys. (Shift, Control, Alt, Super)
pub key_modifiers: ModifiersState, pub key_modifiers: ModifiersState,
/// HashSet of currently pressed keyboard keys. /// `HashSet` of currently pressed keyboard keys.
keys_pressed: HashSet<Key>, keys_pressed: HashSet<Key>,
/// HashSet of currently pressed mouse buttons. /// `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. /// `HashMap` of mouse buttons (keys) with the last time they were pressed.
mouse_last_pressed: HashMap<MouseButton, MousePressState>, mouse_last_pressed: HashMap<MouseButton, MousePressState>,
/// Current cursor position relative to the top-left corner of the window. /// Current cursor position relative to the top-left corner of the window.
cursor_pos: LogicalPoint<f32>, cursor_pos: LogicalPoint<f32>,
@@ -105,7 +105,7 @@ impl InputState {
} }
} }
/// Attempts to convert the provided string `s` to a [winit::keyboard::Key]. /// Attempts to convert the provided string `s` to a [`winit::keyboard::Key`].
/// Returns [None] if no matching Key found. /// Returns [None] if no matching Key found.
pub fn str_as_key(s: &str) -> Option<Key> { pub fn str_as_key(s: &str) -> Option<Key> {
Some(match s.to_uppercase().as_str() { Some(match s.to_uppercase().as_str() {
@@ -188,7 +188,7 @@ pub fn str_as_key(s: &str) -> Option<Key> {
}) })
} }
/// Attempts to convert the provided [winit::keyboard::Key] `key` to a string /// Attempts to convert the provided [`winit::keyboard::Key`] `key` to a string
/// representation that PoB recognizes. /// representation that PoB recognizes.
/// ///
/// Returns [None] if no matching string found. /// Returns [None] if no matching string found.
@@ -257,10 +257,10 @@ pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
}) })
} }
/// Attempts to convert the provided [MouseButton] to a [SmolStr] that the PoB Lua /// Attempts to convert the provided [`MouseButton`] to a [`SmolStr`] that the PoB Lua
/// backend recognizes. /// backend recognizes.
/// ///
/// Returns [None] if no matching [MouseButton] was found. /// Returns [None] if no matching [`MouseButton`] was found.
pub fn mousebutton_as_str(button: MouseButton) -> Option<SmolStr> { pub fn mousebutton_as_str(button: MouseButton) -> Option<SmolStr> {
Some(match button { Some(match button {
MouseButton::Left => SmolStr::new("LEFTBUTTON"), MouseButton::Left => SmolStr::new("LEFTBUTTON"),
+4 -4
View File
@@ -220,7 +220,7 @@ fn fetch_compatibility_info(
// Beta versions have a non-semver suffix and are filtered out by the regex. // Beta versions have a non-semver suffix and are filtered out by the regex.
Ok(compatibility_table Ok(compatibility_table
.pairs::<String, String>() .pairs::<String, String>()
.filter_map(|p| p.ok()) .filter_map(Result::ok)
.filter(|(pob_version, _)| VERSION_RE.is_match(pob_version)) .filter(|(pob_version, _)| VERSION_RE.is_match(pob_version))
.map(|(pob_version, min_req_rpob_ver)| VersionReq { .map(|(pob_version, min_req_rpob_ver)| VersionReq {
pob_ver: pob_version, pob_ver: pob_version,
@@ -292,7 +292,7 @@ fn download_pob<P: AsRef<Path>>(
]; ];
download_and_extract_tarball( download_and_extract_tarball(
&client, client,
pob_repo, pob_repo,
&format!("v{pob_version}"), &format!("v{pob_version}"),
&rules, &rules,
@@ -313,7 +313,7 @@ fn download_pob<P: AsRef<Path>>(
format!("Downloading assets... ({})", format_bytes(downloaded)) format!("Downloading assets... ({})", format_bytes(downloaded))
} }
DownloadEvent::Retrying { attempt } => { DownloadEvent::Retrying { attempt } => {
format!("Retrying... (Attempt {})", attempt) format!("Retrying... (Attempt {attempt})")
} }
}; };
let _ = progress_tx.send(Progress::Status(msg)); let _ = progress_tx.send(Progress::Status(msg));
@@ -391,7 +391,7 @@ fn is_higher_version(v1: &str, v2: &str) -> anyhow::Result<bool> {
let parse_version = |v: &str| -> anyhow::Result<(u32, u32, u32)> { let parse_version = |v: &str| -> anyhow::Result<(u32, u32, u32)> {
let caps = VERSION_RE let caps = VERSION_RE
.captures(v) .captures(v)
.ok_or_else(|| anyhow::anyhow!("Invalid semver format: {}", v))?; .ok_or_else(|| anyhow::anyhow!("Invalid semver format: {v}"))?;
let major = caps[1].parse::<u32>().unwrap(); let major = caps[1].parse::<u32>().unwrap();
let minor = caps[2].parse::<u32>().unwrap(); let minor = caps[2].parse::<u32>().unwrap();
+3 -4
View File
@@ -19,7 +19,7 @@ pub enum DownloadEvent {
/// Build a reqwest blocking client /// Build a reqwest blocking client
pub fn build_client() -> Result<Client, reqwest::Error> { pub fn build_client() -> Result<Client, reqwest::Error> {
Client::builder().timeout(Duration::from_secs(60)).build() Client::builder().timeout(Duration::from_mins(1)).build()
} }
// Rate-limit-aware GET. // Rate-limit-aware GET.
@@ -194,9 +194,8 @@ pub fn download_and_extract_tarball(
} }
// Strip root folder before matching against rules // Strip root folder before matching against rules
let relative = match entry_str.split_once('/') { let Some((_, relative)) = entry_str.split_once('/') else {
Some((_, rest)) => rest, continue;
None => continue,
}; };
let dest: Option<PathBuf> = rules.iter().find_map(|rule| match rule { let dest: Option<PathBuf> = rules.iter().find_map(|rule| match rule {
+1 -1
View File
@@ -123,7 +123,7 @@ impl Layers {
pub fn add_text(&mut self, mut text: TextPrimitive, is_absolute_position: bool) { pub fn add_text(&mut self, mut text: TextPrimitive, is_absolute_position: bool) {
if !is_absolute_position { if !is_absolute_position {
text.translate(self.viewport.min.to_vector()); text.translate(self.viewport.min.to_vector());
}; }
let clipped_primitive = ClippedPrimitive { let clipped_primitive = ClippedPrimitive {
clip_rect: self.viewport, clip_rect: self.viewport,
+12 -12
View File
@@ -15,7 +15,7 @@ use clap::Parser;
use mlua::{Function, Lua, Result as LuaResult, Table, thread::ThreadStatus}; use mlua::{Function, Lua, Result as LuaResult, Table, thread::ThreadStatus};
use std::{ use std::{
cell::{Cell, RefCell}, cell::{Cell, RefCell},
path::PathBuf, path::{Path, PathBuf},
rc::Rc, rc::Rc,
}; };
use winit::keyboard::SmolStr; use winit::keyboard::SmolStr;
@@ -77,7 +77,7 @@ impl Context {
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.script_dir.set(&mut ctx.app.script_dir); self.script_dir.set(&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);
@@ -131,14 +131,14 @@ pub enum PoBEvent {
impl std::fmt::Display for PoBEvent { impl std::fmt::Display for PoBEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
PoBEvent::Init => write!(f, "Init"), Self::Init => write!(f, "Init"),
PoBEvent::Exit => write!(f, "Exit"), Self::Exit => write!(f, "Exit"),
PoBEvent::Frame => write!(f, "Frame"), Self::Frame => write!(f, "Frame"),
PoBEvent::KeyDown(_, _) => write!(f, "KeyDown"), Self::KeyDown(_, _) => write!(f, "KeyDown"),
PoBEvent::KeyUp(_) => write!(f, "KeyUp"), Self::KeyUp(_) => write!(f, "KeyUp"),
PoBEvent::Char(_) => write!(f, "Char"), Self::Char(_) => write!(f, "Char"),
PoBEvent::SubFinished { .. } => write!(f, "SubFinished"), Self::SubFinished { .. } => write!(f, "SubFinished"),
PoBEvent::SubError { .. } => write!(f, "SubError"), Self::SubError { .. } => write!(f, "SubError"),
} }
} }
} }
@@ -176,7 +176,7 @@ impl LuaInstance {
}) })
} }
fn create_lua_state(script_dir: &PathBuf) -> LuaResult<Lua> { fn create_lua_state(script_dir: &Path) -> 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() };
@@ -308,7 +308,7 @@ impl LuaInstance {
} }
/// Adds "${script_dir}/lua" to package path /// Adds "${script_dir}/lua" to package path
pub fn register_package_paths(lua: &Lua, script_dir: &PathBuf) -> LuaResult<()> { pub fn register_package_paths(lua: &Lua, script_dir: &Path) -> LuaResult<()> {
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(';');
+4 -4
View File
@@ -59,10 +59,10 @@ fn find_nearby_launch_script() -> Option<PathBuf> {
} }
for candidate in candidates { for candidate in candidates {
if candidate.try_exists().is_ok_and(|exists| exists) { if candidate.try_exists().is_ok_and(|exists| exists)
if let Some(Ok(candidate)) = candidate.parent().map(Path::canonicalize) { && let Some(Ok(candidate)) = candidate.parent().map(Path::canonicalize)
return Some(candidate); {
} return Some(candidate);
} }
} }
+2 -2
View File
@@ -92,7 +92,7 @@ where
where where
T: Zero, T: Zero,
{ {
Quad { Self {
p0: Point::zero(), p0: Point::zero(),
p1: Point::new(size.width, Zero::zero()), p1: Point::new(size.width, Zero::zero()),
p2: Point::new(size.width, size.height), p2: Point::new(size.width, size.height),
@@ -107,7 +107,7 @@ where
{ {
/// Constructor, setting all points to zero. /// Constructor, setting all points to zero.
pub fn zero() -> Self { pub fn zero() -> Self {
Quad::new(Point::zero(), Point::zero(), Point::zero(), Point::zero()) Self::new(Point::zero(), Point::zero(), Point::zero(), Point::zero())
} }
} }
+8 -8
View File
@@ -47,29 +47,29 @@ pub enum AppMode {
impl AppMode { impl AppMode {
pub fn frame(&mut self, state: &mut AppState) -> anyhow::Result<ModeFrameOutput> { pub fn frame(&mut self, state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
match self { match self {
AppMode::Install(mode) => mode.frame(state), Self::Install(mode) => mode.frame(state),
AppMode::PoB(mode) => mode.frame(state), Self::PoB(mode) => mode.frame(state),
} }
} }
pub fn update(&mut self, state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> { pub fn update(&mut self, state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
match self { match self {
AppMode::Install(mode) => mode.update(state), Self::Install(mode) => mode.update(state),
AppMode::PoB(mode) => mode.update(state), Self::PoB(mode) => mode.update(state),
} }
} }
pub fn handle_event(&mut self, state: &mut AppState, event: AppEvent) -> anyhow::Result<()> { pub fn handle_event(&mut self, state: &mut AppState, event: AppEvent) -> anyhow::Result<()> {
match self { match self {
AppMode::Install(mode) => mode.handle_event(state, event), Self::Install(mode) => mode.handle_event(state, event),
AppMode::PoB(mode) => mode.handle_event(state, event), Self::PoB(mode) => mode.handle_event(state, event),
} }
} }
pub fn can_exit(&mut self, state: &mut AppState) -> bool { pub fn can_exit(&mut self, state: &mut AppState) -> bool {
match self { match self {
AppMode::Install(_) => true, Self::Install(_) => true,
AppMode::PoB(mode) => mode.can_exit(state), Self::PoB(mode) => mode.can_exit(state),
} }
} }
} }
+1 -1
View File
@@ -547,7 +547,7 @@ fn create_sampler(options: TextureOptions, device: &wgpu::Device) -> wgpu::Sampl
} }
/// Adapted from `wgpu::Device::create_texture_with_data`. /// Adapted from `wgpu::Device::create_texture_with_data`.
/// Doesn't upload any data for mip level > 0 if skip_mipmaps is true. /// Doesn't upload any data for mip level > 0 if `skip_mipmaps` is true.
fn create_texture_with_data( fn create_texture_with_data(
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
+2 -2
View File
@@ -103,7 +103,7 @@ impl std::fmt::Debug for ImageData {
.field("height", &self.height) .field("height", &self.height)
.field("array_layers", &self.array_layers) .field("array_layers", &self.array_layers)
.field("mipmap_count", &self.mipmap_count) .field("mipmap_count", &self.mipmap_count)
.finish() .finish_non_exhaustive()
} }
} }
@@ -153,7 +153,7 @@ fn dds_format_to_wgpu(format: dds::Format) -> anyhow::Result<wgpu::TextureFormat
dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm, dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm,
dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm, dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm,
dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm, dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm,
_ => anyhow::bail!("Unsupported DDS format: {:?}", format), _ => anyhow::bail!("Unsupported DDS format: {format:?}"),
}) })
} }
+1 -1
View File
@@ -2,7 +2,7 @@
/// Assumes data to contain one mip level 0 image for each layer in RGBA format. /// Assumes data to contain one mip level 0 image for each layer in RGBA format.
pub fn generate_mipmap_chain(queue: &wgpu::Queue, texture: &wgpu::Texture, data: &[u8]) { pub fn generate_mipmap_chain(queue: &wgpu::Queue, texture: &wgpu::Texture, data: &[u8]) {
assert!(!texture.format().is_compressed()); assert!(!texture.format().is_compressed());
assert!(texture.format().components() == 4); assert_eq!(texture.format().components(), 4);
let size = texture.size(); let size = texture.size();
let block_size = texture.format().block_copy_size(None).unwrap_or(4); let block_size = texture.format().block_copy_size(None).unwrap_or(4);
+3 -3
View File
@@ -35,13 +35,13 @@ pub enum DrawPrimitive {
impl DrawPrimitive { impl DrawPrimitive {
pub fn texture_id(&self) -> TextureId { pub fn texture_id(&self) -> TextureId {
match self { match self {
DrawPrimitive::Rect(rect_primitive) => rect_primitive Self::Rect(rect_primitive) => rect_primitive
.texture .texture
.map_or_else(TextureId::default, |tex| tex.texture_id), .map_or_else(TextureId::default, |tex| tex.texture_id),
DrawPrimitive::Quad(quad_primitive) => quad_primitive Self::Quad(quad_primitive) => quad_primitive
.texture .texture
.map_or_else(TextureId::default, |tex| tex.texture_id), .map_or_else(TextureId::default, |tex| tex.texture_id),
_ => TextureId::default(), Self::Text(_) => TextureId::default(),
} }
} }
} }
+16 -17
View File
@@ -57,15 +57,12 @@ impl Tessellator {
return; return;
} }
let start_new_mesh = match out_clipped_meshes.last() { let start_new_mesh = out_clipped_meshes.last().is_none_or(|last_clipped_mesh| {
None => true, // append to previous mesh if clip_rect and texture_id match.
Some(last_clipped_mesh) => { // otherwise, start a new mesh.
// append to previous mesh if clip_rect and texture_id match. !(last_clipped_mesh.clip_rect == clip_rect
// otherwise, start a new mesh. && last_clipped_mesh.mesh.texture_id == primitive.texture_id())
!(last_clipped_mesh.clip_rect == clip_rect });
&& last_clipped_mesh.mesh.texture_id == primitive.texture_id())
}
};
if start_new_mesh { if start_new_mesh {
out_clipped_meshes.push(ClippedMesh { out_clipped_meshes.push(ClippedMesh {
@@ -78,17 +75,19 @@ impl Tessellator {
match primitive { match primitive {
DrawPrimitive::Rect(rect_primitive) => { DrawPrimitive::Rect(rect_primitive) => {
self.convert_rect_primitive(rect_primitive, &mut last_clipped_mesh.mesh) self.convert_rect_primitive(rect_primitive, &mut last_clipped_mesh.mesh);
} }
DrawPrimitive::Quad(quad_primitive) => { DrawPrimitive::Quad(quad_primitive) => {
self.convert_quad_primitive(quad_primitive, &mut last_clipped_mesh.mesh) self.convert_quad_primitive(quad_primitive, &mut last_clipped_mesh.mesh);
}
DrawPrimitive::Text(text_primitive) => {
self.convert_text_primitive(
text_primitive,
font_atlas_size,
pixels_per_point,
&mut last_clipped_mesh.mesh,
);
} }
DrawPrimitive::Text(text_primitive) => self.convert_text_primitive(
text_primitive,
font_atlas_size,
pixels_per_point,
&mut last_clipped_mesh.mesh,
),
} }
// This can be empty if a new mesh was started but the conversion from a text primitive // This can be empty if a new mesh was started but the conversion from a text primitive
+5 -5
View File
@@ -103,7 +103,7 @@ impl TextureManager {
id id
} }
/// Reserves a new TextureId for later assignment. /// Reserves a new `TextureId` for later assignment.
pub fn reserve(&mut self, name: String, options: TextureOptions) -> TextureId { pub fn reserve(&mut self, name: String, options: TextureOptions) -> TextureId {
let id = self.next_id; let id = self.next_id;
self.next_id += 1; self.next_id += 1;
@@ -228,7 +228,7 @@ impl WrappedTextureManager {
.unwrap() .unwrap()
.set(id, ImageDelta::new(image, options)); .set(id, ImageDelta::new(image, options));
} }
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e), Err(e) => log::warn!("Unable to load image fron {image_path}: {e}"),
}); });
TextureHandle::new(manager, id) TextureHandle::new(manager, id)
@@ -239,7 +239,7 @@ impl WrappedTextureManager {
TextureHandle::new(manager, id) TextureHandle::new(manager, id)
} }
Err(e) => { Err(e) => {
log::warn!("Unable to load image fron {}: {}", &image_path, e); log::warn!("Unable to load image fron {image_path}: {e}");
bail!(e); bail!(e);
} }
} }
@@ -265,7 +265,7 @@ impl WrappedTextureManager {
.unwrap() .unwrap()
.set(texture_id, ImageDelta::new(image, options)); .set(texture_id, ImageDelta::new(image, options));
} }
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e), Err(e) => log::warn!("Unable to load image fron {image_path}: {e}"),
}); });
} else { } else {
match load_image_file(Path::new(&image_path)) { match load_image_file(Path::new(&image_path)) {
@@ -276,7 +276,7 @@ impl WrappedTextureManager {
.set(texture_id, ImageDelta::new(image, options)); .set(texture_id, ImageDelta::new(image, options));
} }
Err(e) => { Err(e) => {
log::warn!("Unable to load image fron {}: {}", &image_path, e); log::warn!("Unable to load image fron {image_path}: {e}");
bail!(e); bail!(e);
} }
} }
+8 -16
View File
@@ -65,14 +65,11 @@ impl SubscriptManager {
self.scripts.retain_mut(|subscript| { self.scripts.retain_mut(|subscript| {
subscript.handle_calls(lua); subscript.handle_calls(lua);
if let Some(event) = subscript.try_join() { subscript.try_join().is_none_or(|event| {
results.push(event); results.push(event);
// subscript has finished or errored, remove it // subscript has finished or errored, remove it
false false
} else { })
// subscript has not finished yet, keep it
true
}
}); });
results results
@@ -149,7 +146,7 @@ impl Subscript {
}) })
.unwrap(); .unwrap();
// this blocks until we receive return values // this blocks until we receive return values
let return_values = rx_return.recv().map_err(|e| anyhow!("{}", e))??; let return_values = rx_return.recv().map_err(|e| anyhow!("{e}"))??;
Ok(return_values) Ok(return_values)
})?, })?,
)?; )?;
@@ -165,7 +162,7 @@ impl Subscript {
function_name: function_name.clone(), function_name: function_name.clone(),
arguments: args.try_into()?, arguments: args.try_into()?,
}) })
.map_err(|e| anyhow!("{}", e))?; .map_err(|e| anyhow!("{e}"))?;
Ok(()) Ok(())
})?, })?,
)?; )?;
@@ -227,12 +224,7 @@ impl Subscript {
} }
fn try_join(&mut self) -> Option<SubscriptResult> { fn try_join(&mut self) -> Option<SubscriptResult> {
if self if self.handle.as_ref().is_some_and(JoinHandle::is_finished) {
.handle
.as_ref()
.map(|h| h.is_finished())
.unwrap_or(false)
{
let event = match self.handle.take().unwrap().join() { let event = match self.handle.take().unwrap().join() {
Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished { Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished {
id: self.id, id: self.id,
@@ -272,14 +264,14 @@ pub fn register_subscript_globals(
)| { )| {
let blocking_calls = func_list let blocking_calls = func_list
.split(',') .split(',')
.map(|s| s.trim()) .map(str::trim)
.filter(|&s| !s.is_empty()) .filter(|&s| !s.is_empty())
.map(String::from) .map(String::from)
.collect(); .collect();
let nonblocking_calls = sub_list let nonblocking_calls = sub_list
.split(',') .split(',')
.map(|s| s.trim()) .map(str::trim)
.filter(|&s| !s.is_empty()) .filter(|&s| !s.is_empty())
.map(String::from) .map(String::from)
.collect(); .collect();
@@ -351,7 +343,7 @@ impl TryFrom<MultiValue> for NativeMultiValue {
}) })
.collect::<Result<VecDeque<_>, _>>()?; .collect::<Result<VecDeque<_>, _>>()?;
Ok(NativeMultiValue(native)) Ok(Self(native))
} }
} }
+3 -5
View File
@@ -81,11 +81,9 @@ impl WindowState {
} }
pub fn get_clipboard_text(&mut self) -> Option<String> { pub fn get_clipboard_text(&mut self) -> Option<String> {
if let Some(clipboard) = &mut self.clipboard { self.clipboard
clipboard.get_text() .as_mut()
} else { .and_then(|clipboard| clipboard.get_text())
None
}
} }
pub fn request_redraw(&self) { pub fn request_redraw(&self) {