Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! The mouse pointer, drawn into captured frames.
//!
//! Windows Graphics Capture can draw the pointer itself, but it leaves it out of games that
//! present through independent flip or a hardware cursor plane (Minecraft, for one). Discord's
//! and OBS's game capture draw the system cursor into each frame instead, and so does this: the
//! pointer appears wherever Windows shows it and is gone while a game hides it.
#![allow(unsafe_code)]
use windows::Win32::{
Foundation::{HWND, POINT, RECT},
Graphics::{
Dwm::{DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute},
Gdi::{
BI_RGB, BITMAP, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleDC, CreateDIBSection,
DIB_RGB_COLORS, DeleteDC, DeleteObject, GdiFlush, GetMonitorInfoW, GetObjectW,
HMONITOR, MONITORINFO, SelectObject,
},
},
UI::{
HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetThreadDpiAwarenessContext},
WindowsAndMessaging::{
CURSOR_SHOWING, CURSORINFO, DI_NORMAL, DrawIconEx, GA_ROOTOWNER, GetAncestor,
GetCursorInfo, GetIconInfo, HCURSOR, HICON, ICONINFO, IsIconic, WindowFromPoint,
},
},
};
/// Larger than any system cursor (the biggest accessibility size is 256 pixels at 100%).
const MAX_SHAPE_SIZE: u32 = 512;
/// What is being captured: the pointer is placed relative to it.
#[derive(Clone, Copy)]
pub(super) enum Target {
Display(HMONITOR),
Window(HWND),
}
// SAFETY: both are plain handles that are only passed back to Windows, which checks them.
unsafe impl Send for Target {}
pub(super) struct Pointer {
target: Target,
/// The last drawn cursor, rebuilt when Windows switches to another one.
shape: Option<Shape>,
}
struct Shape {
cursor: HCURSOR,
hotspot: (i32, i32),
width: usize,
height: usize,
/// Premultiplied BGRA.
pixels: Vec<u8>,
/// Pixels that invert what is under them (the parts of the text cursor that stay
/// readable on any background).
invert: Vec<bool>,
}
// SAFETY: the cursor handle is only compared, never drawn from another thread's state.
unsafe impl Send for Shape {}
impl Pointer {
pub(super) fn new(target: Target) -> Self {
Self { target, shape: None }
}
/// Draws the pointer into one BGRA frame of the target, if it is showing over it.
pub(super) fn draw(&mut self, frame: &mut [u8], width: u32, height: u32) {
// Cursor, monitor and window positions all in physical pixels, as captured.
// SAFETY: changes this thread's awareness only, and it is restored below.
let previous =
unsafe { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) };
self.draw_physical(frame, width, height);
if !previous.is_invalid() {
// SAFETY: as above.
unsafe { SetThreadDpiAwarenessContext(previous) };
}
}
fn draw_physical(&mut self, frame: &mut [u8], width: u32, height: u32) {
let mut info = CURSORINFO { cbSize: size_of::<CURSORINFO>() as u32, ..Default::default() };
// SAFETY: `info` is a correctly sized CURSORINFO.
if unsafe { GetCursorInfo(&mut info) }.is_err()
|| info.flags.0 & CURSOR_SHOWING.0 == 0
|| info.hCursor.is_invalid()
{
return;
}
let point = info.ptScreenPos;
let Some(bounds) = self.bounds(point) else {
return;
};
let (bounds_width, bounds_height) = (bounds.right - bounds.left, bounds.bottom - bounds.top);
if bounds_width <= 0
|| bounds_height <= 0
|| !(bounds.left..bounds.right).contains(&point.x)
|| !(bounds.top..bounds.bottom).contains(&point.y)
{
return;
}
if self.shape.as_ref().is_none_or(|shape| shape.cursor != info.hCursor) {
self.shape = Shape::read(info.hCursor);
}
let Some(shape) = &self.shape else {
return;
};
// The frame can briefly lag a resize; place the pointer proportionally.
let x = i64::from(point.x - bounds.left) * i64::from(width) / i64::from(bounds_width);
let y = i64::from(point.y - bounds.top) * i64::from(height) / i64::from(bounds_height);
shape.blend(
frame,
(width as usize, height as usize),
(x - i64::from(shape.hotspot.0), y - i64::from(shape.hotspot.1)),
);
}
/// The target's screen rectangle, or `None` when the pointer is not over it.
fn bounds(&self, point: POINT) -> Option<RECT> {
match self.target {
Target::Display(monitor) => {
let mut info =
MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, ..Default::default() };
// SAFETY: `info` is a correctly sized MONITORINFO; a stale handle only fails.
unsafe { GetMonitorInfoW(monitor, &mut info) }.as_bool().then_some(info.rcMonitor)
}
Target::Window(window) => {
// SAFETY: stale or foreign handles only make these calls fail or return null.
unsafe {
if IsIconic(window).as_bool() {
return None;
}
// Another window on top hides the pointer, as it hides the window; the
// target's own popups (menus, tooltips) do not.
let under = GetAncestor(WindowFromPoint(point), GA_ROOTOWNER);
if under != GetAncestor(window, GA_ROOTOWNER) {
return None;
}
// The area Windows Graphics Capture records: the window without its shadow.
let mut bounds = RECT::default();
DwmGetWindowAttribute(
window,
DWMWA_EXTENDED_FRAME_BOUNDS,
(&raw mut bounds).cast(),
size_of::<RECT>() as u32,
)
.ok()?;
Some(bounds)
}
}
}
}
}
impl Shape {
/// Renders `cursor` on black and on white: the difference gives each pixel's coverage,
/// which works the same for colour, alpha and monochrome cursors.
fn read(cursor: HCURSOR) -> Option<Self> {
let icon = HICON(cursor.0);
let mut info = ICONINFO::default();
// SAFETY: `info` receives two bitmaps this function owns and deletes below.
unsafe { GetIconInfo(icon, &mut info) }.ok()?;
let size = |bitmap| {
let mut header = BITMAP::default();
// SAFETY: writes at most `size_of::<BITMAP>()` bytes into `header`.
let written = unsafe {
GetObjectW(bitmap, size_of::<BITMAP>() as i32, Some((&raw mut header).cast()))
};
(written > 0).then_some((header.bmWidth, header.bmHeight))
};
let dimensions = if info.hbmColor.is_invalid() {
// A monochrome cursor stacks its AND mask above its XOR mask.
size(info.hbmMask.into()).map(|(width, height)| (width, height / 2))
} else {
size(info.hbmColor.into())
};
// SAFETY: GetIconInfo handed over both bitmaps; deleting a null one is a no-op.
unsafe {
let _ = DeleteObject(info.hbmColor.into());
let _ = DeleteObject(info.hbmMask.into());
}
let (width, height) = dimensions?;
let (width, height) = (u32::try_from(width).ok()?, u32::try_from(height).ok()?);
if width == 0 || height == 0 || width > MAX_SHAPE_SIZE || height > MAX_SHAPE_SIZE {
return None;
}
let on_black = render(icon, width, height, 0x00)?;
let on_white = render(icon, width, height, 0xFF)?;
let count = width as usize * height as usize;
let mut pixels = Vec::with_capacity(count * 4);
let mut invert = Vec::with_capacity(count);
for (black, white) in on_black.as_chunks::<4>().0.iter().zip(on_white.as_chunks::<4>().0) {
// Covered pixels look the same on both; uncovered ones show the background.
let shown = (0..3).map(|i| i32::from(white[i]) - i32::from(black[i])).max().unwrap_or(0);
if shown < 0 {
// Black on white and white on black: the pixel inverts its background.
pixels.extend_from_slice(&[0; 4]);
invert.push(true);
continue;
}
let alpha = (255 - shown.min(255)) as u8;
pixels.extend_from_slice(&[
black[0].min(alpha),
black[1].min(alpha),
black[2].min(alpha),
alpha,
]);
invert.push(false);
}
Some(Self {
cursor,
hotspot: (info.xHotspot as i32, info.yHotspot as i32),
width: width as usize,
height: height as usize,
pixels,
invert,
})
}
/// Blends the pointer into `frame` with its top-left corner at `origin`, clipped.
fn blend(&self, frame: &mut [u8], (width, height): (usize, usize), origin: (i64, i64)) {
if frame.len() < width * height * 4 {
return;
}
for row in 0..self.height {
let Ok(y) = usize::try_from(origin.1 + row as i64) else {
continue;
};
if y >= height {
break;
}
for column in 0..self.width {
let Ok(x) = usize::try_from(origin.0 + column as i64) else {
continue;
};
if x >= width {
break;
}
let source = row * self.width + column;
let target = &mut frame[(y * width + x) * 4..][..3];
if self.invert[source] {
for channel in target {
*channel = 255 - *channel;
}
continue;
}
let pixel = &self.pixels[source * 4..][..4];
let behind = 255 - u16::from(pixel[3]);
if behind == 255 {
continue;
}
for (channel, &colour) in target.iter_mut().zip(pixel) {
*channel = (u16::from(colour) + (u16::from(*channel) * behind + 127) / 255) as u8;
}
}
}
}
}
/// `icon` drawn at its own size onto a `background`-filled 32-bit bitmap, as BGRA rows.
fn render(icon: HICON, width: u32, height: u32, background: u8) -> Option<Vec<u8>> {
let header = BITMAPINFOHEADER {
biSize: size_of::<BITMAPINFOHEADER>() as u32,
biWidth: width as i32,
// Negative: rows top to bottom, like the captured frame.
biHeight: -(height as i32),
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB.0,
..Default::default()
};
let info = BITMAPINFO { bmiHeader: header, ..Default::default() };
let len = width as usize * height as usize * 4;
// SAFETY: the bitmap's `len` bytes of pixels stay valid until it is deleted, after they are
// copied out; the device context and bitmap are released on every path.
unsafe {
let dc = CreateCompatibleDC(None);
if dc.is_invalid() {
return None;
}
let mut bits = std::ptr::null_mut();
let Ok(bitmap) = CreateDIBSection(Some(dc), &info, DIB_RGB_COLORS, &mut bits, None, 0)
else {
let _ = DeleteDC(dc);
return None;
};
let previous = SelectObject(dc, bitmap.into());
std::ptr::write_bytes(bits.cast::<u8>(), background, len);
let drawn =
DrawIconEx(dc, 0, 0, icon, width as i32, height as i32, 0, None, DI_NORMAL).is_ok();
let _ = GdiFlush();
let pixels = drawn.then(|| std::slice::from_raw_parts(bits.cast::<u8>(), len).to_vec());
SelectObject(dc, previous);
let _ = DeleteObject(bitmap.into());
let _ = DeleteDC(dc);
pixels
}
}
#[cfg(test)]
mod tests {
use super::*;
fn shape(pixels: Vec<u8>, invert: Vec<bool>) -> Shape {
Shape {
cursor: HCURSOR::default(),
hotspot: (0, 0),
width: 2,
height: 1,
pixels,
invert,
}
}
#[test]
fn blends_premultiplied_and_inverts() {
// An opaque white pixel and an inverting one.
let pointer = shape(vec![255, 255, 255, 255, 0, 0, 0, 0], vec![false, true]);
let mut frame = vec![10, 20, 30, 255, 10, 20, 30, 255];
pointer.blend(&mut frame, (2, 1), (0, 0));
assert_eq!(frame, [255, 255, 255, 255, 245, 235, 225, 255]);
}
#[test]
fn clips_at_every_edge() {
let pointer = shape(vec![255; 8], vec![false; 2]);
let mut frame = vec![0; 8];
pointer.blend(&mut frame, (2, 1), (-1, 0));
assert_eq!(frame, [255, 255, 255, 0, 0, 0, 0, 0]);
let mut frame = vec![0; 8];
pointer.blend(&mut frame, (2, 1), (1, 0));
assert_eq!(frame, [0, 0, 0, 0, 255, 255, 255, 0]);
let mut frame = vec![0; 8];
pointer.blend(&mut frame, (2, 1), (0, 1));
assert_eq!(frame, [0; 8]);
}
#[test]
fn system_arrow_has_coverage() {
use windows::Win32::UI::WindowsAndMessaging::{IDC_ARROW, LoadCursorW};
// SAFETY: a shared system cursor, never destroyed.
let arrow = unsafe { LoadCursorW(None, IDC_ARROW) }.expect("arrow cursor");
let shape = Shape::read(arrow).expect("arrow shape");
assert!(shape.width >= 16 && shape.height >= 16);
assert!(shape.pixels.as_chunks::<4>().0.iter().any(|pixel| pixel[3] == 255));
assert!(shape.pixels.as_chunks::<4>().0.iter().any(|pixel| pixel[3] == 0));
}
}