From 03b2fec7444a3d94f0cb92ff482455011f15c0be Mon Sep 17 00:00:00 2001 From: lashman Date: Mon, 21 Sep 2026 00:44:25 +0300 Subject: [PATCH] tighten visibility and clear the remaining mechanical lint noise --- src-tauri/build.rs | 4 +- src-tauri/src/audio.rs | 18 +++---- src-tauri/src/bootstrap.rs | 27 +++++----- src-tauri/src/capture.rs | 50 +++++++++--------- src-tauri/src/clicks.rs | 4 +- src-tauri/src/config.rs | 8 ++- src-tauri/src/encode.rs | 55 +++++++++---------- src-tauri/src/lib.rs | 97 ++++++++++++++++------------------ src-tauri/src/updates.rs | 27 +++++----- src-tauri/src/window_picker.rs | 28 +++++----- src-tauri/src/windows_list.rs | 12 ++--- 11 files changed, 158 insertions(+), 172 deletions(-) diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 2bff717..4389b43 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -7,10 +7,10 @@ fn main() { } /// Compile the HDR tonemap HLSL to bytecode at build time so we can embed it -/// via include_bytes! and avoid a runtime dependency on d3dcompiler_47.dll. +/// via `include_bytes`! and avoid a runtime dependency on `d3dcompiler_47.dll`. /// Looks for fxc.exe in the installed Windows SDK. If fxc is unavailable the /// .cso files are emitted empty and capture.rs falls back to runtime -/// D3DCompile (so a clean checkout without the SDK still builds). +/// `D3DCompile` (so a clean checkout without the SDK still builds). fn compile_shaders() { let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR")); let shader_dir = PathBuf::from("shaders"); diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs index bc12a16..d1938cd 100644 --- a/src-tauri/src/audio.rs +++ b/src-tauri/src/audio.rs @@ -29,7 +29,7 @@ pub struct AudioSession { /// `running` was flipped to false by a normal stop). The frontend-facing /// watchdog in lib.rs polls this to emit `audio-failed` mid-record, since /// an unplugged endpoint or a default-output switch otherwise leaves the - /// session slot populated with a dead thread until stop_capture. + /// session slot populated with a dead thread until `stop_capture`. died: Arc, output_path: PathBuf, pub sample_rate: u32, @@ -37,7 +37,7 @@ pub struct AudioSession { pub started_at: std::time::Instant, } -pub fn start(output_path: PathBuf) -> Result { +pub(crate) fn start(output_path: PathBuf) -> Result { let running = Arc::new(AtomicBool::new(true)); let died = Arc::new(AtomicBool::new(false)); let running_for_thread = running.clone(); @@ -108,12 +108,12 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> { false } else if w_format_tag == WAVE_FORMAT_EXTENSIBLE { // SAFETY: When wFormatTag is WAVE_FORMAT_EXTENSIBLE, the struct is actually WAVEFORMATEXTENSIBLE. - let ext = unsafe { &*(fmt as *const WAVEFORMATEX as *const WAVEFORMATEXTENSIBLE) }; + let ext = unsafe { &*std::ptr::from_ref::(fmt).cast::() }; // SAFETY: WAVEFORMATEXTENSIBLE contains repr(packed) fields; read_unaligned is required. let sub_fmt = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(ext.SubFormat)) }; sub_fmt == windows::core::GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71) } else { - bail!("unsupported WAVEFORMATEX format tag: {}", w_format_tag); + bail!("unsupported WAVEFORMATEX format tag: {w_format_tag}"); }; Ok((n_samples_per_sec, n_channels, w_bits_per_sample, is_float)) @@ -175,7 +175,7 @@ fn capture_thread( // SAFETY: Freeing the format pointer returned by GetMixFormat. unsafe { - CoTaskMemFree(Some(mix_format_ptr as *mut std::ffi::c_void)); + CoTaskMemFree(Some(mix_format_ptr.cast::())); } // SAFETY: Standard WASAPI pattern to get the capture client from the audio client. @@ -269,9 +269,9 @@ fn write_next_packet( unsafe { capture_client .GetBuffer( - &mut data_ptr, - &mut num_frames_available, - &mut flags, + &raw mut data_ptr, + &raw mut num_frames_available, + &raw mut flags, None, None, ) @@ -292,7 +292,7 @@ fn write_next_packet( } else if is_float { let num_bytes = samples * (bits_per_sample as usize / 8); // SAFETY: data_ptr from GetBuffer is valid for num_bytes. - let slice = unsafe { std::slice::from_raw_parts(data_ptr as *const u8, num_bytes) }; + let slice = unsafe { std::slice::from_raw_parts(data_ptr.cast_const(), num_bytes) }; writer.write_all(slice).context("writing audio data")?; } else { match bits_per_sample { diff --git a/src-tauri/src/bootstrap.rs b/src-tauri/src/bootstrap.rs index fdcc141..c39a013 100644 --- a/src-tauri/src/bootstrap.rs +++ b/src-tauri/src/bootstrap.rs @@ -9,20 +9,20 @@ use sha2::{Digest, Sha256}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] -pub enum FfmpegStatus { +pub(crate) enum FfmpegStatus { Ready, Missing, } -pub fn bin_dir(app_dir: &Path) -> PathBuf { +pub(crate) fn bin_dir(app_dir: &Path) -> PathBuf { app_dir.join("bin") } -pub fn ffmpeg_path(app_dir: &Path) -> PathBuf { +pub(crate) fn ffmpeg_path(app_dir: &Path) -> PathBuf { bin_dir(app_dir).join("ffmpeg.exe") } -pub fn check(app_dir: &Path) -> FfmpegStatus { +pub(crate) fn check(app_dir: &Path) -> FfmpegStatus { if ffmpeg_path(app_dir).is_file() { FfmpegStatus::Ready } else { @@ -70,7 +70,7 @@ struct GithubAsset { browser_download_url: String, } -pub async fn download(app_dir: &Path, mut on_progress: F) -> Result<()> +pub(crate) async fn download(app_dir: &Path, mut on_progress: F) -> Result<()> where F: FnMut(u64, Option) + Send, { @@ -143,7 +143,7 @@ where download_plain(&client, &asset.browser_download_url, &archive_path, on_progress) .await .with_context(|| format!("downloading {}", asset.browser_download_url))?; - }; + } let result = match source.kind { ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest), @@ -153,7 +153,7 @@ where result } -/// Fetch and parse a SHA-256 checksums file from GyanD. +/// Fetch and parse a SHA-256 checksums file from `GyanD`. /// The file contains a line like: /// abc123def456... ffmpeg-8.1.1-full_build.7z async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> { @@ -200,7 +200,7 @@ where { let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); - let mut file = std::fs::File::create(dest).context("creating archive temp file")?; + let mut file = File::create(dest).context("creating archive temp file")?; let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); while let Some(chunk) = stream.next().await { @@ -253,7 +253,7 @@ where let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); let mut hasher = Sha256::new(); - let mut file = std::fs::File::create(dest).context("creating archive temp file")?; + let mut file = File::create(dest).context("creating archive temp file")?; let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); while let Some(chunk) = stream.next().await { @@ -266,7 +266,7 @@ where file.flush()?; let got: [u8; 32] = hasher.finalize().into(); if &got != expected { - drop(std::fs::remove_file(dest)); + drop(fs::remove_file(dest)); bail!( "sha256 mismatch: expected {} got {}", hex::encode(expected), @@ -284,8 +284,7 @@ fn is_ffmpeg_entry(name: &str) -> bool { normalized .rsplit('/') .next() - .map(|leaf| leaf.eq_ignore_ascii_case("ffmpeg.exe")) - .unwrap_or(false) + .is_some_and(|leaf| leaf.eq_ignore_ascii_case("ffmpeg.exe")) } fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> { @@ -297,7 +296,7 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> { drop(fs::remove_dir_all(&scratch)); fs::create_dir_all(&scratch).context("create 7z scratch dir")?; - let file = std::fs::File::open(archive_path).context("opening 7z archive")?; + let file = File::open(archive_path).context("opening 7z archive")?; let extract_result = sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true)) .map_err(|e| anyhow!("7z extraction failed: {e}")); @@ -330,7 +329,7 @@ fn find_ffmpeg_in(dir: &Path) -> Option { } fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { - let file = std::fs::File::open(archive_path).context("opening zip archive")?; + let file = File::open(archive_path).context("opening zip archive")?; let mut zip = zip::ZipArchive::new(file).context("open zip archive")?; for i in 0..zip.len() { let mut entry = zip.by_index(i)?; diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index d6fd376..166724c 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -40,14 +40,14 @@ const FULLSCREEN_VS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/fullscree const TONEMAP_PS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/tonemap_ps.cso")); /// Hard ceiling for the Full quality mode so a 4K recording can't balloon to -/// 8K on exotic hardware. Auto mode caps at AUTO_ENCODE_WIDTH instead. +/// 8K on exotic hardware. Auto mode caps at `AUTO_ENCODE_WIDTH` instead. const MAX_ENCODE_WIDTH: u32 = 3840; const AUTO_ENCODE_WIDTH: u32 = 1920; const FALLBACK_REFRESH_HZ: u32 = 60; /// Returns the cap to apply to the encode width, or None for native res. /// Auto keeps the historic 1920 cap so nothing changes for existing users; -/// Full records at native res up to MAX_ENCODE_WIDTH (3840). +/// Full records at native res up to `MAX_ENCODE_WIDTH` (3840). fn encode_width_limit(quality: CaptureQuality) -> Option { match quality { CaptureQuality::Auto => Some(AUTO_ENCODE_WIDTH), @@ -56,7 +56,7 @@ fn encode_width_limit(quality: CaptureQuality) -> Option { } #[derive(Debug, Clone)] -pub struct CaptureSetup { +pub(crate) struct CaptureSetup { pub output_path: PathBuf, pub ffmpeg_path: PathBuf, pub width: u32, @@ -67,7 +67,7 @@ pub struct CaptureSetup { pub frame_counter: Arc, } -pub struct CaptureHandler { +pub(crate) struct CaptureHandler { stdin: Option, child: Option, width: u32, @@ -100,7 +100,7 @@ impl TonemapPipeline { // Vertex shader: fullscreen-triangle pass-through (no vertex buffer). let mut vs = None; unsafe { - device.CreateVertexShader(FULLSCREEN_VS, None, Some(&mut vs))?; + device.CreateVertexShader(FULLSCREEN_VS, None, Some(&raw mut vs))?; } let vs = vs.ok_or_else(|| anyhow!("CreateVertexShader returned null"))?; @@ -131,7 +131,7 @@ impl TonemapPipeline { device.CreateInputLayout( &input_elements, FULLSCREEN_VS, - Some(&mut input_layout), + Some(&raw mut input_layout), )?; } let input_layout = input_layout.ok_or_else(|| anyhow!("CreateInputLayout returned null"))?; @@ -146,7 +146,7 @@ impl TonemapPipeline { -1.0, 3.0, 0.0, -1.0, // top-left (off-screen) ]; let vb_desc = D3D11_BUFFER_DESC { - ByteWidth: std::mem::size_of_val(&verts) as u32, + ByteWidth: size_of_val(&verts) as u32, Usage: D3D11_USAGE_IMMUTABLE, BindFlags: D3D11_BIND_VERTEX_BUFFER.0 as u32, CPUAccessFlags: 0, @@ -154,20 +154,20 @@ impl TonemapPipeline { StructureByteStride: 0, }; let vb_init = D3D11_SUBRESOURCE_DATA { - pSysMem: verts.as_ptr() as *const std::ffi::c_void, + pSysMem: verts.as_ptr().cast::(), SysMemPitch: 0, SysMemSlicePitch: 0, }; let mut vertex_buffer = None; unsafe { - device.CreateBuffer(&vb_desc, Some(&vb_init), Some(&mut vertex_buffer))?; + device.CreateBuffer(&raw const vb_desc, Some(&raw const vb_init), Some(&raw mut vertex_buffer))?; } let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?; // Pixel shader: Hable tonemap + bt709 OETF. let mut ps = None; unsafe { - device.CreatePixelShader(TONEMAP_PS, None, Some(&mut ps))?; + device.CreatePixelShader(TONEMAP_PS, None, Some(&raw mut ps))?; } let ps = ps.ok_or_else(|| anyhow!("CreatePixelShader returned null"))?; @@ -186,7 +186,7 @@ impl TonemapPipeline { }; let mut sampler = None; unsafe { - device.CreateSamplerState(&sampler_desc, Some(&mut sampler))?; + device.CreateSamplerState(&raw const sampler_desc, Some(&raw mut sampler))?; } let sampler = sampler.ok_or_else(|| anyhow!("CreateSamplerState returned null"))?; @@ -208,7 +208,7 @@ impl TonemapPipeline { }; let mut rasterizer = None; unsafe { - device.CreateRasterizerState(&rasterizer_desc, Some(&mut rasterizer))?; + device.CreateRasterizerState(&raw const rasterizer_desc, Some(&raw mut rasterizer))?; } let rasterizer = rasterizer.ok_or_else(|| anyhow!("CreateRasterizerState returned null"))?; @@ -228,7 +228,7 @@ impl TonemapPipeline { }; let mut render_target = None; unsafe { - device.CreateTexture2D(&rt_desc, None, Some(&mut render_target))?; + device.CreateTexture2D(&raw const rt_desc, None, Some(&raw mut render_target))?; } let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?; @@ -241,7 +241,7 @@ impl TonemapPipeline { }; let mut rtv = None; unsafe { - device.CreateRenderTargetView(&render_target, Some(&view_desc), Some(&mut rtv))?; + device.CreateRenderTargetView(&render_target, Some(&raw const view_desc), Some(&raw mut rtv))?; } let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?; @@ -260,7 +260,7 @@ impl TonemapPipeline { }; let mut staging = None; unsafe { - device.CreateTexture2D(&staging_desc, None, Some(&mut staging))?; + device.CreateTexture2D(&raw const staging_desc, None, Some(&raw mut staging))?; } let staging = staging.ok_or_else(|| anyhow!("CreateTexture2D staging returned null"))?; @@ -290,7 +290,7 @@ impl TonemapPipeline { out: &mut dyn Write, ) -> Result<()> { let mut desc = D3D11_TEXTURE2D_DESC::default(); - unsafe { src.GetDesc(&mut desc) }; + unsafe { src.GetDesc(&raw mut desc) }; if desc.Width != self.width || desc.Height != self.height { // Resize - rebuild the RT/staging at the new dimensions. tracing::info!( @@ -313,7 +313,7 @@ impl TonemapPipeline { }, }; let mut srv: Option = None; - device.CreateShaderResourceView(src, Some(&srv_desc), Some(&mut srv))?; + device.CreateShaderResourceView(src, Some(&raw const srv_desc), Some(&raw mut srv))?; let srv = srv.ok_or_else(|| anyhow!("CreateShaderResourceView returned null"))?; // Canonical bind sequence: IA -> shaders -> resources -> output @@ -357,7 +357,7 @@ impl TonemapPipeline { // Copy to staging and read back. context.CopyResource(&self.staging, &self.render_target); let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); - context.Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?; + context.Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&raw mut mapped))?; let row_bytes = self.width * 4; let src_slice = std::slice::from_raw_parts( mapped.pData as *const u8, @@ -397,11 +397,11 @@ impl GraphicsCaptureApiHandler for CaptureHandler { let y = c.y.max(0); let w = c.width.min(setup.width.saturating_sub(x.cast_unsigned())); let h = c.height.min(setup.height.saturating_sub(y.cast_unsigned())); - filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y)); + filter_parts.push(format!("crop={w}:{h}:{x}:{y}")); } if let Some(limit) = setup.encode_width_limit { if setup.width > limit { - filter_parts.push(format!("scale={}:-2", limit)); + filter_parts.push(format!("scale={limit}:-2")); } else { filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string()); } @@ -512,7 +512,7 @@ pub struct CaptureSession { control: CaptureControl, } -pub fn primary_monitor_dims() -> Result<(u32, u32)> { +pub(crate) fn primary_monitor_dims() -> Result<(u32, u32)> { let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?; let w = monitor .width() @@ -566,7 +566,7 @@ fn monitor_at_point(x: i32, y: i32) -> Result { Ok(Monitor::from_raw_hmonitor(hmonitor.0)) } -pub fn start( +pub(crate) fn start( output_path: PathBuf, ffmpeg_path: PathBuf, capture_cursor: bool, @@ -693,7 +693,7 @@ impl CaptureSession { /// Idempotent: if `input` has already been consumed (e.g. a previous /// pause/resume cycle ran this to completion and removed it), and /// `output` exists, returns Ok without re-running ffmpeg. -pub fn fix_intermediate_fps( +pub(crate) fn fix_intermediate_fps( ffmpeg: &std::path::Path, input: &std::path::Path, output: &std::path::Path, @@ -740,7 +740,7 @@ pub fn fix_intermediate_fps( .arg("-y") .arg("-hide_banner") .args(["-loglevel", "error"]) - .args(["-itsscale", &format!("{:.6}", pts_scale)]) + .args(["-itsscale", &format!("{pts_scale:.6}")]) .args(["-i", &input.to_string_lossy()]) .args(["-c", "copy"]) .arg(output) @@ -761,7 +761,7 @@ pub fn fix_intermediate_fps( .arg("-hide_banner") .args(["-loglevel", "error"]) .args(["-i", &input.to_string_lossy()]) - .args(["-vf", &format!("setpts=PTS*{:.4}", pts_scale)]) + .args(["-vf", &format!("setpts=PTS*{pts_scale:.4}")]) .args(["-c:v", "libx264"]) .args(["-preset", "veryfast"]) .args(["-crf", "18"]) diff --git a/src-tauri/src/clicks.rs b/src-tauri/src/clicks.rs index 749b117..3a612c9 100644 --- a/src-tauri/src/clicks.rs +++ b/src-tauri/src/clicks.rs @@ -26,7 +26,7 @@ pub struct ClickRecorder { clicks: Arc>>, } -pub fn start() -> ClickRecorder { +pub(crate) fn start() -> ClickRecorder { let running = Arc::new(AtomicBool::new(true)); let clicks: Arc>> = Arc::new(Mutex::new(Vec::new())); let running_clone = running.clone(); @@ -56,7 +56,7 @@ pub fn start() -> ClickRecorder { let pressed = (state.cast_unsigned() & 0x8000) != 0; if pressed && !last_pressed[i] { let mut pt = POINT::default(); - if unsafe { GetCursorPos(&mut pt) }.is_ok() { + if unsafe { GetCursorPos(&raw mut pt) }.is_ok() { let click = Click { time_secs: start.elapsed().as_secs_f64(), x: pt.x, diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index d57752e..6755c31 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -169,8 +169,7 @@ impl Config { // timestamped name collides for some reason. let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); + .map_or(0, |d| d.as_secs()); let stem = path .file_stem() .and_then(|s| s.to_str()) @@ -211,7 +210,7 @@ impl Config { } } -pub fn config_path(app_dir: &Path) -> PathBuf { +pub(crate) fn config_path(app_dir: &Path) -> PathBuf { app_dir.join("config.toml") } @@ -225,8 +224,7 @@ fn sweep_stale_backups(config_path: &Path) { let Some(dir) = config_path.parent() else { return }; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); + .map_or(0, |d| d.as_secs()); let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { let name = entry.file_name(); diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 197d1ff..6730fce 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -19,17 +19,17 @@ const AUDIO_BITRATE_KBPS: u64 = 192; /// Progress update sent during encoding. /// pass: 1-based pass number (1 or 2 for two-pass video, 1 for GIF). -/// total_passes: total number of passes. +/// `total_passes`: total number of passes. /// percent: 0.0 to 100.0. #[derive(Debug, Clone, Copy, serde::Serialize)] -pub struct EncodeProgress { +pub(crate) struct EncodeProgress { pub pass: u8, pub total_passes: u8, pub percent: f64, } #[derive(Debug, Clone)] -pub struct TranscodeRequest { +pub(crate) struct TranscodeRequest { pub input: PathBuf, pub output: PathBuf, pub format: Format, @@ -151,7 +151,7 @@ fn crop_filter(crop: Option) -> Option { }) } -pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { +pub(crate) fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { if req.duration_secs <= 0.01 { bail!("clip duration is essentially zero - nothing to encode"); } @@ -284,7 +284,7 @@ fn webm_video_codec(c: WebmCodec) -> &'static str { /// codecs (H265, AV1) are reported because those are the ones users pick to /// save size and only learn at minute 5 that their build lacks them. #[derive(Debug, Clone, serde::Serialize)] -pub struct CodecAvailability { +pub(crate) struct CodecAvailability { pub h264: bool, pub h265: bool, pub vp9: bool, @@ -294,12 +294,12 @@ pub struct CodecAvailability { impl CodecAvailability { /// Returns all-true when ffmpeg is not installed yet (the bootstrap screen /// is still up). Settings will re-query after the user installs ffmpeg. - pub fn all_unknown() -> Self { + pub(crate) fn all_unknown() -> Self { Self { h264: true, h265: true, vp9: true, av1: true } } } -pub fn codec_availability(ffmpeg: &Path) -> CodecAvailability { +pub(crate) fn codec_availability(ffmpeg: &Path) -> CodecAvailability { let encoders = match list_encoders(ffmpeg) { Ok(set) => set, Err(_) => return CodecAvailability::all_unknown(), @@ -598,8 +598,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { ); let actual = std::fs::metadata(&req.output) - .map(|m| m.len()) - .unwrap_or(0); + .map_or(0, |m| m.len()); if actual == 0 { bail!("gif output is empty"); @@ -672,7 +671,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { } // All retries exhausted - warn if still over target - let final_size = std::fs::metadata(&req.output).map(|m| m.len()).unwrap_or(0); + let final_size = std::fs::metadata(&req.output).map_or(0, |m| m.len()); if final_size > req.target_bytes { tracing::warn!( "gif encode: could not meet target size after {} attempts. Final: {} bytes (target: {})", @@ -754,7 +753,7 @@ fn gif_rgb_scale_filter(width: u32) -> String { } #[derive(Debug, Clone)] -pub struct GifBudgetInput { +pub(crate) struct GifBudgetInput { pub gif_colors: u16, pub target_bytes: u64, pub fps: u32, @@ -762,7 +761,7 @@ pub struct GifBudgetInput { pub gif_budget_mode: GifBudgetMode, } -pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) { +pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) { let aspect = aspect_ratio(clip_width, clip_height); // GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors. // Real compression varies 3-5x depending on content (solid colors compress much better @@ -814,7 +813,7 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> } } -pub fn aspect_ratio(width: u32, height: u32) -> f64 { +pub(crate) fn aspect_ratio(width: u32, height: u32) -> f64 { if height > 0 { f64::from(width) / f64::from(height) } else { @@ -822,7 +821,7 @@ pub fn aspect_ratio(width: u32, height: u32) -> f64 { } } -pub fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u32 { +pub(crate) fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u32 { let aspect = aspect_ratio(clip_width, clip_height); if width == 0 { 0 @@ -831,7 +830,7 @@ pub fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u3 } } -pub fn render_preview( +pub(crate) fn render_preview( ffmpeg: &Path, input: &Path, out_path: &Path, @@ -841,7 +840,7 @@ pub fn render_preview( if let Some(parent) = out_path.parent() { std::fs::create_dir_all(parent).context("creating preview parent")?; } - let scale_filter = format!("scale={}:-2", target_width); + let scale_filter = format!("scale={target_width}:-2"); let mut cmd = Command::new(ffmpeg); cmd.arg("-y") .arg("-hide_banner") @@ -856,7 +855,7 @@ pub fn render_preview( /// Render a GIF preview with actual palette and dithering applied. /// Generates a palette from the full clip, then applies it to a single frame. -pub fn render_gif_preview( +pub(crate) fn render_gif_preview( ffmpeg: &Path, input: &Path, out_path: &Path, @@ -923,8 +922,7 @@ pub fn render_gif_preview( /// actually affect palettegen output. Same inputs -> same palette. fn palette_cache_key(gif_colors: u16, target_width: u32, sample_start: f64, sample_dur: f64) -> String { format!( - "c{gif_colors}-w{target_width}-s{:.3}-d{:.3}", - sample_start, sample_dur + "c{gif_colors}-w{target_width}-s{sample_start:.3}-d{sample_dur:.3}" ) } @@ -941,7 +939,7 @@ fn clean_stale_palettes(dir: &Path) { } } -pub fn extract_thumbnails( +pub(crate) fn extract_thumbnails( ffmpeg: &Path, input: &Path, out_dir: &Path, @@ -957,9 +955,7 @@ pub fn extract_thumbnails( .map(|c| format!("{c},")) .unwrap_or_default(); let filter = format!( - "{prefix}fps={fps},scale=120:-1:flags=lanczos", - prefix = crop_prefix, - fps = fps + "{crop_prefix}fps={fps},scale=120:-1:flags=lanczos" ); let pattern = out_dir.join("thumb-%05d.png"); @@ -979,15 +975,14 @@ pub fn extract_thumbnails( p.extension().and_then(|s| s.to_str()) == Some("png") && p.file_name() .and_then(|s| s.to_str()) - .map(|s| s.starts_with("thumb-")) - .unwrap_or(false) + .is_some_and(|s| s.starts_with("thumb-")) }) .collect(); paths.sort(); Ok(paths) } -pub fn mux_with_audio( +pub(crate) fn mux_with_audio( ffmpeg: &Path, video: &Path, audio_pcm: &Path, @@ -1016,7 +1011,7 @@ pub fn mux_with_audio( run(&mut cmd, "mux") } -pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { +pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { use std::io::Write; if segments.is_empty() { bail!("no audio segments to concatenate"); @@ -1038,7 +1033,7 @@ impl Drop for TempFileGuard { fn drop(&mut self) { drop(std::fs::remove_file(&self.0)); } } -pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> { +pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> { if segments.is_empty() { bail!("no segments to concatenate"); } @@ -1085,7 +1080,7 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> { } /// Run an ffmpeg command with progress monitoring via `-progress pipe:1`. -/// progress_tx, if provided, receives (pass, total_passes, percent) updates +/// `progress_tx`, if provided, receives (pass, `total_passes`, percent) updates /// driven by ffmpeg's stable key=value output (`out_time_us`) rather than /// fragile stderr line parsing. fn run_with_progress( @@ -1236,7 +1231,7 @@ fn run_impl( }); } Ok(None) => { - std::thread::sleep(std::time::Duration::from_millis(20)); + thread::sleep(std::time::Duration::from_millis(20)); } Err(e) => bail!("waiting for ffmpeg: {e}"), } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7ad8388..2c2d282 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -51,8 +51,8 @@ pub struct AppState { pub overlay_aspect_ratio: Mutex>, /// (active flag, condvar) so the overlay click-through poll thread can park /// itself when no overlay is on screen instead of waking every 80ms. - /// show_overlay/hide_overlay flip the flag and notify. - pub overlay_poll_live: Arc<(std::sync::Mutex, std::sync::Condvar)>, + /// `show_overlay/hide_overlay` flip the flag and notify. + pub overlay_poll_live: Arc<(Mutex, std::sync::Condvar)>, } pub struct SessionState { @@ -310,11 +310,11 @@ pub struct StartCaptureRequest { } fn segment_path(app_dir: &Path, idx: usize) -> PathBuf { - temp_dir(app_dir).join(format!("segment-{:03}.mp4", idx)) + temp_dir(app_dir).join(format!("segment-{idx:03}.mp4")) } fn audio_segment_path(app_dir: &Path, idx: usize) -> PathBuf { - temp_dir(app_dir).join(format!("audio-{:03}.pcm", idx)) + temp_dir(app_dir).join(format!("audio-{idx:03}.pcm")) } fn clear_temp_segments(app_dir: &Path) { @@ -449,7 +449,7 @@ fn start_click_recorder(enabled: bool) -> Option { /// output switched, WASAPI invalidated the client). The capture thread sets /// its `died` flag on such an exit; this poller emits `audio-failed` so the /// existing retry UI in Main.svelte can recover mid-record instead of the -/// session slot silently holding a dead thread until stop_capture. +/// session slot silently holding a dead thread until `stop_capture`. fn watch_audio_death(app: AppHandle, died: Arc) { std::thread::spawn(move || { use std::time::Duration; @@ -531,8 +531,7 @@ fn start_capture( let (a_sr, a_ch) = audio_session .as_ref() - .map(|s| (Some(s.sample_rate), Some(s.channels))) - .unwrap_or((None, None)); + .map_or((None, None), |s| (Some(s.sample_rate), Some(s.channels))); let session_state = SessionState { segments: Vec::new(), @@ -571,7 +570,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { .take() .ok_or_else(|| "no capture in progress".to_string())?; let elapsed = session.started_at.elapsed().as_secs_f64(); - let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed); + let frames = session.frame_counter.load(Ordering::Relaxed); let pipe_fps = session.pipe_fps; let raw_path = session.stop().map_err(|e| format!("{e:#}"))?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); @@ -586,7 +585,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { let new_clicks: Vec = lock(&state.click_recorder) .take() - .map(|r| r.stop()) + .map(clicks::ClickRecorder::stop) .unwrap_or_default(); let mut ss = lock(&state.session); @@ -711,7 +710,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result) -> Result GifEstimate { GifEstimate { width: w, fps, height, dims_label } } -/// Return estimates for a grid of target_bytes values so the frontend can +/// Return estimates for a grid of `target_bytes` values so the frontend can /// interpolate on slider drag without an IPC per debounce tick. The grid is /// geometric from 100KB to 200MB. #[tauri::command] @@ -1125,7 +1124,7 @@ fn cleanup_temp_on_exit(app: &AppHandle) { fn start_overlay_clickthrough_poll( app: AppHandle, shutdown: Arc, - live: Arc<(std::sync::Mutex, std::sync::Condvar)>, + live: Arc<(Mutex, std::sync::Condvar)>, ) { use std::time::Duration; use windows::Win32::Foundation::{HWND, POINT}; @@ -1141,11 +1140,11 @@ fn start_overlay_clickthrough_poll( // flips the flag and notifies. { let (lock, cvar) = &*live; - let mut active = lock.lock().unwrap_or_else(|e| e.into_inner()); + let mut active = lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner); while !*active && !shutdown.load(Ordering::Relaxed) { let (g, _timeout) = cvar .wait_timeout(active, Duration::from_secs(1)) - .unwrap_or_else(|e| e.into_inner()); + .unwrap_or_else(std::sync::PoisonError::into_inner); active = g; } } @@ -1167,7 +1166,7 @@ fn start_overlay_clickthrough_poll( } let mut pt = POINT::default(); - if unsafe { GetCursorPos(&mut pt) }.is_err() { + if unsafe { GetCursorPos(&raw mut pt) }.is_err() { continue; } let raw = match overlay.hwnd() { @@ -1180,7 +1179,7 @@ fn start_overlay_clickthrough_poll( None => continue, }; - let dpi = unsafe { GetDpiForWindow(HWND(raw.0 as *mut std::ffi::c_void)) }; + let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::())) }; let scale = if dpi > 0 { f64::from(dpi) / 96.0 } else { 1.0 }; let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; @@ -1210,7 +1209,7 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(), SetWindowDisplayAffinity, WDA_EXCLUDEFROMCAPTURE, }; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; - let hwnd = HWND(raw.0 as *mut std::ffi::c_void); + let hwnd = HWND(raw.0.cast::()); unsafe { SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) .map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?; @@ -1230,7 +1229,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { { let st = app.state::(); let (lock, cvar) = &*st.overlay_poll_live; - *lock.lock().unwrap_or_else(|e| e.into_inner()) = true; + *lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; cvar.notify_one(); } @@ -1242,18 +1241,18 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER}; if let Ok(raw) = win.hwnd() { if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) { - let center = POINT { x: (vl + vr) / 2, y: (vt + vb) / 2 }; + let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb) }; let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) }; if hmon.0.is_null() { - let hwnd = HWND(raw.0 as *mut std::ffi::c_void); + let hwnd = HWND(raw.0.cast::()); let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) }; - let mut mi = MONITORINFO { cbSize: std::mem::size_of::() as u32, ..Default::default() }; - if unsafe { GetMonitorInfoW(primary, &mut mi) }.as_bool() { + let mut mi = MONITORINFO { cbSize: size_of::() as u32, ..Default::default() }; + if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() { let work = mi.rcWork; let w = vr - vl; let h = vb - vt; - let cx = (work.left + work.right) / 2 - w / 2; - let cy = (work.top + work.bottom) / 2 - h / 2; + let cx = i32::midpoint(work.left, work.right) - w / 2; + let cy = i32::midpoint(work.top, work.bottom) - h / 2; drop( unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) }, ); @@ -1275,7 +1274,7 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> { { let st = app.state::(); let (lock, cvar) = &*st.overlay_poll_live; - *lock.lock().unwrap_or_else(|e| e.into_inner()) = false; + *lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false; cvar.notify_one(); } win.hide().map_err(|e| format!("hiding overlay: {e:#}")) @@ -1349,7 +1348,7 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result< use windows::Win32::Foundation::HWND; use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER}; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; - let hwnd = HWND(raw.0 as *mut std::ffi::c_void); + let hwnd = HWND(raw.0.cast::()); // Compute outer size including borders let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; @@ -1407,16 +1406,16 @@ fn open_window_picker( use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; - let hwnd = HWND(h.0 as *mut std::ffi::c_void); + let hwnd = HWND(h.0.cast::()); let mut gr = RECT::default(); - drop(unsafe { GetWindowRect(hwnd, &mut gr) }); + drop(unsafe { GetWindowRect(hwnd, &raw mut gr) }); let mut dr = RECT::default(); drop(unsafe { DwmGetWindowAttribute( hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, - &raw mut dr as *mut RECT as *mut std::ffi::c_void, - std::mem::size_of::() as u32, + (&raw mut dr).cast::().cast::(), + size_of::() as u32, ) }); tracing::debug!( @@ -1460,8 +1459,8 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> { DwmGetWindowAttribute( hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, - &mut dwm as *mut RECT as *mut std::ffi::c_void, - std::mem::size_of::() as u32, + (&raw mut dwm).cast::(), + size_of::() as u32, ) } .is_ok() @@ -1471,7 +1470,7 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> { return Some((dwm.left, dwm.top, dwm.right, dwm.bottom)); } let mut outer = RECT::default(); - if unsafe { GetWindowRect(hwnd, &mut outer) }.is_ok() { + if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_ok() { Some((outer.left, outer.top, outer.right, outer.bottom)) } else { None @@ -1485,7 +1484,7 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) { let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void); let mut outer = RECT::default(); - if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() { + if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_err() { return (0, 0, 0, 0); } let mut dwm = RECT::default(); @@ -1493,8 +1492,8 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) { DwmGetWindowAttribute( hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, - &mut dwm as *mut RECT as *mut std::ffi::c_void, - std::mem::size_of::() as u32, + (&raw mut dwm).cast::(), + size_of::() as u32, ) }; if r.is_err() || dwm.right <= dwm.left || dwm.bottom <= dwm.top { @@ -1525,8 +1524,8 @@ fn scale_factor_at_point(x: i32, y: i32) -> f64 { GetDpiForMonitor( hmonitor, MONITOR_DPI_TYPE(0), // MdtEffectiveDpi - &mut dpi_x, - &mut dpi_y, + &raw mut dpi_x, + &raw mut dpi_y, ) }; if hr.is_ok() && dpi_x > 0 { @@ -1567,8 +1566,7 @@ fn set_overlay_to_window( // visible content sits inside the DWM inset). let (li, ti, ri, bi) = win .hwnd() - .map(|h| dwm_insets(h.0 as isize)) - .unwrap_or((0, 0, 0, 0)); + .map_or((0, 0, 0, 0), |h| dwm_insets(h.0 as isize)); let outer_x = visible_left - li; let outer_y = visible_top - ti; @@ -1582,7 +1580,7 @@ fn set_overlay_to_window( use windows::Win32::UI::WindowsAndMessaging::{ SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER, }; - let hwnd = HWND(raw.0 as *mut std::ffi::c_void); + let hwnd = HWND(raw.0.cast::()); unsafe { SetWindowPos( hwnd, @@ -1639,9 +1637,7 @@ fn reveal_in_explorer(path: String) -> Result<(), String> { let canonical = std::fs::canonicalize(&path).ok(); let normalized = canonical - .as_ref() - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_else(|| path.clone()); + .as_ref().map_or_else(|| path.clone(), |p| p.to_string_lossy().into_owned()); let stripped = normalized .strip_prefix(r"\\?\") .unwrap_or(&normalized) @@ -1729,7 +1725,7 @@ fn diagnostics_info(state: State<'_, AppState>) -> DiagnosticsInfo { String::from_utf8_lossy(&o.stdout) .lines() .next() - .map(|s| s.to_string()) + .map(ToString::to_string) }) .unwrap_or_else(|| "ffmpeg present (version unreadable)".to_string()) } else { @@ -1884,7 +1880,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque // Run the (potentially minutes-long) ffmpeg encode on a blocking thread so // we don't hold a Tauri async worker for the whole duration. - let ffmpeg_arc = std::sync::Arc::new(ffmpeg); + let ffmpeg_arc = Arc::new(ffmpeg); let ffmpeg_for_task = ffmpeg_arc.clone(); let result = tauri::async_runtime::spawn_blocking(move || { encode::transcode(&ffmpeg_for_task, &req_with_progress) @@ -1894,8 +1890,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque result.map_err(|e| format!("{e:#}"))?; let size_bytes = std::fs::metadata(&out_path) - .map(|m| m.len()) - .unwrap_or(0); + .map_or(0, |m| m.len()); Ok(ExportResult { met_target: size_bytes <= request.target_bytes, target_bytes: request.target_bytes, @@ -1961,7 +1956,7 @@ pub fn run() { overlay_poll_shutdown: Arc::new(AtomicBool::new(false)), export_cancel: Arc::new(AtomicBool::new(false)), overlay_aspect_ratio: Mutex::new(None), - overlay_poll_live: Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())), + overlay_poll_live: Arc::new((Mutex::new(false), std::sync::Condvar::new())), }; let app = tauri::Builder::default() @@ -2034,7 +2029,7 @@ pub fn run() { let app_dir = app.state::().app_dir.clone(); tauri::async_runtime::spawn(async move { // Skip the network call if we checked within the last 6 hours. - if !updates::should_check(&app_dir, std::time::Duration::from_secs(6 * 3600)) { + if !updates::should_check(&app_dir, std::time::Duration::from_hours(6)) { tracing::debug!("update check skipped (TTL not elapsed)"); return; } diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 121c41b..3424207 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -8,7 +8,7 @@ const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest"; #[derive(Debug, Clone, Serialize)] -pub struct UpdateInfo { +pub(crate) struct UpdateInfo { pub version: String, pub current_version: String, pub release_url: String, @@ -31,7 +31,7 @@ struct GiteaAsset { browser_download_url: String, } -pub async fn check_for_update() -> Result> { +pub(crate) async fn check_for_update() -> Result> { let client = reqwest::Client::builder() .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; @@ -63,7 +63,7 @@ pub async fn check_for_update() -> Result> { } } -pub async fn download_to(url: &str, dest: &Path, mut on_progress: F) -> Result<()> +pub(crate) async fn download_to(url: &str, dest: &Path, mut on_progress: F) -> Result<()> where F: FnMut(u64, Option) + Send, { @@ -89,7 +89,7 @@ where Ok(()) } -pub fn pending_update_path(app_dir: &Path) -> PathBuf { +pub(crate) fn pending_update_path(app_dir: &Path) -> PathBuf { app_dir.join("ByteSize.new.exe") } @@ -99,7 +99,7 @@ fn last_check_path(app_dir: &Path) -> PathBuf { /// Returns true if the last successful update check happened more than `ttl` /// ago, or never. The stamp file's mtime is the source of truth. -pub fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { +pub(crate) fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { let path = last_check_path(app_dir); let Ok(meta) = std::fs::metadata(&path) else { return true; @@ -113,7 +113,7 @@ pub fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { elapsed > ttl } -pub fn stamp_check(app_dir: &Path) { +pub(crate) fn stamp_check(app_dir: &Path) { let path = last_check_path(app_dir); if let Some(parent) = path.parent() { drop(std::fs::create_dir_all(parent)); @@ -121,11 +121,11 @@ pub fn stamp_check(app_dir: &Path) { drop(std::fs::write(&path, b"")); } -pub fn has_pending_update(app_dir: &Path) -> bool { +pub(crate) fn has_pending_update(app_dir: &Path) -> bool { pending_update_path(app_dir).is_file() } -pub fn write_apply_script(app_dir: &Path) -> Result { +pub(crate) fn write_apply_script(app_dir: &Path) -> Result { let bat_path = app_dir.join("bytesize-apply-update.bat"); let exe_name = std::env::current_exe() .ok() @@ -135,21 +135,20 @@ pub fn write_apply_script(app_dir: &Path) -> Result { "@echo off\r\n\ timeout /t 3 /nobreak >nul\r\n\ :retry\r\n\ - del \"%~dp0{exe}\" 2>nul\r\n\ - if exist \"%~dp0{exe}\" (\r\n\ + del \"%~dp0{exe_name}\" 2>nul\r\n\ + if exist \"%~dp0{exe_name}\" (\r\n\ timeout /t 2 /nobreak >nul\r\n\ goto retry\r\n\ )\r\n\ - move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\ + move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe_name}\" >nul\r\n\ if errorlevel 1 (\r\n\ echo Failed to replace executable\r\n\ pause\r\n\ del \"%~f0\"\r\n\ exit /b 1\r\n\ )\r\n\ - start \"\" \"%~dp0{exe}\"\r\n\ - del \"%~f0\"\r\n", - exe = exe_name + start \"\" \"%~dp0{exe_name}\"\r\n\ + del \"%~f0\"\r\n" ); std::fs::write(&bat_path, body).context("writing apply script")?; Ok(bat_path) diff --git a/src-tauri/src/window_picker.rs b/src-tauri/src/window_picker.rs index 18e2d06..1189433 100644 --- a/src-tauri/src/window_picker.rs +++ b/src-tauri/src/window_picker.rs @@ -14,30 +14,30 @@ use windows::Win32::UI::WindowsAndMessaging::{ IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW, }; -unsafe fn visible_window_rect(hwnd: HWND) -> Option { +unsafe fn visible_window_rect(hwnd: HWND) -> Option { unsafe { let mut rect = RECT::default(); let r = DwmGetWindowAttribute( hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, - &mut rect as *mut RECT as *mut std::ffi::c_void, - std::mem::size_of::() as u32, + (&raw mut rect).cast::(), + size_of::() as u32, ); if r.is_ok() && rect.right > rect.left && rect.bottom > rect.top { return Some(rect); } let mut fallback = RECT::default(); - if GetWindowRect(hwnd, &mut fallback).is_ok() { + if GetWindowRect(hwnd, &raw mut fallback).is_ok() { Some(fallback) } else { None } -} +}} const VK_LBUTTON: i32 = 0x01; const VK_ESCAPE: i32 = 0x1B; #[derive(Serialize, Clone)] -pub struct Rect { +pub(crate) struct Rect { pub x: i32, pub y: i32, pub width: u32, @@ -46,7 +46,7 @@ pub struct Rect { pub struct PickerSession { running: Arc, - handle: Option>, + handle: Option>, } struct EnumCtx { @@ -68,16 +68,16 @@ const SHELL_CLASSES: &[&str] = &[ "Windows.UI.Core.CoreWindow", ]; -unsafe fn class_of(hwnd: HWND) -> String { +unsafe fn class_of(hwnd: HWND) -> String { unsafe { let mut buf = [0u16; 128]; let n = GetClassNameW(hwnd, &mut buf); if n <= 0 { return String::new(); } String::from_utf16_lossy(&buf[..n as usize]) -} +}} -unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { +unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { let ctx = &mut *(lparam.0 as *mut EnumCtx); if ctx.found.is_some() { return BOOL(1); @@ -118,7 +118,7 @@ unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { } ctx.found = Some((id, rect)); BOOL(0) -} +}} fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> { let mut ctx = EnumCtx { @@ -129,13 +129,13 @@ fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> { unsafe { drop(EnumWindows( Some(enum_at_point), - LPARAM(&raw mut ctx as *mut EnumCtx as isize), + LPARAM((&raw mut ctx).cast::() as isize), )); } ctx.found } -pub fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession { +pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession { let running = Arc::new(AtomicBool::new(true)); let running_clone = running.clone(); let handle = thread::spawn(move || { @@ -149,7 +149,7 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession { } let mut pt = POINT::default(); - if unsafe { GetCursorPos(&mut pt) }.is_err() { + if unsafe { GetCursorPos(&raw mut pt) }.is_err() { thread::sleep(Duration::from_millis(30)); continue; } diff --git a/src-tauri/src/windows_list.rs b/src-tauri/src/windows_list.rs index 6c6748c..0c78a33 100644 --- a/src-tauri/src/windows_list.rs +++ b/src-tauri/src/windows_list.rs @@ -8,7 +8,7 @@ use windows::Win32::UI::WindowsAndMessaging::{ const MIN_DIM: i32 = 80; #[derive(Debug, Clone, Serialize)] -pub struct WindowInfo { +pub(crate) struct WindowInfo { pub title: String, pub x: i32, pub y: i32, @@ -16,18 +16,18 @@ pub struct WindowInfo { pub height: u32, } -pub fn list_visible_windows() -> Vec { +pub(crate) fn list_visible_windows() -> Vec { let mut out: Vec = Vec::new(); unsafe { drop(EnumWindows( Some(enum_cb), - LPARAM(&raw mut out as *mut Vec as isize), + LPARAM((&raw mut out).cast::>() as isize), )); } out } -unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { +unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { if !IsWindowVisible(hwnd).as_bool() { return BOOL(1); } @@ -36,7 +36,7 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { } let mut rect = RECT::default(); - if GetWindowRect(hwnd, &mut rect).is_err() { + if GetWindowRect(hwnd, &raw mut rect).is_err() { return BOOL(1); } let w = rect.right - rect.left; @@ -68,4 +68,4 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { height: h.cast_unsigned(), }); BOOL(1) -} +}}