diff --git a/src/app.rs b/src/app.rs index e172160..a138b9e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -13,8 +13,11 @@ use anyhow::Result; use std::sync::Arc; use std::{cell::RefCell, path::PathBuf, rc::Rc}; use winit::{ - application::ApplicationHandler, event::*, event_loop::ActiveEventLoop, - platform::modifier_supplement::KeyEventExtModifierSupplement, window::Window, + application::ApplicationHandler, + event::{ElementState, MouseScrollDelta, WindowEvent}, + event_loop::ActiveEventLoop, + platform::modifier_supplement::KeyEventExtModifierSupplement, + window::Window, }; struct FrameOutput { @@ -78,7 +81,7 @@ impl App { self.handle_event(StageEvent::Exit); event_loop.exit(); } - }; + } } Ok(()) } @@ -214,7 +217,7 @@ impl ApplicationHandler for App { if let Some(ref mut gfx) = self.gfx_context { match gfx.render(render_job) { - Ok(_) => {} + Ok(()) => {} Err(err) => { log::error!("Unable to render: {err}"); } diff --git a/src/args.rs b/src/args.rs index a1c46ce..1828e51 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1,14 +1,9 @@ -//! `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::ValueEnum; use directories::BaseDirs; use std::path::PathBuf; -/// CLI arguments passed to the application on launch. +/// CLI arguments passed to the application. #[derive(Parser, Debug)] #[command(version, about, long_about = None)] pub struct Args { @@ -23,7 +18,7 @@ pub struct Args { pub import_url: Option, } -/// Enum representing which game (PoE1 or PoE2) the application needs to launch. +/// Enum representing the game version. #[derive(Debug, Clone, Copy, ValueEnum)] pub enum Game { /// Path of Exile 1 @@ -35,17 +30,17 @@ pub enum Game { } impl Game { - /// Returns the path to the user’s data directory based on which `Game` option - /// was used to start the application. + /// Returns the path to the user’s data directory based on which `Game` option was used to + /// start the application. pub fn data_dir(&self) -> PathBuf { let directory_name = match self { - Game::Poe1 => "RustyPathOfBuilding1", - Game::Poe2 => "RustyPathOfBuilding2", + Self::Poe1 => "RustyPathOfBuilding1", + Self::Poe2 => "RustyPathOfBuilding2", }; BaseDirs::new().unwrap().data_dir().join(directory_name) } - /// Returns the path to the user's data directory. Calls [`Self::data_dir`]. + /// Returns the path to the user's data directory. pub fn script_dir(&self) -> PathBuf { self.data_dir() } diff --git a/src/batcher.rs b/src/batcher.rs index 674e7c5..ed6cd64 100644 --- a/src/batcher.rs +++ b/src/batcher.rs @@ -37,7 +37,7 @@ impl BatchBuilder { /// Tries to assign a texture to the batch. /// - /// Returns slot_index into textures array if texture can be assigned. + /// Returns `slot_index` into textures array if texture can be assigned. /// Returns `None` if maximum amount of texture slots is reached. fn try_assign(&mut self, id: TextureId, max_slots: NonZeroU32) -> Option { if let Some(&slot) = self.texture_mapping.get(&id) { diff --git a/src/draw_commands.rs b/src/draw_commands.rs index 3e7e9f6..1e5e670 100644 --- a/src/draw_commands.rs +++ b/src/draw_commands.rs @@ -91,7 +91,7 @@ impl DrawCommandRecorder { let (texture_id, uvs, texture_layer_idx) = match texture_id { Some(texture_id) => ( texture_id, - uv.map_or(UvQuad::full_uv(), |uv_rect| uv_rect.into()), + uv.map_or_else(UvQuad::full_uv, |uv_rect| uv_rect.into()), layer_idx, ), None => (TextureId::default(), UvQuad::white_uv(), 0), @@ -122,7 +122,7 @@ impl DrawCommandRecorder { layer_idx: u32, ) { let (texture_id, uvs, texture_layer_idx) = match texture_id { - Some(texture_id) => (texture_id, uv.unwrap_or(UvQuad::full_uv()), layer_idx), + Some(texture_id) => (texture_id, uv.unwrap_or_else(UvQuad::full_uv), layer_idx), None => (TextureId::default(), UvQuad::white_uv(), 0), }; diff --git a/src/fonts.rs b/src/fonts.rs index 8e56310..f9834b9 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -68,7 +68,7 @@ impl Fonts { layout_context: LayoutContext::new(), atlas: FontAtlas::new(1024, 1024), glyph_rasterizer: GlyphRasterizer::new(), - layout_cache: Default::default(), + layout_cache: LayoutCache::default(), }; fonts.register_fonts(); @@ -205,10 +205,9 @@ impl Fonts { font_family: job.font_family, font_size: job.font_size.into(), line_height: parley::LineHeight::Absolute(job.line_height.into()), - font_weight: job - .font_weight - .map(|w| parley::FontWeight::new(w.into())) - .unwrap_or(default_style.font_weight), + font_weight: job.font_weight.map_or(default_style.font_weight, |w| { + parley::FontWeight::new(w.into()) + }), font_style: job.font_style.into(), ..default_style }; diff --git a/src/fonts/atlas.rs b/src/fonts/atlas.rs index f930b61..2183bfd 100644 --- a/src/fonts/atlas.rs +++ b/src/fonts/atlas.rs @@ -210,10 +210,12 @@ impl FontAtlas { let a = image.data[i]; // SAFETY: allocated atlas region and swash image have the same size unsafe { - allocation - .sub_image - .unsafe_put_pixel(x, y, Srgba::new(255, 255, 255, a).into()) - }; + allocation.sub_image.unsafe_put_pixel( + x, + y, + Srgba::new(255, 255, 255, a).into(), + ); + } i += 1; } } diff --git a/src/fonts/layout.rs b/src/fonts/layout.rs index 9e5992a..9a52529 100644 --- a/src/fonts/layout.rs +++ b/src/fonts/layout.rs @@ -14,7 +14,7 @@ pub type LayoutRect = Rect; pub type LayoutToLogical = Translation; -#[derive(Copy, Clone, Default, Debug, Hash, PartialEq)] +#[derive(Copy, Clone, Default, Debug, Hash, Eq, PartialEq)] pub enum Alignment { #[default] Min, @@ -22,7 +22,7 @@ pub enum Alignment { Max, } -#[derive(Copy, Clone, Default, Debug, Hash, PartialEq)] +#[derive(Copy, Clone, Default, Debug, Hash, Eq, PartialEq)] pub enum FontStyle { #[default] Normal, @@ -32,8 +32,8 @@ pub enum FontStyle { impl From for parley::FontStyle { fn from(value: FontStyle) -> Self { match value { - FontStyle::Normal => parley::FontStyle::Normal, - FontStyle::Italic => parley::FontStyle::Italic, + FontStyle::Normal => Self::Normal, + FontStyle::Italic => Self::Italic, } } } diff --git a/src/fonts/rasterizer.rs b/src/fonts/rasterizer.rs index f68e551..21c3fb0 100644 --- a/src/fonts/rasterizer.rs +++ b/src/fonts/rasterizer.rs @@ -43,10 +43,10 @@ impl GlyphRasterizer { pub fn new() -> Self { Self { scale_context: swash::scale::ScaleContext::new(), - swash_keys: Default::default(), - style_cache: Default::default(), - cached_glyphs: Default::default(), - scratch: Default::default(), + swash_keys: HashMap::default(), + style_cache: StyleCache::default(), + cached_glyphs: HashMap::default(), + scratch: swash::scale::image::Image::default(), } } @@ -158,7 +158,7 @@ fn rasterize_glyph( if !did_render || image.placement.width == 0 || image.placement.height == 0 { return None; - }; + } let (size, uv, layer_idx) = atlas.write_mask(image); diff --git a/src/installer.rs b/src/installer.rs index bcc07f7..a07e365 100644 --- a/src/installer.rs +++ b/src/installer.rs @@ -107,10 +107,9 @@ impl Installer { pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result> { match event { StageEvent::Resized(size) => self.window_state.size = size, - StageEvent::ScaleFactorChanged(factor) => - { + StageEvent::ScaleFactorChanged(factor) => { #[allow(clippy::cast_possible_truncation)] - self.window_state.set_scale_factor(factor as f32) + self.window_state.set_scale_factor(factor as f32); } _ => {} } diff --git a/src/installer/download.rs b/src/installer/download.rs index 5ec5ab5..2de6c80 100644 --- a/src/installer/download.rs +++ b/src/installer/download.rs @@ -122,6 +122,9 @@ pub enum ExtractionRule { RewritePrefix { prefix: String, dest_dir: PathBuf }, } +const CHUNK_SIZE: usize = 512 * 1024; +const PROGRESS_INTERVAL: Duration = Duration::from_millis(50); + /// Download a GitHub release tarball and extract entries to specified destinations. pub fn download_and_extract_tarball( client: &Client, @@ -146,13 +149,11 @@ pub fn download_and_extract_tarball( 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)?; diff --git a/src/math/quad.rs b/src/math/quad.rs index 96746f3..3840bf8 100644 --- a/src/math/quad.rs +++ b/src/math/quad.rs @@ -52,10 +52,10 @@ impl fmt::Debug for Quad { impl Default for Quad { fn default() -> Self { Self::new( - Default::default(), - Default::default(), - Default::default(), - Default::default(), + Point::default(), + Point::default(), + Point::default(), + Point::default(), ) } } diff --git a/src/pob/api.rs b/src/pob/api.rs index 0f4c859..f4caaee 100644 --- a/src/pob/api.rs +++ b/src/pob/api.rs @@ -202,10 +202,10 @@ pub enum Input { impl Input { fn as_pob_key_str(&self) -> Option { match self { - Input::Keyboard(key) => key_as_str(key.clone()), - Input::Mouse(button) => mousebutton_as_str(*button), - Input::WheelUp => Some("WHEELUP".into()), - Input::WheelDown => Some("WHEELDOWN".into()), + Self::Keyboard(key) => key_as_str(key.clone()), + Self::Mouse(button) => mousebutton_as_str(*button), + Self::WheelUp => Some("WHEELUP".into()), + Self::WheelDown => Some("WHEELDOWN".into()), } } } diff --git a/src/pob/api/image_handle.rs b/src/pob/api/image_handle.rs index 21c7b84..0e1dd59 100644 --- a/src/pob/api/image_handle.rs +++ b/src/pob/api/image_handle.rs @@ -21,7 +21,7 @@ impl ImageHandle { Self { texture: None } } - #[inline(always)] + #[inline] pub fn texture_id(&self) -> Option { self.texture.as_ref().map(TextureHandle::id) } @@ -33,18 +33,15 @@ impl ImageHandle { #[inline] pub fn is_loading(&self) -> bool { - match &self.texture { - Some(texture) => texture.is_loading(), - None => true, - } + self.texture.as_ref().is_none_or(TextureHandle::is_loading) } #[inline] pub fn image_size(&self) -> PhysicalSize { - match &self.texture { - Some(texture) => texture.size().unwrap_or(PhysicalSize::zero()), - None => PhysicalSize::zero(), - } + self.texture + .as_ref() + .and_then(TextureHandle::size) + .unwrap_or_else(PhysicalSize::zero) } } @@ -62,7 +59,7 @@ const IMAGE_HANDLE_METATABLE: &[u8] = b"runtime.ImageHandle\0"; #[inline] unsafe fn push_image_handle(state: *mut ffi::lua_State) -> *mut ImageHandle { let ptr = unsafe { ffi::lua_newuserdata(state, std::mem::size_of::()) } - as *mut ImageHandle; + .cast::(); // Construct the Rust object directly in Lua-owned memory unsafe { @@ -78,7 +75,7 @@ unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_in push_image_handle(state); // The metatable must already have been registered. - ffi::luaL_getmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr() as *const _); + ffi::luaL_getmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr().cast()); ffi::lua_setmetatable(state, -2); } @@ -89,12 +86,12 @@ unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_in #[inline] unsafe fn get_image_handle(state: *mut ffi::lua_State, index: c_int) -> *mut ImageHandle { unsafe { - ffi::luaL_checkudata(state, index, IMAGE_HANDLE_METATABLE.as_ptr() as *const _) - as *mut ImageHandle + ffi::luaL_checkudata(state, index, IMAGE_HANDLE_METATABLE.as_ptr().cast()) + .cast::() } } -#[inline(always)] +#[inline] pub unsafe fn image_handle_texture_id( state: *mut ffi::lua_State, index: c_int, @@ -103,7 +100,7 @@ pub unsafe fn image_handle_texture_id( return None; } - let ptr = unsafe { ffi::lua_touserdata(state, index) } as *const ImageHandle; + let ptr = unsafe { ffi::lua_touserdata(state, index) }.cast::(); if ptr.is_null() { return None; @@ -114,7 +111,7 @@ pub unsafe fn image_handle_texture_id( // Drops the `ImageHandle` 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) }.cast::(); if !ptr.is_null() { unsafe { @@ -131,7 +128,7 @@ unsafe extern "C-unwind" fn image_handle_is_valid(state: *mut ffi::lua_State) -> let valid = unsafe { (*handle).is_valid() }; unsafe { - ffi::lua_pushboolean(state, valid as c_int); + ffi::lua_pushboolean(state, c_int::from(valid)); } 1 @@ -143,7 +140,7 @@ unsafe extern "C-unwind" fn image_handle_is_loading(state: *mut ffi::lua_State) let loading = unsafe { (*handle).is_loading() }; unsafe { - ffi::lua_pushboolean(state, loading as c_int); + ffi::lua_pushboolean(state, c_int::from(loading)); } 1 @@ -211,12 +208,12 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i let mut len = 0; - let ptr = unsafe { ffi::lua_tolstring(state, index, &mut len) }; + let ptr = unsafe { ffi::lua_tolstring(state, index, &raw mut len) }; if ptr.is_null() { continue; } - let bytes = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) }; + let bytes = unsafe { std::slice::from_raw_parts(ptr.cast::(), len) }; match bytes { b"CLAMP" => { @@ -268,7 +265,7 @@ unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_i unsafe fn register_image_handle_metatable(state: *mut ffi::lua_State) { unsafe { - let created = ffi::luaL_newmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr() as *const _); + let created = ffi::luaL_newmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr().cast()); // Create metatable if it doesn't exist already if created != 0 { diff --git a/src/pob/api/paths.rs b/src/pob/api/paths.rs index f13ec15..1217bcb 100644 --- a/src/pob/api/paths.rs +++ b/src/pob/api/paths.rs @@ -14,20 +14,17 @@ pub fn get_user_path(l: &Lua, _: ()) -> LuaResult { // parent directory of Launch.lua script pub fn get_script_path(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - Ok(ctx.script_dir.to_owned()) + Ok(ctx.script_dir.clone()) } // parent directory of executable pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult { - match get_executable_dir() { - Ok(exe_path) => Ok(exe_path), - Err(_) => Ok(PathBuf::new()), - } + Ok(get_executable_dir().unwrap_or_default()) } pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); - Ok(ctx.current_working_dir.to_owned()) + Ok(ctx.current_working_dir.clone()) } // NOTE: unused diff --git a/src/pob/api/rendering.rs b/src/pob/api/rendering.rs index 556b4d3..ce50dde 100644 --- a/src/pob/api/rendering.rs +++ b/src/pob/api/rendering.rs @@ -14,7 +14,7 @@ macro_rules! str_from_stack { unsafe { let mut size = 0; let data = ffi::luaL_checklstring($s, $i, &mut size); - let bytes = std::slice::from_raw_parts(data as *const u8, size); + let bytes = std::slice::from_raw_parts(data.cast::(), size); std::str::from_utf8_unchecked(bytes) } }; @@ -74,10 +74,10 @@ pub unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_ let ctx = lua_instance.app_data_ref::().unwrap(); let color: [f32; 4] = ctx.recorder.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) }; + unsafe { ffi::lua_pushnumber(state, f64::from(color[0])) }; + unsafe { ffi::lua_pushnumber(state, f64::from(color[1])) }; + unsafe { ffi::lua_pushnumber(state, f64::from(color[2])) }; + unsafe { ffi::lua_pushnumber(state, f64::from(color[3])) }; 4 } diff --git a/src/pob/api/search_handle.rs b/src/pob/api/search_handle.rs index 1adb8be..b2658c4 100644 --- a/src/pob/api/search_handle.rs +++ b/src/pob/api/search_handle.rs @@ -64,16 +64,19 @@ impl UserData for SearchHandle { methods.add_method_mut("GetFileName", |l, this, ()| { Ok(this.current.as_ref().unwrap().file_name().into_lua(l)) }); - methods.add_method("GetFileSize", |_, this, ()| match &this.current { - Some(path) => match fs::metadata(path) { - Ok(metadata) => Ok(metadata.len()), - Err(_) => Ok(0), - }, - None => Ok(0), + methods.add_method("GetFileSize", |_, this, ()| { + Ok(this + .current + .as_ref() + .and_then(|path| fs::metadata(path).ok()) + .map_or(0, |metadata| metadata.len())) }); - methods.add_method("GetFileModifiedTime", |_, this, ()| match &this.current { - Some(path) => get_time_modified(path).map_or(Ok(0), Ok), - None => Ok(0), + methods.add_method("GetFileModifiedTime", |_, this, ()| { + Ok(this + .current + .as_ref() + .and_then(|path| get_time_modified(path).ok()) + .unwrap_or(0)) }); } } diff --git a/src/pob/api/text.rs b/src/pob/api/text.rs index 3017b1e..1c40f51 100644 --- a/src/pob/api/text.rs +++ b/src/pob/api/text.rs @@ -19,7 +19,7 @@ macro_rules! str_from_stack { unsafe { let mut size = 0; let data = ffi::luaL_checklstring($s, $i, &mut size); - let bytes = std::slice::from_raw_parts(data as *const u8, size); + let bytes = std::slice::from_raw_parts(data.cast::(), size); std::str::from_utf8_unchecked(bytes) } }; @@ -140,7 +140,7 @@ pub unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> .layout(job, ctx.window_state.scale_factor()); let width = layout.width(); - unsafe { ffi::lua_pushnumber(state, width as f64) }; + unsafe { ffi::lua_pushnumber(state, f64::from(width)) }; 1 } @@ -313,7 +313,7 @@ impl<'a> IntoIterator for PoBString<'a> { } /// A segment of text that shares the same color. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct ColoredSegment<'a> { pub color: Option, pub text: &'a str, @@ -353,36 +353,33 @@ impl<'a> Iterator for PoBStringSegmentIterator<'a> { } loop { - match self.captures.next() { - Some(captures) => { - let m = &captures.get(0).expect("group 0 always matches"); - let start = self.cursor; - let text = &self.haystack[start..m.start()]; - let color = self.color; + if let Some(captures) = self.captures.next() { + let m = &captures.get(0).expect("group 0 always matches"); + let start = self.cursor; + let text = &self.haystack[start..m.start()]; + let color = self.color; - self.cursor = m.end(); - self.color = Some(Srgba::from_escape_code(m.as_str())); + self.cursor = m.end(); + self.color = Some(Srgba::from_escape_code(m.as_str())); - // check for case where string starts with escape code - if text.is_empty() && color.is_none() { - continue; - } - - return Some(ColoredSegment { - color, - text, - original_start: start, - }); - } - None => { - self.done = true; - return Some(ColoredSegment { - color: self.color, - text: &self.haystack[self.cursor..], - original_start: self.cursor, - }); + // check for case where string starts with escape code + if text.is_empty() && color.is_none() { + continue; } + + return Some(ColoredSegment { + color, + text, + original_start: start, + }); } + + self.done = true; + return Some(ColoredSegment { + color: self.color, + text: &self.haystack[self.cursor..], + original_start: self.cursor, + }); } } } diff --git a/src/pob/subscript.rs b/src/pob/subscript.rs index 9f4f5ff..ab0e24c 100644 --- a/src/pob/subscript.rs +++ b/src/pob/subscript.rs @@ -191,10 +191,9 @@ impl Subscript { /// /// Does nothing if there is no pending call. fn handle_calls(&self, lua: &Lua) { - let call = match self.call_rx.try_recv() { - Ok(call) => call, + let Ok(call) = self.call_rx.try_recv() else { // no pending call, or thread disconnected which is handled on join - Err(_) => return, + return; }; match call { diff --git a/src/renderer/textures.rs b/src/renderer/textures.rs index 0218a38..7771c06 100644 --- a/src/renderer/textures.rs +++ b/src/renderer/textures.rs @@ -294,7 +294,7 @@ impl TextureManager { #[inline] pub fn update_font_texture(&self, delta: Vec) { - for d in delta.into_iter() { + for d in delta { self.manager.borrow_mut().set(TextureId::default(), d); } } diff --git a/src/util.rs b/src/util.rs index 63f30f6..74bb245 100644 --- a/src/util.rs +++ b/src/util.rs @@ -15,8 +15,8 @@ pub fn get_executable_dir() -> anyhow::Result { pub fn change_working_directory>(path: P) -> anyhow::Result<()> { env::set_current_dir(path.as_ref()).map_err(|e| { anyhow::anyhow!( - "Failed to change working directory {:?}: {}", - path.as_ref(), + "Failed to change working directory {}: {}", + path.as_ref().display(), e ) })