document the remaining win32 safety contracts

This commit is contained in:
2026-09-21 01:14:27 +03:00
parent 630687945a
commit 8972592b8d
6 changed files with 152 additions and 37 deletions
+19 -5
View File
@@ -96,11 +96,25 @@ impl AudioSession {
} }
fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> { fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
// SAFETY: WAVEFORMATEX is repr(packed); read_unaligned avoids UB from unaligned field access. // WAVEFORMATEX is repr(packed), so the fields have to be read with
let w_format_tag = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wFormatTag)) }; // read_unaligned rather than through references. `fmt` comes from
let n_channels = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nChannels)) }; // GetMixFormat and stays valid for the whole call.
let n_samples_per_sec = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nSamplesPerSec)) }; //
let w_bits_per_sample = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wBitsPerSample)) }; // Kept in one block because the four reads share one invariant.
#[allow(
clippy::multiple_unsafe_ops_per_block,
reason = "one packed-struct readout; splitting would repeat the same safety argument four times"
)]
// SAFETY: `fmt` is a valid, fully-initialized WAVEFORMATEX for the duration
// of this function, and each read copies an integer out by value.
let (w_format_tag, n_channels, n_samples_per_sec, w_bits_per_sample) = unsafe {
(
std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wFormatTag)),
std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nChannels)),
std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nSamplesPerSec)),
std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wBitsPerSample)),
)
};
let is_float = if w_format_tag == WAVE_FORMAT_IEEE_FLOAT { let is_float = if w_format_tag == WAVE_FORMAT_IEEE_FLOAT {
true true
+11 -2
View File
@@ -363,6 +363,10 @@ impl TonemapPipeline {
// -> viewport+scissor -> draw. Every stage is set explicitly because the // -> viewport+scissor -> draw. Every stage is set explicitly because the
// frame's device/context still carries state from prior frames. // frame's device/context still carries state from prior frames.
// //
#[allow(
clippy::multiple_unsafe_ops_per_block,
reason = "the bind sequence only makes sense as one unit; splitting it would imply the intermediate states are reachable"
)]
// SAFETY: every resource bound here was created on this same device and // SAFETY: every resource bound here was created on this same device and
// is kept alive by `self` for the duration of the draw; the slices and // is kept alive by `self` for the duration of the draw; the slices and
// viewport/scissor arrays are stack locals that outlive each call. // viewport/scissor arrays are stack locals that outlive each call.
@@ -388,10 +392,15 @@ impl TonemapPipeline {
} }
// Copy to the SDR staging texture and read it back. // Copy to the SDR staging texture and read it back.
let row_bytes = self.width * 4;
#[allow(
clippy::multiple_unsafe_ops_per_block,
reason = "copy/map/read/unmap must stay paired; the map guard has to be released in the same scope"
)]
// SAFETY: both textures live on this device and share dimensions and // SAFETY: both textures live on this device and share dimensions and
// format, so the copy is well-defined; `mapped` is a zeroed local that // format, so the copy is well-defined; `mapped` is a zeroed local that
// Map fills before any field of it is read. // Map fills before any field of it is read, and the slice is sized from
let row_bytes = self.width * 4; // the mapped pitch and this pipeline's own height.
unsafe { unsafe {
context.CopyResource(&self.staging, &self.render_target); context.CopyResource(&self.staging, &self.render_target);
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
+4
View File
@@ -52,10 +52,14 @@ pub(crate) 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() {
// SAFETY: both calls are self-contained Win32 queries. `pt` is
// a local that GetCursorPos writes, and it is only read after
// the call reports success.
let state = unsafe { GetAsyncKeyState(vk) }; let state = unsafe { GetAsyncKeyState(vk) };
let pressed = (state.cast_unsigned() & 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();
// SAFETY: `pt` is a live local the call writes through.
if unsafe { GetCursorPos(&raw mut pt) }.is_ok() { if unsafe { GetCursorPos(&raw mut pt) }.is_ok() {
let click = Click { let click = Click {
time_secs: start.elapsed().as_secs_f64(), time_secs: start.elapsed().as_secs_f64(),
+31
View File
@@ -1212,6 +1212,7 @@ fn start_overlay_clickthrough_poll(
} }
let mut pt = POINT::default(); let mut pt = POINT::default();
// SAFETY: `pt` is a live local that GetCursorPos writes through.
if unsafe { GetCursorPos(&raw mut pt) }.is_err() { if unsafe { GetCursorPos(&raw mut pt) }.is_err() {
continue; continue;
} }
@@ -1225,6 +1226,7 @@ fn start_overlay_clickthrough_poll(
None => continue, None => continue,
}; };
// SAFETY: `raw` is the overlay's own live HWND from Tauri.
let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::<std::ffi::c_void>())) }; let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::<std::ffi::c_void>())) };
let scale = if dpi > 0 { f64::from(dpi) / 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;
@@ -1256,6 +1258,8 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(),
}; };
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.cast::<std::ffi::c_void>()); let hwnd = HWND(raw.0.cast::<std::ffi::c_void>());
// SAFETY: `hwnd` is the overlay's live window handle and the affinity flag
// is a plain enum with no pointer arguments.
unsafe { unsafe {
SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE)
.map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?; .map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?;
@@ -1288,11 +1292,21 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
if let Ok(raw) = win.hwnd() { if let Ok(raw) = win.hwnd() {
if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) { if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) {
let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb) }; let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb) };
// MonitorFromPoint only reads the POINT by value and returns null
// for "no monitor", which the next branch handles.
//
// SAFETY: the POINTs passed in are plain values constructed here.
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.cast::<std::ffi::c_void>()); let hwnd = HWND(raw.0.cast::<std::ffi::c_void>());
// SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot
// fail on a running desktop.
let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) }; let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
// cbSize is required by GetMonitorInfoW and is set from the
// actual struct size, so the write below stays in bounds.
let mut mi = MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, ..Default::default() }; let mut mi = MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, ..Default::default() };
// SAFETY: `mi` is a live local of the declared size, and the
// result is checked with as_bool() before mi is read.
if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() { if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() {
let work = mi.rcWork; let work = mi.rcWork;
let w = vr - vl; let w = vr - vl;
@@ -1300,6 +1314,8 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
let cx = i32::midpoint(work.left, work.right) - w / 2; let cx = i32::midpoint(work.left, work.right) - w / 2;
let cy = i32::midpoint(work.top, work.bottom) - h / 2; let cy = i32::midpoint(work.top, work.bottom) - h / 2;
drop( drop(
// SAFETY: `hwnd` is the overlay's live handle; the flags
// keep this a size-only, non-activating move.
unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) }, unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) },
); );
} }
@@ -1400,6 +1416,8 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
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.cast_signed().max(2); let outer_w = sz.width.cast_signed().max(2);
let outer_h = (target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0).round() as i32; let outer_h = (target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0).round() as i32;
// SAFETY: `hwnd` is the overlay's live handle; the flags keep the resize
// non-activating and non-reordering, and no pointers are involved.
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)
@@ -1454,8 +1472,11 @@ fn open_window_picker(
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let hwnd = HWND(h.0.cast::<std::ffi::c_void>()); let hwnd = HWND(h.0.cast::<std::ffi::c_void>());
let mut gr = RECT::default(); let mut gr = RECT::default();
// SAFETY: `gr` is a live local that GetWindowRect writes through.
drop(unsafe { GetWindowRect(hwnd, &raw mut gr) }); drop(unsafe { GetWindowRect(hwnd, &raw mut gr) });
let mut dr = RECT::default(); let mut dr = RECT::default();
// SAFETY: `dr` is a live RECT local, the attribute is the documented
// DWMWA_EXTENDED_FRAME_BOUNDS, and the size passed matches its type.
drop(unsafe { drop(unsafe {
DwmGetWindowAttribute( DwmGetWindowAttribute(
hwnd, hwnd,
@@ -1501,6 +1522,8 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> {
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void); let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void);
let mut dwm = RECT::default(); let mut dwm = RECT::default();
// SAFETY: `dwm` is a live RECT local and the size argument matches it; the
// result is checked and the rect is only read when it is well-formed.
if unsafe { if unsafe {
DwmGetWindowAttribute( DwmGetWindowAttribute(
hwnd, hwnd,
@@ -1516,6 +1539,7 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> {
return Some((dwm.left, dwm.top, dwm.right, dwm.bottom)); return Some((dwm.left, dwm.top, dwm.right, dwm.bottom));
} }
let mut outer = RECT::default(); let mut outer = RECT::default();
// SAFETY: `outer` is a live RECT local that the call writes through.
if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_ok() { if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_ok() {
Some((outer.left, outer.top, outer.right, outer.bottom)) Some((outer.left, outer.top, outer.right, outer.bottom))
} else { } else {
@@ -1530,10 +1554,12 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) {
let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void); let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void);
let mut outer = RECT::default(); let mut outer = RECT::default();
// SAFETY: `outer` is a live RECT local that the call writes through.
if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_err() { if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_err() {
return (0, 0, 0, 0); return (0, 0, 0, 0);
} }
let mut dwm = RECT::default(); let mut dwm = RECT::default();
// SAFETY: `dwm` is a live RECT local and the size argument matches it.
let r = unsafe { let r = unsafe {
DwmGetWindowAttribute( DwmGetWindowAttribute(
hwnd, hwnd,
@@ -1560,12 +1586,15 @@ fn scale_factor_at_point(x: i32, y: i32) -> f64 {
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MONITOR_DPI_TYPE}; use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MONITOR_DPI_TYPE};
let pt = POINT { x, y }; let pt = POINT { x, y };
// SAFETY: value-only call; a null result is handled on the next line.
let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) }; let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
if hmonitor.0.is_null() { if hmonitor.0.is_null() {
return 1.0; return 1.0;
} }
let mut dpi_x = 0u32; let mut dpi_x = 0u32;
let mut dpi_y = 0u32; let mut dpi_y = 0u32;
// SAFETY: both out-params are live u32 locals that the call writes through,
// and `hmonitor` was checked non-null above.
let hr = unsafe { let hr = unsafe {
GetDpiForMonitor( GetDpiForMonitor(
hmonitor, hmonitor,
@@ -1627,6 +1656,8 @@ fn set_overlay_to_window(
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER, SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER,
}; };
let hwnd = HWND(raw.0.cast::<std::ffi::c_void>()); let hwnd = HWND(raw.0.cast::<std::ffi::c_void>());
// SAFETY: `hwnd` is the overlay's live handle and every dimension is a
// plain integer computed above; no pointers are passed.
unsafe { unsafe {
SetWindowPos( SetWindowPos(
hwnd, hwnd,
+56 -16
View File
@@ -14,24 +14,34 @@ use windows::Win32::UI::WindowsAndMessaging::{
IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW, IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW,
}; };
unsafe fn visible_window_rect(hwnd: HWND) -> Option<RECT> { unsafe { /// Resolve the visible frame of a window: the DWM extended frame when the
/// compositor reports one, otherwise the raw window rect.
///
/// # Safety
///
/// The caller must pass a live `HWND`.
unsafe fn visible_window_rect(hwnd: HWND) -> Option<RECT> {
let mut rect = RECT::default(); let mut rect = RECT::default();
let r = DwmGetWindowAttribute( // SAFETY: `rect` is a live RECT local and the size argument matches it.
let r = unsafe {
DwmGetWindowAttribute(
hwnd, hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS, DWMWA_EXTENDED_FRAME_BOUNDS,
(&raw mut rect).cast::<std::ffi::c_void>(), (&raw mut rect).cast::<std::ffi::c_void>(),
size_of::<RECT>() as u32, size_of::<RECT>() as u32,
); )
};
if r.is_ok() && rect.right > rect.left && rect.bottom > rect.top { if r.is_ok() && rect.right > rect.left && rect.bottom > rect.top {
return Some(rect); return Some(rect);
} }
let mut fallback = RECT::default(); let mut fallback = RECT::default();
if GetWindowRect(hwnd, &raw mut fallback).is_ok() { // SAFETY: `fallback` is a live RECT local that the call writes through.
if unsafe { GetWindowRect(hwnd, &raw mut fallback) }.is_ok() {
Some(fallback) Some(fallback)
} else { } else {
None None
} }
}} }
const VK_LBUTTON: i32 = 0x01; const VK_LBUTTON: i32 = 0x01;
const VK_ESCAPE: i32 = 0x1B; const VK_ESCAPE: i32 = 0x1B;
@@ -68,17 +78,33 @@ const SHELL_CLASSES: &[&str] = &[
"Windows.UI.Core.CoreWindow", "Windows.UI.Core.CoreWindow",
]; ];
unsafe fn class_of(hwnd: HWND) -> String { unsafe { /// Read a window's class name into a fixed buffer.
///
/// # Safety
///
/// The caller must pass a live `HWND`.
unsafe fn class_of(hwnd: HWND) -> String {
let mut buf = [0u16; 128]; let mut buf = [0u16; 128];
let n = GetClassNameW(hwnd, &mut buf); // SAFETY: GetClassNameW writes at most buf.len() UTF-16 units into `buf`;
// it returns the count written, which is bounds-checked before slicing.
let n = unsafe { GetClassNameW(hwnd, &mut buf) };
if n <= 0 { if n <= 0 {
return String::new(); return String::new();
} }
String::from_utf16_lossy(&buf[..n as usize]) String::from_utf16_lossy(&buf[..n as usize])
}} }
unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { /// `EnumWindows` callback: records the first top-level window containing the
let ctx = &mut *(lparam.0 as *mut EnumCtx); /// target point. Returning FALSE stops the enumeration.
///
/// # Safety
///
/// `EnumWindows` hands back the `LPARAM` that `top_window_at` passed in, which
/// is a live `*mut EnumCtx` for the duration of the enumeration.
unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL {
// SAFETY: `lparam` is the pointer passed to EnumWindows by top_window_at,
// and that EnumCtx outlives the call.
let ctx = unsafe { &mut *(lparam.0 as *mut EnumCtx) };
if ctx.found.is_some() { if ctx.found.is_some() {
return BOOL(1); return BOOL(1);
} }
@@ -86,21 +112,29 @@ unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { un
if ctx.exclude.contains(&id) { if ctx.exclude.contains(&id) {
return BOOL(1); return BOOL(1);
} }
if !IsWindowVisible(hwnd).as_bool() { // The checks below are all read-only queries against the window handle
// EnumWindows just handed us, so it is live for this call.
//
// SAFETY: `hwnd` is a live top-level window handle.
if !unsafe { IsWindowVisible(hwnd) }.as_bool() {
return BOOL(1); return BOOL(1);
} }
if IsIconic(hwnd).as_bool() { // SAFETY: same live handle.
if unsafe { IsIconic(hwnd) }.as_bool() {
return BOOL(1); return BOOL(1);
} }
let ex = GetWindowLongW(hwnd, GWL_EXSTYLE).cast_unsigned(); // SAFETY: same live handle; GWL_EXSTYLE reads a window style word.
let ex = unsafe { 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);
} }
let class_name = class_of(hwnd); // SAFETY: `hwnd` is the live handle described above.
let class_name = unsafe { class_of(hwnd) };
if SHELL_CLASSES.iter().any(|c| class_name == *c) { if SHELL_CLASSES.iter().any(|c| class_name == *c) {
return BOOL(1); return BOOL(1);
} }
let rect = match visible_window_rect(hwnd) { // SAFETY: `hwnd` is the live handle described above.
let rect = match unsafe { visible_window_rect(hwnd) } {
Some(r) => r, Some(r) => r,
None => return BOOL(1), None => return BOOL(1),
}; };
@@ -118,7 +152,7 @@ unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { un
} }
ctx.found = Some((id, rect)); ctx.found = Some((id, rect));
BOOL(0) BOOL(0)
}} }
fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> { fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> {
let mut ctx = EnumCtx { let mut ctx = EnumCtx {
@@ -126,6 +160,8 @@ fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> {
exclude: exclude.to_vec(), exclude: exclude.to_vec(),
found: None, found: None,
}; };
// SAFETY: `ctx` is a live local of exactly the type enum_at_point expects,
// and it outlives the call because EnumWindows runs to completion here.
unsafe { unsafe {
drop(EnumWindows( drop(EnumWindows(
Some(enum_at_point), Some(enum_at_point),
@@ -149,6 +185,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession
} }
let mut pt = POINT::default(); let mut pt = POINT::default();
// SAFETY: `pt` is a live local that GetCursorPos writes through.
if unsafe { GetCursorPos(&raw mut pt) }.is_err() { if unsafe { GetCursorPos(&raw mut pt) }.is_err() {
thread::sleep(Duration::from_millis(30)); thread::sleep(Duration::from_millis(30));
continue; continue;
@@ -158,6 +195,7 @@ pub(crate) 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 {
// SAFETY: `id` came from EnumWindows, so it is a live HWND.
let class = unsafe { class_of(HWND(id as *mut std::ffi::c_void)) }; 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{}",
@@ -185,6 +223,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession
} }
let pressed = let pressed =
// SAFETY: a self-contained query with no pointer arguments.
unsafe { (GetAsyncKeyState(VK_LBUTTON).cast_unsigned() & 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 {
@@ -203,6 +242,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession
last_pressed = pressed; last_pressed = pressed;
let esc = let esc =
// SAFETY: a self-contained query with no pointer arguments.
unsafe { (GetAsyncKeyState(VK_ESCAPE).cast_unsigned() & 0x8000) != 0 }; unsafe { (GetAsyncKeyState(VK_ESCAPE).cast_unsigned() & 0x8000) != 0 };
if esc && !last_esc { if esc && !last_esc {
drop(app.emit("picker-cancel", ())); drop(app.emit("picker-cancel", ()));
+27 -10
View File
@@ -18,6 +18,8 @@ pub(crate) struct WindowInfo {
pub(crate) fn list_visible_windows() -> Vec<WindowInfo> { pub(crate) fn list_visible_windows() -> Vec<WindowInfo> {
let mut out: Vec<WindowInfo> = Vec::new(); let mut out: Vec<WindowInfo> = Vec::new();
// SAFETY: `out` is a live local of exactly the type enum_cb expects, and it
// outlives the call because EnumWindows runs to completion here.
unsafe { unsafe {
drop(EnumWindows( drop(EnumWindows(
Some(enum_cb), Some(enum_cb),
@@ -27,16 +29,26 @@ pub(crate) fn list_visible_windows() -> Vec<WindowInfo> {
out out
} }
unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { /// `EnumWindows` callback: appends every visible, titled, non-minimised
if !IsWindowVisible(hwnd).as_bool() { /// top-level window to the `Vec` behind `lparam`.
return BOOL(1); ///
} /// # Safety
if IsIconic(hwnd).as_bool() { ///
/// `EnumWindows` hands back the `LPARAM` that `list_visible_windows` passed in,
/// which is a live `*mut Vec<WindowInfo>` for the duration of the enumeration.
unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL {
// SAFETY: `hwnd` comes from the enumerator, so it is a live handle for the
// duration of this call.
let visible = unsafe { IsWindowVisible(hwnd) };
// SAFETY: same live handle.
let iconic = unsafe { IsIconic(hwnd) };
if !visible.as_bool() || iconic.as_bool() {
return BOOL(1); return BOOL(1);
} }
let mut rect = RECT::default(); let mut rect = RECT::default();
if GetWindowRect(hwnd, &raw mut rect).is_err() { // SAFETY: `rect` is a live RECT local that the call writes through.
if unsafe { GetWindowRect(hwnd, &raw mut rect) }.is_err() {
return BOOL(1); return BOOL(1);
} }
let w = rect.right - rect.left; let w = rect.right - rect.left;
@@ -45,12 +57,15 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe {
return BOOL(1); return BOOL(1);
} }
let title_len = GetWindowTextLengthW(hwnd); // SAFETY: `hwnd` is the live handle described above.
let title_len = unsafe { GetWindowTextLengthW(hwnd) };
if title_len <= 0 { if title_len <= 0 {
return BOOL(1); return BOOL(1);
} }
let mut buf = vec![0u16; (title_len as usize) + 1]; let mut buf = vec![0u16; (title_len as usize) + 1];
let copied = GetWindowTextW(hwnd, &mut buf); // SAFETY: `buf` has room for title_len + 1 UTF-16 units, which is what the
// call is documented to write at most; the result is bounds-checked below.
let copied = unsafe { GetWindowTextW(hwnd, &mut buf) };
if copied <= 0 { if copied <= 0 {
return BOOL(1); return BOOL(1);
} }
@@ -59,7 +74,9 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe {
return BOOL(1); return BOOL(1);
} }
let list = &mut *(lparam.0 as *mut Vec<WindowInfo>); // SAFETY: `lparam` is the pointer passed to EnumWindows by
// list_visible_windows, and that Vec outlives the call.
let list = unsafe { &mut *(lparam.0 as *mut Vec<WindowInfo>) };
list.push(WindowInfo { list.push(WindowInfo {
title, title,
x: rect.left, x: rect.left,
@@ -68,4 +85,4 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe {
height: h.cast_unsigned(), height: h.cast_unsigned(),
}); });
BOOL(1) BOOL(1)
}} }