enforce stricter lints, drop discarded results properly

This commit is contained in:
2026-09-21 00:40:51 +03:00
parent 95d168d5d8
commit 1332600148
12 changed files with 204 additions and 171 deletions
+31
View File
@@ -6,6 +6,37 @@ authors = ["lashman <lashman@robotbrush.com>"]
edition = "2021" edition = "2021"
rust-version = "1.94" rust-version = "1.94"
# Lint policy. pedantic is on wholesale; from the restriction group only the
# lints that catch real defects are enabled, since that group is documented as
# cherry-pick-only and its members contradict each other (absolute_paths vs
# unused_qualifications, implicit_return vs semicolon_outside_block).
[lints.rust]
unreachable_pub = "warn"
unused_qualifications = "warn"
unsafe_op_in_unsafe_fn = "warn"
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
# Correctness-first selection from restriction.
undocumented_unsafe_blocks = "warn"
multiple_unsafe_ops_per_block = "warn"
indexing_slicing = "warn"
unwrap_used = "warn"
expect_used = "warn"
panic = "warn"
unwrap_in_result = "warn"
borrow_as_ptr = "warn"
ptr_as_ptr = "warn"
ref_as_ptr = "warn"
ptr_cast_constness = "warn"
as_pointer_underscore = "warn"
cast_ptr_alignment = "warn"
let_underscore_must_use = "warn"
let_underscore_untyped = "warn"
else_if_without_else = "warn"
exit = "warn"
[lib] [lib]
name = "bytesize_lib" name = "bytesize_lib"
crate-type = ["staticlib", "cdylib", "rlib"] crate-type = ["staticlib", "cdylib", "rlib"]
+3 -3
View File
@@ -39,18 +39,18 @@ fn compile_shaders() {
"cargo:warning=fxc failed for {entry}: {}", "cargo:warning=fxc failed for {entry}: {}",
String::from_utf8_lossy(&o.stderr) String::from_utf8_lossy(&o.stderr)
); );
let _ = std::fs::write(&dst, []); drop(std::fs::write(&dst, []));
} }
Err(e) => { Err(e) => {
println!("cargo:warning=could not run fxc for {entry}: {e}"); println!("cargo:warning=could not run fxc for {entry}: {e}");
let _ = std::fs::write(&dst, []); drop(std::fs::write(&dst, []));
} }
} }
} }
None => { None => {
// No SDK on the build machine - emit an empty .cso; capture.rs // No SDK on the build machine - emit an empty .cso; capture.rs
// detects the zero size and compiles the HLSL at runtime. // detects the zero size and compiles the HLSL at runtime.
let _ = std::fs::write(&dst, []); drop(std::fs::write(&dst, []));
} }
} }
} }
+4 -4
View File
@@ -175,7 +175,7 @@ fn capture_thread(
// SAFETY: Freeing the format pointer returned by GetMixFormat. // SAFETY: Freeing the format pointer returned by GetMixFormat.
unsafe { unsafe {
CoTaskMemFree(Some(mix_format_ptr as *mut _)); CoTaskMemFree(Some(mix_format_ptr as *mut std::ffi::c_void));
} }
// SAFETY: Standard WASAPI pattern to get the capture client from the audio client. // SAFETY: Standard WASAPI pattern to get the capture client from the audio client.
@@ -199,13 +199,13 @@ fn capture_thread(
let started_at = std::time::Instant::now(); let started_at = std::time::Instant::now();
// Notify parent that init succeeded. // Notify parent that init succeeded.
let _ = init_tx.send(Ok((sample_rate, channels, started_at))); drop(init_tx.send(Ok((sample_rate, channels, started_at))));
let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer); let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer);
// SAFETY: Stops the audio capture stream before tearing down. // SAFETY: Stops the audio capture stream before tearing down.
unsafe { unsafe {
let _ = client.Stop(); drop(client.Stop());
} }
// Drain any remaining packets that were buffered before Stop(). // Drain any remaining packets that were buffered before Stop().
@@ -301,7 +301,7 @@ fn write_next_packet(
let i16_slice = let i16_slice =
unsafe { std::slice::from_raw_parts(data_ptr as *const i16, samples) }; unsafe { std::slice::from_raw_parts(data_ptr as *const i16, samples) };
for &sample in i16_slice { for &sample in i16_slice {
let f = sample as f32 / 32768.0; let f = f32::from(sample) / 32768.0;
writer writer
.write_all(&f.to_le_bytes()) .write_all(&f.to_le_bytes())
.context("writing f32 sample")?; .context("writing f32 sample")?;
+4 -4
View File
@@ -149,7 +149,7 @@ where
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest), ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest),
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest), ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest),
}; };
let _ = fs::remove_file(&archive_path); drop(fs::remove_file(&archive_path));
result result
} }
@@ -266,7 +266,7 @@ where
file.flush()?; file.flush()?;
let got: [u8; 32] = hasher.finalize().into(); let got: [u8; 32] = hasher.finalize().into();
if &got != expected { if &got != expected {
let _ = std::fs::remove_file(dest); drop(std::fs::remove_file(dest));
bail!( bail!(
"sha256 mismatch: expected {} got {}", "sha256 mismatch: expected {} got {}",
hex::encode(expected), hex::encode(expected),
@@ -294,7 +294,7 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
.and_then(|p| p.parent()) .and_then(|p| p.parent())
.context("invalid dest path")?; .context("invalid dest path")?;
let scratch = app_dir.join("temp").join("ffmpeg-extract"); let scratch = app_dir.join("temp").join("ffmpeg-extract");
let _ = fs::remove_dir_all(&scratch); drop(fs::remove_dir_all(&scratch));
fs::create_dir_all(&scratch).context("create 7z scratch dir")?; fs::create_dir_all(&scratch).context("create 7z scratch dir")?;
let file = std::fs::File::open(archive_path).context("opening 7z archive")?; let file = std::fs::File::open(archive_path).context("opening 7z archive")?;
@@ -302,7 +302,7 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true)) sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true))
.map_err(|e| anyhow!("7z extraction failed: {e}")); .map_err(|e| anyhow!("7z extraction failed: {e}"));
let found = find_ffmpeg_in(&scratch); let found = find_ffmpeg_in(&scratch);
let _ = fs::remove_dir_all(&scratch); drop(fs::remove_dir_all(&scratch));
extract_result?; extract_result?;
let Some(src) = found else { let Some(src) = found else {
+19 -19
View File
@@ -154,13 +154,13 @@ impl TonemapPipeline {
StructureByteStride: 0, StructureByteStride: 0,
}; };
let vb_init = D3D11_SUBRESOURCE_DATA { let vb_init = D3D11_SUBRESOURCE_DATA {
pSysMem: verts.as_ptr() as *const _, pSysMem: verts.as_ptr() as *const std::ffi::c_void,
SysMemPitch: 0, SysMemPitch: 0,
SysMemSlicePitch: 0, SysMemSlicePitch: 0,
}; };
let mut vertex_buffer = None; let mut vertex_buffer = None;
unsafe { unsafe {
device.CreateBuffer(&vb_desc as *const _, Some(&vb_init as *const _), Some(&mut vertex_buffer))?; device.CreateBuffer(&vb_desc, Some(&vb_init), Some(&mut vertex_buffer))?;
} }
let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?; let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?;
@@ -349,8 +349,8 @@ impl TonemapPipeline {
context.RSSetScissorRects(Some(&[windows::Win32::Foundation::RECT { context.RSSetScissorRects(Some(&[windows::Win32::Foundation::RECT {
left: 0, left: 0,
top: 0, top: 0,
right: self.width as i32, right: self.width.cast_signed(),
bottom: self.height as i32, bottom: self.height.cast_signed(),
}])); }]));
context.Draw(3, 0); context.Draw(3, 0);
@@ -395,8 +395,8 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
if let Some(c) = setup.crop { if let Some(c) = setup.crop {
let x = c.x.max(0); let x = c.x.max(0);
let y = c.y.max(0); let y = c.y.max(0);
let w = c.width.min(setup.width.saturating_sub(x as u32)); let w = c.width.min(setup.width.saturating_sub(x.cast_unsigned()));
let h = c.height.min(setup.height.saturating_sub(y as u32)); 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 let Some(limit) = setup.encode_width_limit {
@@ -496,7 +496,7 @@ impl Drop for CaptureHandler {
fn drop(&mut self) { fn drop(&mut self) {
drop(self.stdin.take()); drop(self.stdin.take());
if let Some(mut child) = self.child.take() { if let Some(mut child) = self.child.take() {
let _ = child.wait(); drop(child.wait());
} }
} }
} }
@@ -578,8 +578,8 @@ pub fn start(
// Use the center of the capture region to determine which monitor to capture. // Use the center of the capture region to determine which monitor to capture.
// If the region spans monitors, we pick the one containing the center. // If the region spans monitors, we pick the one containing the center.
let monitor = if let Some(ref c) = crop { let monitor = if let Some(ref c) = crop {
let cx = c.x.saturating_add(c.width as i32 / 2); let cx = c.x.saturating_add(c.width.cast_signed() / 2);
let cy = c.y.saturating_add(c.height as i32 / 2); let cy = c.y.saturating_add(c.height.cast_signed() / 2);
tracing::info!("capture center=({cx}, {cy}), selecting monitor"); tracing::info!("capture center=({cx}, {cy}), selecting monitor");
monitor_at_point(cx, cy).unwrap_or_else(|_| { monitor_at_point(cx, cy).unwrap_or_else(|_| {
tracing::warn!("no monitor at ({cx}, {cy}), falling back to primary"); tracing::warn!("no monitor at ({cx}, {cy}), falling back to primary");
@@ -655,8 +655,8 @@ fn compute_output_dims(
) -> (u32, u32) { ) -> (u32, u32) {
let (raw_w, raw_h) = match crop { let (raw_w, raw_h) = match crop {
Some(c) => { Some(c) => {
let x = c.x.max(0) as u32; let x = c.x.max(0).cast_unsigned();
let y = c.y.max(0) as u32; let y = c.y.max(0).cast_unsigned();
( (
c.width.min(monitor_w.saturating_sub(x)), c.width.min(monitor_w.saturating_sub(x)),
c.height.min(monitor_h.saturating_sub(y)), c.height.min(monitor_h.saturating_sub(y)),
@@ -666,8 +666,8 @@ fn compute_output_dims(
}; };
let cap = width_limit.unwrap_or(u32::MAX); let cap = width_limit.unwrap_or(u32::MAX);
if raw_w > cap { if raw_w > cap {
let scale = cap as f64 / raw_w as f64; let scale = f64::from(cap) / f64::from(raw_w);
let nh = (raw_h as f64 * scale).round() as u32; let nh = (f64::from(raw_h) * scale).round() as u32;
(cap, (nh / 2) * 2) (cap, (nh / 2) * 2)
} else { } else {
((raw_w / 2) * 2, (raw_h / 2) * 2) ((raw_w / 2) * 2, (raw_h / 2) * 2)
@@ -676,7 +676,7 @@ fn compute_output_dims(
impl CaptureSession { impl CaptureSession {
pub fn stop(self) -> Result<PathBuf> { pub fn stop(self) -> Result<PathBuf> {
let _ = self.control.stop(); drop(self.control.stop());
let meta = std::fs::metadata(&self.output_path) let meta = std::fs::metadata(&self.output_path)
.with_context(|| format!("checking output file {}", self.output_path.display()))?; .with_context(|| format!("checking output file {}", self.output_path.display()))?;
if meta.len() == 0 { if meta.len() == 0 {
@@ -748,11 +748,11 @@ pub fn fix_intermediate_fps(
.context("stream-copy timestamp fix")?; .context("stream-copy timestamp fix")?;
if copy_status.success() && output.is_file() { if copy_status.success() && output.is_file() {
tracing::debug!("capture fix: stream copy with -itsscale succeeded, no re-encode"); tracing::debug!("capture fix: stream copy with -itsscale succeeded, no re-encode");
let _ = std::fs::remove_file(input); drop(std::fs::remove_file(input));
return Ok(()); return Ok(());
} }
tracing::warn!("capture fix: -itsscale copy failed, falling back to re-encode"); tracing::warn!("capture fix: -itsscale copy failed, falling back to re-encode");
let _ = std::fs::remove_file(output); drop(std::fs::remove_file(output));
// Fallback: re-encode with scaled PTS to fix timing. // Fallback: re-encode with scaled PTS to fix timing.
// CRF 18 is visually lossless; preset veryfast keeps stop/pause/resume snappy. // CRF 18 is visually lossless; preset veryfast keeps stop/pause/resume snappy.
@@ -774,10 +774,10 @@ pub fn fix_intermediate_fps(
.context("re-encoding with corrected timestamps")?; .context("re-encoding with corrected timestamps")?;
if status.success() { if status.success() {
let _ = std::fs::remove_file(input); drop(std::fs::remove_file(input));
} else { } else {
tracing::warn!("capture fix: re-encode failed, keeping original"); tracing::warn!("capture fix: re-encode failed, keeping original");
let _ = rename_or_copy(input, output); drop(rename_or_copy(input, output));
} }
Ok(()) Ok(())
} }
@@ -796,7 +796,7 @@ fn capture_timing(frame_count: u64, elapsed_secs: f64, pipe_fps: u32) -> Option<
return None; return None;
} }
let actual_fps = frame_count as f64 / elapsed_secs; let actual_fps = frame_count as f64 / elapsed_secs;
Some((actual_fps, pipe_fps as f64 / actual_fps)) Some((actual_fps, f64::from(pipe_fps) / actual_fps))
} }
#[cfg(test)] #[cfg(test)]
+2 -2
View File
@@ -53,7 +53,7 @@ pub fn start() -> ClickRecorder {
while running_clone.load(Ordering::Relaxed) { while running_clone.load(Ordering::Relaxed) {
for (i, &(vk, button)) in buttons.iter().enumerate() { for (i, &(vk, button)) in buttons.iter().enumerate() {
let state = unsafe { GetAsyncKeyState(vk) }; let state = unsafe { GetAsyncKeyState(vk) };
let pressed = (state as u16 & 0x8000) != 0; let pressed = (state.cast_unsigned() & 0x8000) != 0;
if pressed && !last_pressed[i] { if pressed && !last_pressed[i] {
let mut pt = POINT::default(); let mut pt = POINT::default();
if unsafe { GetCursorPos(&mut pt) }.is_ok() { if unsafe { GetCursorPos(&mut pt) }.is_ok() {
@@ -85,7 +85,7 @@ impl ClickRecorder {
pub fn stop(mut self) -> Vec<Click> { pub fn stop(mut self) -> Vec<Click> {
self.running.store(false, Ordering::Relaxed); self.running.store(false, Ordering::Relaxed);
if let Some(t) = self.thread.take() { if let Some(t) = self.thread.take() {
let _ = t.join(); drop(t.join());
} }
self.clicks self.clicks
.lock() .lock()
+4 -4
View File
@@ -187,7 +187,7 @@ impl Config {
e, e,
backup backup
); );
let _ = std::fs::copy(path, &backup); drop(std::fs::copy(path, &backup));
let cfg = Self::default(); let cfg = Self::default();
cfg.save(path)?; cfg.save(path)?;
Ok(cfg) Ok(cfg)
@@ -235,7 +235,7 @@ fn sweep_stale_backups(config_path: &Path) {
if let Some(rest) = name.strip_prefix("config-").and_then(|s| s.strip_suffix(".toml.bak")) { if let Some(rest) = name.strip_prefix("config-").and_then(|s| s.strip_suffix(".toml.bak")) {
if let Ok(ts) = rest.parse::<u64>() { if let Ok(ts) = rest.parse::<u64>() {
if now.saturating_sub(ts) > MAX_AGE_SECS { if now.saturating_sub(ts) > MAX_AGE_SECS {
let _ = std::fs::remove_file(entry.path()); drop(std::fs::remove_file(entry.path()));
} }
} }
} }
@@ -272,7 +272,7 @@ mod tests {
}; };
let dir = std::env::temp_dir().join(format!("bytesize-test-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("bytesize-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir); drop(std::fs::remove_dir_all(&dir));
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("config.toml"); let path = dir.join("config.toml");
cfg.save(&path).unwrap(); cfg.save(&path).unwrap();
@@ -282,7 +282,7 @@ mod tests {
assert_eq!(loaded.hotkeys.start, Some("F9".to_string())); assert_eq!(loaded.hotkeys.start, Some("F9".to_string()));
assert_eq!(loaded.output_dir, Some(PathBuf::from("./custom"))); assert_eq!(loaded.output_dir, Some(PathBuf::from("./custom")));
assert_eq!(loaded.theme, Theme::Light); assert_eq!(loaded.theme, Theme::Light);
let _ = std::fs::remove_dir_all(&dir); drop(std::fs::remove_dir_all(&dir));
} }
#[test] #[test]
+36 -36
View File
@@ -65,8 +65,8 @@ const BOX_HALF: i32 = BOX_SIZE / 2;
/// What `click_filters` needs to place the highlight boxes. /// What `click_filters` needs to place the highlight boxes.
fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32, i32)> { fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32, i32)> {
let vw = clip_w as i32; let vw = clip_w.cast_signed();
let vh = clip_h as i32; let vh = clip_h.cast_signed();
// Only suppress when the point lies entirely outside the frame, so a click // Only suppress when the point lies entirely outside the frame, so a click
// just inside an edge still gets the sliver of box that is visible. // just inside an edge still gets the sliver of box that is visible.
let outside = clip_x + BOX_HALF <= 0 let outside = clip_x + BOX_HALF <= 0
@@ -393,7 +393,7 @@ fn two_pass_video(
// Send 50% to signal pass 1 done, pass 2 starting. // Send 50% to signal pass 1 done, pass 2 starting.
if let Some(ref t) = tx { if let Some(ref t) = tx {
let _ = t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 }); drop(t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 }));
} }
let mut pass2 = Command::new(ffmpeg); let mut pass2 = Command::new(ffmpeg);
@@ -453,7 +453,7 @@ fn cleanup_pass_logs(stem: &Path) {
let name = entry.file_name(); let name = entry.file_name();
if let Some(name_str) = name.to_str() { if let Some(name_str) = name.to_str() {
if name_str.starts_with(prefix) { if name_str.starts_with(prefix) {
let _ = std::fs::remove_file(entry.path()); drop(std::fs::remove_file(entry.path()));
} }
} }
} }
@@ -503,13 +503,13 @@ fn calibrate_via_sample(
// clip overstates per-frame cost slightly (less inter-frame reuse) so we // clip overstates per-frame cost slightly (less inter-frame reuse) so we
// apply a small correction factor toward the conservative side. // apply a small correction factor toward the conservative side.
let aspect = aspect_ratio(req.clip_width, req.clip_height); let aspect = aspect_ratio(req.clip_width, req.clip_height);
let sample_h = (est_width as f64 / aspect).round() as u32; let sample_h = (f64::from(est_width) / aspect).round() as u32;
let frames = (est_fps as f64 * sample_dur).max(1.0); let frames = (f64::from(est_fps) * sample_dur).max(1.0);
let measured_bpp = sample_bytes as f64 / (est_width as f64 * sample_h as f64 * frames); let measured_bpp = sample_bytes as f64 / (f64::from(est_width) * f64::from(sample_h) * frames);
// Blend toward the assumed 0.2 constant - don't over-trust a 2s sample. // Blend toward the assumed 0.2 constant - don't over-trust a 2s sample.
let blended_bpp = measured_bpp * 0.7 + 0.2 * 0.3; let blended_bpp = measured_bpp * 0.7 + 0.2 * 0.3;
let color_factor = (req.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0); let color_factor = (f64::from(req.gif_colors) / 256.0).sqrt().clamp(0.15, 1.0);
let assumed_bpp = 0.2 * color_factor; let assumed_bpp = 0.2 * color_factor;
let ratio = assumed_bpp / blended_bpp; let ratio = assumed_bpp / blended_bpp;
// Only recalibrate if the gap is meaningful (>15%). Small gaps aren't // Only recalibrate if the gap is meaningful (>15%). Small gaps aren't
@@ -520,8 +520,8 @@ fn calibrate_via_sample(
// Recompute target params with the corrected constant. Scale resolution // Recompute target params with the corrected constant. Scale resolution
// by the sqrt of the ratio so file size scales roughly linearly. // by the sqrt of the ratio so file size scales roughly linearly.
let new_width = ((est_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60) * 2; let new_width = ((f64::from(est_width) * ratio.sqrt()).round() as u32 / 2).max(60) * 2;
let new_fps = ((est_fps as f64 * ratio.sqrt()).round() as u32).max(1).min(est_fps); let new_fps = ((f64::from(est_fps) * ratio.sqrt()).round() as u32).max(1).min(est_fps);
Some((new_width.min(1280), new_fps)) Some((new_width.min(1280), new_fps))
} }
@@ -647,15 +647,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
GifBudgetMode::Resolution => { GifBudgetMode::Resolution => {
// Halve before clamping so the *2 keeps the width even. // Halve before clamping so the *2 keeps the width even.
scale_width = scale_width =
((scale_width as f64 * factor).round() as u32 / 2).clamp(60, 640) * 2; ((f64::from(scale_width) * factor).round() as u32 / 2).clamp(60, 640) * 2;
} }
GifBudgetMode::Framerate => { GifBudgetMode::Framerate => {
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); effective_fps = ((f64::from(effective_fps) * factor).round() as u32).max(1);
} }
GifBudgetMode::Balanced => { GifBudgetMode::Balanced => {
scale_width = scale_width =
((scale_width as f64 * factor).round() as u32 / 2).clamp(60, 640) * 2; ((f64::from(scale_width) * factor).round() as u32 / 2).clamp(60, 640) * 2;
effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); effective_fps = ((f64::from(effective_fps) * factor).round() as u32).max(1);
} }
} }
@@ -770,18 +770,18 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
// Fewer colors = better compression. Adjust proportionally to the sqrt of the color // Fewer colors = better compression. Adjust proportionally to the sqrt of the color
// fraction (LZW code width tracks palette depth roughly logarithmically). // fraction (LZW code width tracks palette depth roughly logarithmically).
// 256 colors = 1.0x, 128 = ~0.71x, 64 = 0.5x, 32 = ~0.35x, 16 = 0.25x, 2 = ~0.13x // 256 colors = 1.0x, 128 = ~0.71x, 64 = 0.5x, 32 = ~0.35x, 16 = 0.25x, 2 = ~0.13x
let color_factor = (input.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0); let color_factor = (f64::from(input.gif_colors) / 256.0).sqrt().clamp(0.15, 1.0);
let bytes_per_pixel_per_frame = 0.2 * color_factor; let bytes_per_pixel_per_frame = 0.2 * color_factor;
let target_bytes = input.target_bytes as f64; let target_bytes = input.target_bytes as f64;
let requested_fps = input.fps as f64; let requested_fps = f64::from(input.fps);
let duration = input.duration_secs; let duration = input.duration_secs;
match input.gif_budget_mode { match input.gif_budget_mode {
GifBudgetMode::Resolution => { GifBudgetMode::Resolution => {
let max_w = (clip_width.min(1280) as f64).clamp(120.0, 1280.0); let max_w = f64::from(clip_width.min(1280)).clamp(120.0, 1280.0);
let w = (max_w / 2.0).round() as u32 * 2; let w = (max_w / 2.0).round() as u32 * 2;
let h = (w as f64 / aspect).round() as u32; let h = (f64::from(w) / aspect).round() as u32;
let pixels_per_frame = w as f64 * h as f64; let pixels_per_frame = f64::from(w) * f64::from(h);
let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame; let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame;
let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0); let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0);
let min_fps = (max_frames / duration).max(1.0).round() as u32; let min_fps = (max_frames / duration).max(1.0).round() as u32;
@@ -800,14 +800,14 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
let budget_at_full = target_bytes / (frames_at_full * bytes_per_pixel_per_frame); let budget_at_full = target_bytes / (frames_at_full * bytes_per_pixel_per_frame);
let w_at_full = (budget_at_full * aspect).sqrt().clamp(120.0, 1280.0); let w_at_full = (budget_at_full * aspect).sqrt().clamp(120.0, 1280.0);
let scale = if w_at_full < clip_width as f64 { let scale = if w_at_full < f64::from(clip_width) {
(w_at_full / clip_width as f64).sqrt() (w_at_full / f64::from(clip_width)).sqrt()
} else { } else {
1.0 1.0
}; };
let scale = scale.max(0.1); let scale = scale.max(0.1);
let w = ((clip_width as f64 * scale).round() as u32 / 2).max(60) * 2; let w = ((f64::from(clip_width) * scale).round() as u32 / 2).max(60) * 2;
let fps = ((requested_fps * scale).round() as u32).max(1).min(input.fps); let fps = ((requested_fps * scale).round() as u32).max(1).min(input.fps);
(w, fps) (w, fps)
} }
@@ -816,7 +816,7 @@ pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) ->
pub fn aspect_ratio(width: u32, height: u32) -> f64 { pub fn aspect_ratio(width: u32, height: u32) -> f64 {
if height > 0 { if height > 0 {
width as f64 / height as f64 f64::from(width) / f64::from(height)
} else { } else {
16.0 / 9.0 16.0 / 9.0
} }
@@ -827,7 +827,7 @@ pub fn gif_height_for_width(width: u32, clip_width: u32, clip_height: u32) -> u3
if width == 0 { if width == 0 {
0 0
} else { } else {
((width as f64 / aspect).round() as u32 / 2) * 2 ((f64::from(width) / aspect).round() as u32 / 2) * 2
} }
} }
@@ -915,7 +915,7 @@ pub fn render_gif_preview(
.args(["-frames:v", "1"]) .args(["-frames:v", "1"])
.arg(out_path); .arg(out_path);
let result = run(&mut encode, "gif preview encode"); let result = run(&mut encode, "gif preview encode");
let _ = std::fs::remove_file(&palette_path); drop(std::fs::remove_file(&palette_path));
result result
} }
@@ -934,7 +934,7 @@ fn clean_stale_palettes(dir: &Path) {
for entry in entries.flatten() { for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() { if let Some(name) = entry.file_name().to_str() {
if name.starts_with("preview-palette-") && name.ends_with(".png") { if name.starts_with("preview-palette-") && name.ends_with(".png") {
let _ = std::fs::remove_file(entry.path()); drop(std::fs::remove_file(entry.path()));
} }
} }
} }
@@ -950,7 +950,7 @@ pub fn extract_thumbnails(
) -> Result<Vec<PathBuf>> { ) -> Result<Vec<PathBuf>> {
std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?; std::fs::create_dir_all(out_dir).context("creating thumbnails dir")?;
for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() { for entry in std::fs::read_dir(out_dir).into_iter().flatten().flatten() {
let _ = std::fs::remove_file(entry.path()); drop(std::fs::remove_file(entry.path()));
} }
let crop_prefix = crop_filter(crop) let crop_prefix = crop_filter(crop)
@@ -1035,7 +1035,7 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
struct TempFileGuard(PathBuf); struct TempFileGuard(PathBuf);
impl Drop for TempFileGuard { impl Drop for TempFileGuard {
fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } fn drop(&mut self) { drop(std::fs::remove_file(&self.0)); }
} }
pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> { pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
@@ -1190,11 +1190,11 @@ fn run_impl(
} else if key == "progress" { } else if key == "progress" {
let percent = (last_out_time_us / encode_dur_us * 100.0).clamp(0.0, 100.0); let percent = (last_out_time_us / encode_dur_us * 100.0).clamp(0.0, 100.0);
if let Some(ref sender) = tx { if let Some(ref sender) = tx {
let _ = sender.send(EncodeProgress { drop(sender.send(EncodeProgress {
pass, pass,
total_passes, total_passes,
percent, percent,
}); }));
} }
} }
} }
@@ -1208,7 +1208,7 @@ fn run_impl(
let mut collected = Vec::new(); let mut collected = Vec::new();
use std::io::Read; use std::io::Read;
let mut s = serr; let mut s = serr;
let _ = s.read_to_end(&mut collected); drop(s.read_to_end(&mut collected));
collected collected
}) })
}); });
@@ -1216,16 +1216,16 @@ fn run_impl(
loop { loop {
if let Some(ref c) = cancel { if let Some(ref c) = cancel {
if c.load(Ordering::Relaxed) { if c.load(Ordering::Relaxed) {
let _ = child.kill(); drop(child.kill());
let _ = child.wait(); drop(child.wait());
if let Some(h) = stdout_handle.take() { let _ = h.join(); } if let Some(h) = stdout_handle.take() { drop(h.join()); }
if let Some(h) = stderr_handle.take() { let _ = h.join(); } if let Some(h) = stderr_handle.take() { drop(h.join()); }
bail!("export cancelled"); bail!("export cancelled");
} }
} }
match child.try_wait() { match child.try_wait() {
Ok(Some(status)) => { Ok(Some(status)) => {
if let Some(h) = stdout_handle.take() { let _ = h.join(); } if let Some(h) = stdout_handle.take() { drop(h.join()); }
let stderr_bytes = stderr_handle.take() let stderr_bytes = stderr_handle.take()
.and_then(|h| h.join().ok()) .and_then(|h| h.join().ok())
.unwrap_or_default(); .unwrap_or_default();
+77 -75
View File
@@ -158,7 +158,7 @@ pub struct HotkeyRegistrationResult {
fn register_hotkeys(app: &AppHandle, cfg: &Config) -> HotkeyRegistrationResult { fn register_hotkeys(app: &AppHandle, cfg: &Config) -> HotkeyRegistrationResult {
let gs = app.global_shortcut(); let gs = app.global_shortcut();
let _ = gs.unregister_all(); drop(gs.unregister_all());
let start_ok = cfg let start_ok = cfg
.hotkeys .hotkeys
@@ -258,10 +258,10 @@ async fn download_update(
let dest = updates::pending_update_path(&state.app_dir); let dest = updates::pending_update_path(&state.app_dir);
let app_handle = app.clone(); let app_handle = app.clone();
updates::download_to(&url, &dest, move |downloaded, total| { updates::download_to(&url, &dest, move |downloaded, total| {
let _ = app_handle.emit( drop(app_handle.emit(
"update-download-progress", "update-download-progress",
UpdateDownloadProgress { downloaded, total }, UpdateDownloadProgress { downloaded, total },
); ));
}) })
.await .await
.map_err(|e| format!("{e:#}")) .map_err(|e| format!("{e:#}"))
@@ -294,10 +294,10 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
let app_dir = state.app_dir.clone(); let app_dir = state.app_dir.clone();
let app_handle = app.clone(); let app_handle = app.clone();
bootstrap::download(&app_dir, move |downloaded, total| { bootstrap::download(&app_dir, move |downloaded, total| {
let _ = app_handle.emit( drop(app_handle.emit(
"ffmpeg-progress", "ffmpeg-progress",
DownloadProgress { downloaded, total }, DownloadProgress { downloaded, total },
); ));
}) })
.await .await
.map_err(|e| format!("{e:#}")) .map_err(|e| format!("{e:#}"))
@@ -326,26 +326,26 @@ fn clear_temp_segments(app_dir: &Path) {
|| (name.starts_with("audio-") && name.ends_with(".pcm")) || (name.starts_with("audio-") && name.ends_with(".pcm"))
|| (name.starts_with("preview-palette-") && name.ends_with(".png")) || (name.starts_with("preview-palette-") && name.ends_with(".png"))
{ {
let _ = std::fs::remove_file(entry.path()); drop(std::fs::remove_file(entry.path()));
} }
} }
} }
} }
let _ = std::fs::remove_file(temp.join("recording.mp4")); drop(std::fs::remove_file(temp.join("recording.mp4")));
let _ = std::fs::remove_file(temp.join("video-concat.mp4")); drop(std::fs::remove_file(temp.join("video-concat.mp4")));
let _ = std::fs::remove_file(temp.join("audio-concat.pcm")); drop(std::fs::remove_file(temp.join("audio-concat.pcm")));
let thumbs = temp.join("thumbs"); let thumbs = temp.join("thumbs");
if thumbs.is_dir() { if thumbs.is_dir() {
let _ = std::fs::remove_dir_all(&thumbs); drop(std::fs::remove_dir_all(&thumbs));
} }
let _ = std::fs::remove_file(temp.join("preview.png")); drop(std::fs::remove_file(temp.join("preview.png")));
let _ = std::fs::remove_file(temp.join("raw-preview.png")); drop(std::fs::remove_file(temp.join("raw-preview.png")));
} }
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`. /// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs: f64) -> Result<()> { fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs: f64) -> Result<()> {
use std::io::Write; use std::io::Write;
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0; let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
let target_bytes = (target_secs * bytes_per_sec).round() as u64; let target_bytes = (target_secs * bytes_per_sec).round() as u64;
let current_bytes = std::fs::metadata(path)?.len(); let current_bytes = std::fs::metadata(path)?.len();
if current_bytes == target_bytes { if current_bytes == target_bytes {
@@ -376,7 +376,7 @@ fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs
/// form held it all in a Vec before rewriting. /// form held it all in a Vec before rewriting.
fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64) -> Result<()> { fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64) -> Result<()> {
use std::io::Write; use std::io::Write;
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0; let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
let pad_bytes = (head_secs * bytes_per_sec).round() as u64; let pad_bytes = (head_secs * bytes_per_sec).round() as u64;
if pad_bytes == 0 { if pad_bytes == 0 {
return Ok(()); return Ok(());
@@ -404,7 +404,7 @@ fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64)
// (e.g. a handle still holds the file on Windows). // (e.g. a handle still holds the file on Windows).
if std::fs::rename(&temp, path).is_err() { if std::fs::rename(&temp, path).is_err() {
std::fs::copy(&temp, path)?; std::fs::copy(&temp, path)?;
let _ = std::fs::remove_file(&temp); drop(std::fs::remove_file(&temp));
} }
tracing::debug!( tracing::debug!(
"padded audio head with {:.1}ms ({} bytes) of silence", "padded audio head with {:.1}ms ({} bytes) of silence",
@@ -415,7 +415,7 @@ fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64)
fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) { fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
if let Some(win) = app.get_webview_window("overlay") { if let Some(win) = app.get_webview_window("overlay") {
let _ = win.set_ignore_cursor_events(enabled); drop(win.set_ignore_cursor_events(enabled));
} }
} }
@@ -431,7 +431,7 @@ fn try_start_audio(
Ok(s) => Some(s), Ok(s) => Some(s),
Err(e) => { Err(e) => {
tracing::warn!("audio capture failed: {e:#}"); tracing::warn!("audio capture failed: {e:#}");
let _ = app.emit("audio-failed", e.to_string()); drop(app.emit("audio-failed", e.to_string()));
None None
} }
} }
@@ -473,11 +473,11 @@ fn watch_audio_death(app: AppHandle, died: Arc<AtomicBool>) {
if let Some(session) = take { if let Some(session) = take {
// Drain the dead thread so its handle doesn't leak. The pcm // Drain the dead thread so its handle doesn't leak. The pcm
// it already wrote stays in place for stop_capture to mux. // it already wrote stays in place for stop_capture to mux.
let _ = session.stop(); drop(session.stop());
let _ = app.emit( drop(app.emit(
"audio-failed", "audio-failed",
"audio device lost - endpoint changed or was unplugged".to_string(), "audio device lost - endpoint changed or was unplugged".to_string(),
); ));
} }
return; return;
} }
@@ -695,7 +695,7 @@ fn restart_audio_capture(
*lock(&state.audio) = audio_recovered; *lock(&state.audio) = audio_recovered;
if recovered { if recovered {
let _ = app.emit("audio-recovered", ()); drop(app.emit("audio-recovered", ()));
} }
Ok(()) Ok(())
} }
@@ -760,7 +760,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
encode::concat_segments(&ffmpeg, &ss.segments, &vc) encode::concat_segments(&ffmpeg, &ss.segments, &vc)
.map_err(|e| format!("concat: {e:#}"))?; .map_err(|e| format!("concat: {e:#}"))?;
for seg in &ss.segments { for seg in &ss.segments {
let _ = std::fs::remove_file(seg); drop(std::fs::remove_file(seg));
} }
vc vc
}; };
@@ -810,17 +810,17 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
) )
.map_err(|e| format!("mux: {e:#}"))?; .map_err(|e| format!("mux: {e:#}"))?;
if video_concat != final_path { if video_concat != final_path {
let _ = std::fs::remove_file(&video_concat); drop(std::fs::remove_file(&video_concat));
} }
let _ = std::fs::remove_file(&audio_concat); drop(std::fs::remove_file(&audio_concat));
for ap in &ss.audio_segments { for ap in &ss.audio_segments {
let _ = std::fs::remove_file(ap); drop(std::fs::remove_file(ap));
} }
} else if video_concat != final_path { } else if video_concat != final_path {
std::fs::rename(&video_concat, &final_path) std::fs::rename(&video_concat, &final_path)
.or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ())) .or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ()))
.map_err(|e| format!("finalizing: {e:#}"))?; .map_err(|e| format!("finalizing: {e:#}"))?;
let _ = std::fs::remove_file(&video_concat); drop(std::fs::remove_file(&video_concat));
} }
let clip = RecordedClip { let clip = RecordedClip {
@@ -1180,8 +1180,8 @@ fn start_overlay_clickthrough_poll(
None => continue, None => continue,
}; };
let dpi = unsafe { GetDpiForWindow(HWND(raw.0 as *mut _)) }; let dpi = unsafe { GetDpiForWindow(HWND(raw.0 as *mut std::ffi::c_void)) };
let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 }; let scale = if dpi > 0 { f64::from(dpi) / 96.0 } else { 1.0 };
let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
@@ -1196,7 +1196,7 @@ fn start_overlay_clickthrough_poll(
&& pt.y < inner_bottom; && pt.y < inner_bottom;
if last_inner != Some(in_inner) { if last_inner != Some(in_inner) {
let _ = overlay.set_ignore_cursor_events(in_inner); drop(overlay.set_ignore_cursor_events(in_inner));
last_inner = Some(in_inner); last_inner = Some(in_inner);
} }
std::thread::sleep(Duration::from_millis(80)); std::thread::sleep(Duration::from_millis(80));
@@ -1210,7 +1210,7 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(),
SetWindowDisplayAffinity, WDA_EXCLUDEFROMCAPTURE, SetWindowDisplayAffinity, WDA_EXCLUDEFROMCAPTURE,
}; };
let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
let hwnd = HWND(raw.0 as *mut _); let hwnd = HWND(raw.0 as *mut std::ffi::c_void);
unsafe { unsafe {
SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE)
.map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?; .map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?;
@@ -1224,7 +1224,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
win.show().map_err(|e| format!("showing overlay: {e:#}"))?; win.show().map_err(|e| format!("showing overlay: {e:#}"))?;
let _ = mark_overlay_excluded_from_capture(&win); drop(mark_overlay_excluded_from_capture(&win));
// Wake the click-through poll thread out of its parked state. // Wake the click-through poll thread out of its parked state.
{ {
@@ -1245,7 +1245,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
let center = POINT { x: (vl + vr) / 2, y: (vt + vb) / 2 }; let center = POINT { x: (vl + vr) / 2, y: (vt + vb) / 2 };
let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) }; let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) };
if hmon.0.is_null() { if hmon.0.is_null() {
let hwnd = HWND(raw.0 as *mut _); let hwnd = HWND(raw.0 as *mut std::ffi::c_void);
let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) }; let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() }; let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
if unsafe { GetMonitorInfoW(primary, &mut mi) }.as_bool() { if unsafe { GetMonitorInfoW(primary, &mut mi) }.as_bool() {
@@ -1254,7 +1254,9 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
let h = vb - vt; let h = vb - vt;
let cx = (work.left + work.right) / 2 - w / 2; let cx = (work.left + work.right) / 2 - w / 2;
let cy = (work.top + work.bottom) / 2 - h / 2; let cy = (work.top + work.bottom) / 2 - h / 2;
let _ = unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) }; drop(
unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) },
);
} }
} }
} }
@@ -1269,7 +1271,7 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> {
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
// Reset click-through so the next show starts from a known state, and park // Reset click-through so the next show starts from a known state, and park
// the poll thread until show_overlay wakes it again. // the poll thread until show_overlay wakes it again.
let _ = win.set_ignore_cursor_events(false); drop(win.set_ignore_cursor_events(false));
{ {
let st = app.state::<AppState>(); let st = app.state::<AppState>();
let (lock, cvar) = &*st.overlay_poll_live; let (lock, cvar) = &*st.overlay_poll_live;
@@ -1286,7 +1288,7 @@ fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, heig
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
let ratio = lock(&state.overlay_aspect_ratio); let ratio = lock(&state.overlay_aspect_ratio);
let (w, mut h) = (width as f64, height as f64); let (w, mut h) = (f64::from(width), f64::from(height));
if let Some(r) = *ratio { if let Some(r) = *ratio {
h = w / r; h = w / r;
} }
@@ -1307,8 +1309,8 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().unwrap_or(1.0); let scale = win.scale_factor().unwrap_or(1.0);
let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?; let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
let cur_w = sz.width as f64 / scale; let cur_w = f64::from(sz.width) / scale;
let cur_h = sz.height as f64 / scale; let cur_h = f64::from(sz.height) / scale;
let target_h = cur_w / r; let target_h = cur_w / r;
if (target_h - cur_h).abs() > 1.0 { if (target_h - cur_h).abs() > 1.0 {
use tauri::{LogicalSize, Size}; use tauri::{LogicalSize, Size};
@@ -1337,8 +1339,8 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().unwrap_or(1.0); let scale = win.scale_factor().unwrap_or(1.0);
let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?; let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
let cur_w = sz.width as f64 / scale; let cur_w = f64::from(sz.width) / scale;
let cur_h = sz.height as f64 / scale; let cur_h = f64::from(sz.height) / scale;
let target_h = (cur_w / ratio).round(); let target_h = (cur_w / ratio).round();
if (target_h - cur_h).abs() <= 2.0 { if (target_h - cur_h).abs() <= 2.0 {
return Ok(()); // already correct return Ok(()); // already correct
@@ -1347,12 +1349,12 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
use windows::Win32::Foundation::HWND; use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER}; 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 raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
let hwnd = HWND(raw.0 as *mut _); let hwnd = HWND(raw.0 as *mut std::ffi::c_void);
// Compute outer size including borders // Compute outer size including borders
let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
let outer_w = (sz.width as i32).max(2); let outer_w = sz.width.cast_signed().max(2);
let outer_h = (target_h * scale + titlebar as f64 + border as f64 * 2.0).round() as i32; let outer_h = (target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0).round() as i32;
unsafe { unsafe {
SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, outer_w, outer_h, SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, outer_w, outer_h,
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE) SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE)
@@ -1398,25 +1400,25 @@ fn open_window_picker(
picker picker
.set_position(Position::Physical(PhysicalPosition::new(0, 0))) .set_position(Position::Physical(PhysicalPosition::new(0, 0)))
.map_err(|e| format!("setting picker position: {e:#}"))?; .map_err(|e| format!("setting picker position: {e:#}"))?;
let _ = picker.set_ignore_cursor_events(false); drop(picker.set_ignore_cursor_events(false));
let _ = picker.set_always_on_top(true); drop(picker.set_always_on_top(true));
picker.show().map_err(|e| format!("showing picker: {e:#}"))?; picker.show().map_err(|e| format!("showing picker: {e:#}"))?;
if let Ok(h) = picker.hwnd() { if let Ok(h) = picker.hwnd() {
use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let hwnd = HWND(h.0 as *mut _); let hwnd = HWND(h.0 as *mut std::ffi::c_void);
let mut gr = RECT::default(); let mut gr = RECT::default();
let _ = unsafe { GetWindowRect(hwnd, &mut gr) }; drop(unsafe { GetWindowRect(hwnd, &mut gr) });
let mut dr = RECT::default(); let mut dr = RECT::default();
let _ = unsafe { drop(unsafe {
DwmGetWindowAttribute( DwmGetWindowAttribute(
hwnd, hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS, DWMWA_EXTENDED_FRAME_BOUNDS,
&mut dr as *mut RECT as *mut std::ffi::c_void, &raw mut dr as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32, std::mem::size_of::<RECT>() as u32,
) )
}; });
tracing::debug!( tracing::debug!(
"picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})", "picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})",
gr.left, gr.top, gr.right, gr.bottom, gr.left, gr.top, gr.right, gr.bottom,
@@ -1443,7 +1445,7 @@ fn close_window_picker(
session.stop(); session.stop();
} }
if let Some(picker) = app.get_webview_window("picker") { if let Some(picker) = app.get_webview_window("picker") {
let _ = picker.hide(); drop(picker.hide());
} }
Ok(()) Ok(())
} }
@@ -1452,7 +1454,7 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> {
use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let hwnd = HWND(hwnd_raw as *mut _); let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void);
let mut dwm = RECT::default(); let mut dwm = RECT::default();
if unsafe { if unsafe {
DwmGetWindowAttribute( DwmGetWindowAttribute(
@@ -1481,7 +1483,7 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) {
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let hwnd = HWND(hwnd_raw as *mut _); let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void);
let mut outer = RECT::default(); let mut outer = RECT::default();
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() { if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() {
return (0, 0, 0, 0); return (0, 0, 0, 0);
@@ -1528,7 +1530,7 @@ fn scale_factor_at_point(x: i32, y: i32) -> f64 {
) )
}; };
if hr.is_ok() && dpi_x > 0 { if hr.is_ok() && dpi_x > 0 {
dpi_x as f64 / 96.0 f64::from(dpi_x) / 96.0
} else { } else {
1.0 1.0
} }
@@ -1547,8 +1549,8 @@ fn set_overlay_to_window(
.ok_or_else(|| "overlay window not found".to_string())?; .ok_or_else(|| "overlay window not found".to_string())?;
// Use the target monitor's scale factor, not the overlay's current one, // Use the target monitor's scale factor, not the overlay's current one,
// so border/titlebar compensation is correct when snapping across monitors. // so border/titlebar compensation is correct when snapping across monitors.
let cx = x.saturating_add(width as i32 / 2); let cx = x.saturating_add(width.cast_signed() / 2);
let cy = y.saturating_add(height as i32 / 2); let cy = y.saturating_add(height.cast_signed() / 2);
let scale = scale_factor_at_point(cx, cy); let scale = scale_factor_at_point(cx, cy);
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
@@ -1557,8 +1559,8 @@ fn set_overlay_to_window(
// The capture region is inside the border + below the titlebar. // The capture region is inside the border + below the titlebar.
let visible_left = x - border_phys; let visible_left = x - border_phys;
let visible_top = y - border_phys - titlebar_phys; let visible_top = y - border_phys - titlebar_phys;
let visible_w = width as i32 + border_phys * 2; let visible_w = width.cast_signed() + border_phys * 2;
let visible_h = height as i32 + border_phys * 2 + titlebar_phys; let visible_h = height.cast_signed() + border_phys * 2 + titlebar_phys;
// Compensate for the invisible DWM border that Windows adds around // Compensate for the invisible DWM border that Windows adds around
// top-level windows (Tauri's set_position sets the outer rect, but the // top-level windows (Tauri's set_position sets the outer rect, but the
@@ -1570,8 +1572,8 @@ fn set_overlay_to_window(
let outer_x = visible_left - li; let outer_x = visible_left - li;
let outer_y = visible_top - ti; let outer_y = visible_top - ti;
let outer_w = (visible_w + li + ri).max(2) as u32; let outer_w = (visible_w + li + ri).max(2).cast_unsigned();
let outer_h = (visible_h + ti + bi).max(2) as u32; let outer_h = (visible_h + ti + bi).max(2).cast_unsigned();
// Bypass Tauri's set_position/set_size which adds extra pixels for // Bypass Tauri's set_position/set_size which adds extra pixels for
// some unknown reason. Use Win32 SetWindowPos with explicit outer rect. // some unknown reason. Use Win32 SetWindowPos with explicit outer rect.
@@ -1580,15 +1582,15 @@ fn set_overlay_to_window(
use windows::Win32::UI::WindowsAndMessaging::{ use windows::Win32::UI::WindowsAndMessaging::{
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER, SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER,
}; };
let hwnd = HWND(raw.0 as *mut _); let hwnd = HWND(raw.0 as *mut std::ffi::c_void);
unsafe { unsafe {
SetWindowPos( SetWindowPos(
hwnd, hwnd,
Some(HWND_TOP), Some(HWND_TOP),
outer_x, outer_x,
outer_y, outer_y,
outer_w as i32, outer_w.cast_signed(),
outer_h as i32, outer_h.cast_signed(),
SWP_NOACTIVATE | SWP_NOZORDER, SWP_NOACTIVATE | SWP_NOZORDER,
) )
} }
@@ -1617,8 +1619,8 @@ fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
let visible_w = vr - vl; let visible_w = vr - vl;
let visible_h = vb - vt; let visible_h = vb - vt;
let width = (visible_w - inset_sides * 2).max(2) as u32; let width = (visible_w - inset_sides * 2).max(2).cast_unsigned();
let height = (visible_h - inset_top - inset_sides).max(2) as u32; let height = (visible_h - inset_top - inset_sides).max(2).cast_unsigned();
let width = (width / 2) * 2; let width = (width / 2) * 2;
let height = (height / 2) * 2; let height = (height / 2) * 2;
@@ -1746,7 +1748,7 @@ fn diagnostics_info(state: State<'_, AppState>) -> DiagnosticsInfo {
fn open_log_dir(state: State<'_, AppState>) -> Result<(), String> { fn open_log_dir(state: State<'_, AppState>) -> Result<(), String> {
use std::os::windows::process::CommandExt; use std::os::windows::process::CommandExt;
let log_dir = state.app_dir.join("logs"); let log_dir = state.app_dir.join("logs");
let _ = std::fs::create_dir_all(&log_dir); drop(std::fs::create_dir_all(&log_dir));
std::process::Command::new("explorer.exe") std::process::Command::new("explorer.exe")
.raw_arg(log_dir.to_string_lossy().to_string()) .raw_arg(log_dir.to_string_lossy().to_string())
.spawn() .spawn()
@@ -1820,14 +1822,14 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
(0, 0), (0, 0),
) )
}; };
let scale = clip.width as f64 / src_w as f64; let scale = f64::from(clip.width) / f64::from(src_w);
let transformed_clicks: Vec<clicks::Click> = clip let transformed_clicks: Vec<clicks::Click> = clip
.clicks .clicks
.iter() .iter()
.map(|c| clicks::Click { .map(|c| clicks::Click {
time_secs: c.time_secs, time_secs: c.time_secs,
x: (((c.x - src_origin.0) as f64) * scale).round() as i32, x: (f64::from(c.x - src_origin.0) * scale).round() as i32,
y: (((c.y - src_origin.1) as f64) * scale).round() as i32, y: (f64::from(c.y - src_origin.1) * scale).round() as i32,
button: c.button, button: c.button,
}) })
.collect(); .collect();
@@ -1867,14 +1869,14 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
// so the progress bar accumulates across retry attempts. // so the progress bar accumulates across retry attempts.
std::thread::spawn(move || { std::thread::spawn(move || {
while let Ok(progress) = rx.recv() { while let Ok(progress) = rx.recv() {
let _ = app_handle.emit( drop(app_handle.emit(
"encode-progress", "encode-progress",
encode::EncodeProgress { encode::EncodeProgress {
pass: progress.pass, pass: progress.pass,
total_passes: progress.total_passes, total_passes: progress.total_passes,
percent: progress.percent, percent: progress.percent,
}, },
); ));
} }
}); });
@@ -1911,7 +1913,7 @@ pub fn run() {
clear_temp_segments(&app_dir); clear_temp_segments(&app_dir);
let log_dir = app_dir.join("logs"); let log_dir = app_dir.join("logs");
let _ = std::fs::create_dir_all(&log_dir); drop(std::fs::create_dir_all(&log_dir));
let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log"); let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log");
let (file_writer, _log_guard) = tracing_appender::non_blocking(file_appender); let (file_writer, _log_guard) = tracing_appender::non_blocking(file_appender);
@@ -1923,7 +1925,7 @@ pub fn run() {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout)); let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
#[cfg(test)] #[cfg(test)]
let _ = registry.try_init(); drop(registry.try_init());
#[cfg(not(test))] #[cfg(not(test))]
registry.init(); registry.init();
@@ -2006,7 +2008,7 @@ pub fn run() {
None None
}; };
if let Some(k) = kind { if let Some(k) = kind {
let _ = app.emit("hotkey", k); drop(app.emit("hotkey", k));
} }
}) })
.build(), .build(),
@@ -2018,7 +2020,7 @@ pub fn run() {
let cfg = lock(&st.config).clone(); let cfg = lock(&st.config).clone();
(cfg.updates.check_on_launch, cfg) (cfg.updates.check_on_launch, cfg)
}; };
let _ = register_hotkeys(app.handle(), &cfg); drop(register_hotkeys(app.handle(), &cfg));
{ {
let st = app.state::<AppState>(); let st = app.state::<AppState>();
start_overlay_clickthrough_poll( start_overlay_clickthrough_poll(
@@ -2039,7 +2041,7 @@ pub fn run() {
match updates::check_for_update().await { match updates::check_for_update().await {
Ok(Some(info)) => { Ok(Some(info)) => {
tracing::info!(version = info.version, "update available"); tracing::info!(version = info.version, "update available");
let _ = handle.emit("update-available", &info); drop(handle.emit("update-available", &info));
} }
Ok(None) => tracing::debug!("no update available"), Ok(None) => tracing::debug!("no update available"),
Err(e) => tracing::warn!("update check failed: {e:#}"), Err(e) => tracing::warn!("update check failed: {e:#}"),
+2 -2
View File
@@ -116,9 +116,9 @@ pub fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool {
pub fn stamp_check(app_dir: &Path) { pub fn stamp_check(app_dir: &Path) {
let path = last_check_path(app_dir); let path = last_check_path(app_dir);
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent); drop(std::fs::create_dir_all(parent));
} }
let _ = std::fs::write(&path, b""); drop(std::fs::write(&path, b""));
} }
pub fn has_pending_update(app_dir: &Path) -> bool { pub fn has_pending_update(app_dir: &Path) -> bool {
+17 -17
View File
@@ -92,7 +92,7 @@ unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL {
if IsIconic(hwnd).as_bool() { if IsIconic(hwnd).as_bool() {
return BOOL(1); return BOOL(1);
} }
let ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; let ex = GetWindowLongW(hwnd, GWL_EXSTYLE).cast_unsigned();
if (ex & WS_EX_TOOLWINDOW.0) != 0 { if (ex & WS_EX_TOOLWINDOW.0) != 0 {
return BOOL(1); return BOOL(1);
} }
@@ -127,10 +127,10 @@ fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> {
found: None, found: None,
}; };
unsafe { unsafe {
let _ = EnumWindows( drop(EnumWindows(
Some(enum_at_point), Some(enum_at_point),
LPARAM(&mut ctx as *mut EnumCtx as isize), LPARAM(&raw mut ctx as *mut EnumCtx as isize),
); ));
} }
ctx.found ctx.found
} }
@@ -158,7 +158,7 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
if let Some((id, rect)) = target { if let Some((id, rect)) = target {
if id != last_hwnd { if id != last_hwnd {
let class = unsafe { class_of(HWND(id as *mut _)) }; let class = unsafe { class_of(HWND(id as *mut std::ffi::c_void)) };
tracing::info!( tracing::info!(
"picker hover: hwnd={:x} class={} rect=({},{}) {}x{}", "picker hover: hwnd={:x} class={} rect=({},{}) {}x{}",
id, id,
@@ -168,15 +168,15 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
rect.right - rect.left, rect.right - rect.left,
rect.bottom - rect.top rect.bottom - rect.top
); );
let _ = app.emit( drop(app.emit(
"picker-hover", "picker-hover",
Rect { Rect {
x: rect.left, x: rect.left,
y: rect.top, y: rect.top,
width: (rect.right - rect.left).max(0) as u32, width: (rect.right - rect.left).max(0).cast_unsigned(),
height: (rect.bottom - rect.top).max(0) as u32, height: (rect.bottom - rect.top).max(0).cast_unsigned(),
}, },
); ));
last_hwnd = id; last_hwnd = id;
} }
} else if last_hwnd != 0 { } else if last_hwnd != 0 {
@@ -185,27 +185,27 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
} }
let pressed = let pressed =
unsafe { (GetAsyncKeyState(VK_LBUTTON) as u16 & 0x8000) != 0 }; unsafe { (GetAsyncKeyState(VK_LBUTTON).cast_unsigned() & 0x8000) != 0 };
if pressed && !last_pressed { if pressed && !last_pressed {
if let Some((_, rect)) = target { if let Some((_, rect)) = target {
let _ = app.emit( drop(app.emit(
"picker-pick", "picker-pick",
Rect { Rect {
x: rect.left, x: rect.left,
y: rect.top, y: rect.top,
width: (rect.right - rect.left).max(0) as u32, width: (rect.right - rect.left).max(0).cast_unsigned(),
height: (rect.bottom - rect.top).max(0) as u32, height: (rect.bottom - rect.top).max(0).cast_unsigned(),
}, },
); ));
break; break;
} }
} }
last_pressed = pressed; last_pressed = pressed;
let esc = let esc =
unsafe { (GetAsyncKeyState(VK_ESCAPE) as u16 & 0x8000) != 0 }; unsafe { (GetAsyncKeyState(VK_ESCAPE).cast_unsigned() & 0x8000) != 0 };
if esc && !last_esc { if esc && !last_esc {
let _ = app.emit("picker-cancel", ()); drop(app.emit("picker-cancel", ()));
break; break;
} }
last_esc = esc; last_esc = esc;
@@ -224,7 +224,7 @@ impl PickerSession {
pub fn stop(mut self) { pub fn stop(mut self) {
self.running.store(false, Ordering::Relaxed); self.running.store(false, Ordering::Relaxed);
if let Some(h) = self.handle.take() { if let Some(h) = self.handle.take() {
let _ = h.join(); drop(h.join());
} }
} }
} }
+5 -5
View File
@@ -19,10 +19,10 @@ pub struct WindowInfo {
pub fn list_visible_windows() -> Vec<WindowInfo> { pub fn list_visible_windows() -> Vec<WindowInfo> {
let mut out: Vec<WindowInfo> = Vec::new(); let mut out: Vec<WindowInfo> = Vec::new();
unsafe { unsafe {
let _ = EnumWindows( drop(EnumWindows(
Some(enum_cb), Some(enum_cb),
LPARAM(&mut out as *mut Vec<WindowInfo> as isize), LPARAM(&raw mut out as *mut Vec<WindowInfo> as isize),
); ));
} }
out out
} }
@@ -64,8 +64,8 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL {
title, title,
x: rect.left, x: rect.left,
y: rect.top, y: rect.top,
width: w as u32, width: w.cast_unsigned(),
height: h as u32, height: h.cast_unsigned(),
}); });
BOOL(1) BOOL(1)
} }