use std::path::PathBuf;
#[cfg(windows)]
use std::sync::{Arc, Mutex};
use std::time::Duration;
use serde::{Deserialize, Serialize};
pub(crate) const SUPPORTED: bool = cfg!(windows);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Shortcut {
Off,
CtrlShiftPrintScreen,
CtrlPrintScreen,
ShiftPrintScreen,
CtrlAltPrintScreen,
}
impl Shortcut {
pub(crate) const ALL: [Self; 5] = [
Self::CtrlShiftPrintScreen,
Self::CtrlPrintScreen,
Self::ShiftPrintScreen,
Self::CtrlAltPrintScreen,
Self::Off,
];
pub(crate) fn label(self) -> &'static str {
match self {
Self::Off => "Off",
Self::CtrlShiftPrintScreen => "Ctrl+Shift+PrtScn",
Self::CtrlPrintScreen => "Ctrl+PrtScn",
Self::ShiftPrintScreen => "Shift+PrtScn",
Self::CtrlAltPrintScreen => "Ctrl+Alt+PrtScn",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Target {
Foreground,
Pointer,
}
pub(crate) type Taken = Result<PathBuf, String>;
pub(crate) fn default_folder() -> Option<PathBuf> {
#[cfg(windows)]
return imp::pictures().map(|p| p.join("hdrshot"));
#[cfg(not(windows))]
None
}
pub(crate) struct Hotkey {
#[cfg(windows)]
thread: imp::HotkeyThread,
}
impl Hotkey {
#[cfg(windows)]
pub(crate) fn register(
shortcut: Shortcut,
folder: Arc<Mutex<PathBuf>>,
taken: std::sync::mpsc::Sender<Taken>,
ctx: egui::Context,
) -> Result<Self, String> {
imp::HotkeyThread::start(shortcut, folder, taken, ctx).map(|thread| Self { thread })
}
}
#[cfg(windows)]
impl Drop for Hotkey {
fn drop(&mut self) {
self.thread.stop();
}
}
#[cfg_attr(not(windows), allow(unused_variables))]
pub(crate) fn take_later(
delay: Duration,
target: Target,
folder: PathBuf,
taken: std::sync::mpsc::Sender<Taken>,
ctx: egui::Context,
) {
std::thread::spawn(move || {
std::thread::sleep(delay);
#[cfg(windows)]
let outcome = imp::take(target, &folder);
#[cfg(not(windows))]
let outcome = Err("Screenshots need Windows".to_owned());
if taken.send(outcome).is_ok() {
ctx.request_repaint();
}
});
}
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn file_stem(title: &str, time: [u16; 6]) -> String {
let mut name: String = title
.chars()
.map(|c| match c {
'<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' => ' ',
c if c.is_control() => ' ',
c => c,
})
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if name.chars().count() > 60 {
name = name
.chars()
.take(60)
.collect::<String>()
.trim_end()
.to_owned();
}
let name = name.trim_end_matches('.');
let name = if name.is_empty() { "Screenshot" } else { name };
let [y, mo, d, h, mi, s] = time;
format!("{name} {y:04}-{mo:02}-{d:02} {h:02}-{mi:02}-{s:02}")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) enum Rotation {
None,
Cw90,
Cw180,
Cw270,
}
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn rotate<T: Copy>(
pixels: &mut Vec<T>,
width: usize,
height: usize,
rotation: Rotation,
) -> (usize, usize) {
let (w, h) = match rotation {
Rotation::None => return (width, height),
Rotation::Cw180 => (width, height),
Rotation::Cw90 | Rotation::Cw270 => (height, width),
};
let source = |x: usize, y: usize| {
let (sx, sy) = match rotation {
Rotation::Cw90 => (y, height - 1 - x),
Rotation::Cw180 => (width - 1 - x, height - 1 - y),
_ => (width - 1 - y, x),
};
sy * width + sx
};
let turned = (0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.map(|(x, y)| pixels[source(x, y)])
.collect();
*pixels = turned;
(w, h)
}
#[cfg(windows)]
mod imp {
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Sender, sync_channel};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use windows::Win32::Foundation::{
E_ACCESSDENIED, GENERIC_WRITE, HMODULE, HWND, LPARAM, POINT, WPARAM,
};
use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_UNKNOWN;
use windows::Win32::Graphics::Direct3D11::{
D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,
D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
};
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_MODE_ROTATION_ROTATE90, DXGI_MODE_ROTATION_ROTATE180,
DXGI_MODE_ROTATION_ROTATE270,
};
use windows::Win32::Graphics::Dxgi::{
CreateDXGIFactory1, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE,
DXGI_ERROR_SESSION_DISCONNECTED, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT,
DXGI_OUTDUPL_FRAME_INFO, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput, IDXGIOutput5,
IDXGIOutputDuplication, IDXGIResource,
};
use windows::Win32::Graphics::Gdi::{
HMONITOR, MONITOR_DEFAULTTOPRIMARY, MonitorFromPoint, MonitorFromWindow,
};
use windows::Win32::Graphics::Imaging::{
CLSID_WICImagingFactory, GUID_ContainerFormatWmp, GUID_WICPixelFormat64bppRGBAHalf,
IWICBitmapFrameEncode, IWICImagingFactory, WICBitmapEncoderNoCache,
};
use windows::Win32::System::Com::StructuredStorage::{IPropertyBag2, PROPBAG2};
use windows::Win32::System::Com::{
CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree,
};
use windows::Win32::System::SystemInformation::GetLocalTime;
use windows::Win32::System::Threading::GetCurrentThreadId;
use windows::Win32::System::Variant::VARIANT;
use windows::Win32::UI::Input::KeyboardAndMouse::{
HOT_KEY_MODIFIERS, MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, RegisterHotKey,
UnregisterHotKey, VK_SNAPSHOT,
};
use windows::Win32::UI::Shell::{FOLDERID_Pictures, KF_FLAG_DEFAULT, SHGetKnownFolderPath};
use windows::Win32::UI::WindowsAndMessaging::{
GetCursorPos, GetForegroundWindow, GetMessageW, GetWindowTextW, MSG, PM_NOREMOVE,
PeekMessageW, PostThreadMessageW, WM_HOTKEY, WM_QUIT, WM_USER,
};
use windows::core::{GUID, HSTRING, Interface, PCWSTR, w};
use super::{Rotation, Shortcut, Taken, Target, file_stem, rotate};
const HOTKEY_ID: i32 = 1;
pub struct HotkeyThread {
id: u32,
handle: Option<JoinHandle<()>>,
}
impl HotkeyThread {
pub fn start(
shortcut: Shortcut,
folder: Arc<Mutex<PathBuf>>,
taken: Sender<Taken>,
ctx: egui::Context,
) -> Result<Self, String> {
let modifiers = match shortcut {
Shortcut::Off => return Err("No shortcut".to_owned()),
Shortcut::CtrlShiftPrintScreen => MOD_CONTROL | MOD_SHIFT,
Shortcut::CtrlPrintScreen => MOD_CONTROL,
Shortcut::ShiftPrintScreen => MOD_SHIFT,
Shortcut::CtrlAltPrintScreen => MOD_CONTROL | MOD_ALT,
};
let (ready, registered) = sync_channel(1);
let handle = std::thread::spawn(move || {
unsafe {
let mut msg = MSG::default();
let _ = PeekMessageW(&mut msg, None, WM_USER, WM_USER, PM_NOREMOVE);
let modifiers = HOT_KEY_MODIFIERS(modifiers.0 | MOD_NOREPEAT.0);
let result =
RegisterHotKey(None, HOTKEY_ID, modifiers, u32::from(VK_SNAPSHOT.0));
let ok = result.is_ok();
let _ = ready.send(result.map(|()| GetCurrentThreadId()));
if !ok {
return;
}
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
if msg.message == WM_HOTKEY {
let dir = folder.lock().map(|d| d.clone()).unwrap_or_default();
if taken.send(take(Target::Foreground, &dir)).is_ok() {
ctx.request_repaint();
}
}
}
let _ = UnregisterHotKey(None, HOTKEY_ID);
}
});
match registered.recv() {
Ok(Ok(id)) => Ok(Self {
id,
handle: Some(handle),
}),
_ => {
let _ = handle.join();
Err(format!(
"{} is taken by another app. Choose another shortcut.",
shortcut.label()
))
}
}
}
pub fn stop(&mut self) {
unsafe {
let _ = PostThreadMessageW(self.id, WM_QUIT, WPARAM(0), LPARAM(0));
}
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
pub fn pictures() -> Option<PathBuf> {
unsafe {
let path = SHGetKnownFolderPath(&FOLDERID_Pictures, KF_FLAG_DEFAULT, None).ok()?;
let text = path.to_string().ok();
CoTaskMemFree(Some(path.0 as *const _));
text.map(PathBuf::from)
}
}
pub fn take(target: Target, folder: &Path) -> Taken {
let (monitor, title) = unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
match target {
Target::Foreground => {
let window = GetForegroundWindow();
(
MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY),
window_title(window),
)
}
Target::Pointer => {
let mut point = POINT::default();
let _ = GetCursorPos(&mut point);
(
MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY),
String::new(),
)
}
}
};
let frame = capture(monitor).map_err(|e| describe(&e))?;
std::fs::create_dir_all(folder)
.map_err(|e| format!("Can't make {}: {e}", folder.display()))?;
let now = unsafe { GetLocalTime() };
let stem = file_stem(
&title,
[
now.wYear,
now.wMonth,
now.wDay,
now.wHour,
now.wMinute,
now.wSecond,
],
);
let mut path = folder.join(format!("{stem}.jxr"));
let mut n = 2;
while path.exists() {
path = folder.join(format!("{stem} ({n}).jxr"));
n += 1;
}
let partial = path.with_extension("jxr.partial");
let written = save_jxr(&frame, &partial);
if let Err(e) = written {
let _ = std::fs::remove_file(&partial);
return Err(format!("Couldn't save the screenshot: {}", e.message()));
}
std::fs::rename(&partial, &path).map_err(|e| {
let _ = std::fs::remove_file(&partial);
format!("Couldn't save the screenshot: {e}")
})?;
Ok(path)
}
fn window_title(window: HWND) -> String {
let mut text = [0u16; 256];
let len = unsafe { GetWindowTextW(window, &mut text) };
let title = String::from_utf16_lossy(&text[..len.max(0) as usize]);
if title == "Program Manager" {
String::new()
} else {
title
}
}
fn describe(e: &windows::core::Error) -> String {
let code = e.code();
if code == E_ACCESSDENIED {
"Windows doesn't allow screenshots right now, e.g. while a UAC prompt or \
the lock screen shows"
.to_owned()
} else if code == DXGI_ERROR_UNSUPPORTED {
"Windows can't capture this screen with this graphics driver".to_owned()
} else if code == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE {
"Too many apps are capturing the screen right now".to_owned()
} else if code == DXGI_ERROR_SESSION_DISCONNECTED || code == DXGI_ERROR_ACCESS_LOST {
"The screen changed while taking the screenshot. Try again.".to_owned()
} else {
format!("Couldn't capture the screen: {}", e.message())
}
}
struct Frame {
width: usize,
height: usize,
pixels: Vec<[u16; 4]>,
}
const HALF_ONE: u16 = 0x3c00;
const FRAME_WAIT_MS: u32 = 250;
fn capture(monitor: HMONITOR) -> windows::core::Result<Frame> {
unsafe {
let (adapter, output) = find_output(monitor)?;
let output: IDXGIOutput5 = output.cast().map_err(|_| {
windows::core::Error::new(
DXGI_ERROR_UNSUPPORTED,
"HDR screenshots need Windows 10 version 1703 or later",
)
})?;
let mut device: Option<ID3D11Device> = None;
let mut context: Option<ID3D11DeviceContext> = None;
D3D11CreateDevice(
&adapter,
D3D_DRIVER_TYPE_UNKNOWN,
HMODULE::default(),
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
None,
D3D11_SDK_VERSION,
Some(&mut device),
None,
Some(&mut context),
)?;
let device = device.expect("D3D11CreateDevice made a device");
let context = context.expect("D3D11CreateDevice made a context");
let duplication =
output.DuplicateOutput1(&device, 0, &[DXGI_FORMAT_R16G16B16A16_FLOAT])?;
let rotation = match duplication.GetDesc().Rotation {
DXGI_MODE_ROTATION_ROTATE90 => Rotation::Cw90,
DXGI_MODE_ROTATION_ROTATE180 => Rotation::Cw180,
DXGI_MODE_ROTATION_ROTATE270 => Rotation::Cw270,
_ => Rotation::None,
};
let staging = newest_frame(&duplication, &device, &context)?;
let mut desc = D3D11_TEXTURE2D_DESC::default();
staging.GetDesc(&mut desc);
if desc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT {
return Err(windows::core::Error::new(
DXGI_ERROR_UNSUPPORTED,
"Windows gave the screen in a format other than 16-bit float",
));
}
let (width, height) = (desc.Width as usize, desc.Height as usize);
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;
let mut pixels = Vec::with_capacity(width * height);
for y in 0..height {
let row = (mapped.pData as *const u8).add(y * mapped.RowPitch as usize);
let row = std::slice::from_raw_parts(row as *const [u16; 4], width);
pixels.extend(row.iter().map(|&[r, g, b, _]| [r, g, b, HALF_ONE]));
}
context.Unmap(&staging, 0);
let (width, height) = rotate(&mut pixels, width, height, rotation);
Ok(Frame {
width,
height,
pixels,
})
}
}
unsafe fn find_output(
monitor: HMONITOR,
) -> windows::core::Result<(IDXGIAdapter1, IDXGIOutput)> {
unsafe {
let factory: IDXGIFactory1 = CreateDXGIFactory1()?;
let mut first = None;
let mut a = 0;
while let Ok(adapter) = factory.EnumAdapters1(a) {
let mut o = 0;
while let Ok(output) = adapter.EnumOutputs(o) {
if output.GetDesc()?.Monitor == monitor {
return Ok((adapter, output));
}
if first.is_none() {
first = Some((adapter.clone(), output));
}
o += 1;
}
a += 1;
}
first
.ok_or_else(|| windows::core::Error::new(DXGI_ERROR_UNSUPPORTED, "No screen found"))
}
}
unsafe fn newest_frame(
duplication: &IDXGIOutputDuplication,
device: &ID3D11Device,
context: &ID3D11DeviceContext,
) -> windows::core::Result<ID3D11Texture2D> {
unsafe {
let mut staging: Option<ID3D11Texture2D> = None;
for _ in 0..4 {
let mut info = DXGI_OUTDUPL_FRAME_INFO::default();
let mut resource: Option<IDXGIResource> = None;
match duplication.AcquireNextFrame(FRAME_WAIT_MS, &mut info, &mut resource) {
Ok(()) => {}
Err(e) if e.code() == DXGI_ERROR_WAIT_TIMEOUT => {
if staging.is_some() {
break;
}
continue;
}
Err(e) => return Err(e),
}
let presented = info.LastPresentTime != 0;
if let Some(resource) = resource
&& (presented || staging.is_none())
{
let texture: ID3D11Texture2D = resource.cast()?;
if staging.is_none() {
let mut desc = D3D11_TEXTURE2D_DESC::default();
texture.GetDesc(&mut desc);
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;
desc.MiscFlags = 0;
desc.MipLevels = 1;
desc.ArraySize = 1;
device.CreateTexture2D(&desc, None, Some(&mut staging))?;
}
context.CopyResource(staging.as_ref().expect("made above"), &texture);
}
duplication.ReleaseFrame()?;
if presented && staging.is_some() {
break;
}
}
staging.ok_or_else(|| {
windows::core::Error::new(
DXGI_ERROR_WAIT_TIMEOUT,
"The screen didn't show a picture in time",
)
})
}
}
fn save_jxr(frame: &Frame, path: &Path) -> windows::core::Result<()> {
unsafe {
let factory: IWICImagingFactory =
CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
let stream = factory.CreateStream()?;
let name = HSTRING::from(path.as_os_str());
stream.InitializeFromFilename(PCWSTR(name.as_ptr()), GENERIC_WRITE.0)?;
let encoder = factory.CreateEncoder(&GUID_ContainerFormatWmp, std::ptr::null())?;
encoder.Initialize(&stream, WICBitmapEncoderNoCache)?;
let mut encode: Option<IWICBitmapFrameEncode> = None;
let mut options: Option<IPropertyBag2> = None;
encoder.CreateNewFrame(&mut encode, &mut options)?;
let encode = encode.expect("CreateNewFrame made a frame");
if let Some(options) = &options {
let name = PROPBAG2 {
pstrName: windows::core::PWSTR(w!("ImageQuality").as_ptr() as *mut u16),
..Default::default()
};
options.Write(1, &name, &VARIANT::from(1.0f32))?;
}
encode.Initialize(options.as_ref())?;
encode.SetSize(frame.width as u32, frame.height as u32)?;
let wanted: GUID = GUID_WICPixelFormat64bppRGBAHalf;
let mut format = wanted;
encode.SetPixelFormat(&mut format)?;
if format != wanted {
return Err(windows::core::Error::new(
DXGI_ERROR_UNSUPPORTED,
"Windows' JPEG XR encoder doesn't take 16-bit float pixels",
));
}
let bytes = std::slice::from_raw_parts(
frame.pixels.as_ptr() as *const u8,
frame.pixels.len() * 8,
);
let stride = frame.width as u32 * 8;
let band = (16 * 1024 * 1024 / stride as usize).max(1);
for rows in bytes.chunks(band * stride as usize) {
encode.WritePixels(rows.len() as u32 / stride, stride, rows)?;
}
encode.Commit()?;
encoder.Commit()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jxr_round_trip() {
let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
let half = |v: f32| {
match v {
0.5 => 0x3800,
1.0 => 0x3c00,
_ => 0x4400,
}
};
let (width, height) = (16, 8);
let pixels = (0..width * height)
.map(|i| {
let v = [0.5, 1.0, 4.0][i % 3];
[half(v), half(1.0), half(0.5), HALF_ONE]
})
.collect();
let frame = Frame {
width,
height,
pixels,
};
let path =
std::env::temp_dir().join(format!("hdrshot-shot-{}.jxr", std::process::id()));
save_jxr(&frame, &path).unwrap();
let bytes = std::fs::read(&path).unwrap();
let image = hdrshot_core::decode::decode(&bytes).unwrap();
let _ = std::fs::remove_file(&path);
assert_eq!((image.width, image.height), (16, 8));
for (i, p) in image.pixels.iter().enumerate() {
let v = [0.5, 1.0, 4.0][i % 3];
assert!((p[0] - v).abs() < 1e-3, "{p:?} at {i}");
assert!((p[1] - 1.0).abs() < 1e-3 && (p[2] - 0.5).abs() < 1e-3);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_like_game_bar() {
let time = [2026, 11, 28, 9, 5, 2];
assert_eq!(
file_stem("Some Game", time),
"Some Game 2026-11-28 09-05-02"
);
assert_eq!(
file_stem(" A: B / C? ", time),
"A B C 2026-11-28 09-05-02"
);
assert_eq!(file_stem("", time), "Screenshot 2026-11-28 09-05-02");
assert_eq!(file_stem("...", time), "Screenshot 2026-11-28 09-05-02");
let long = "x".repeat(100);
assert_eq!(file_stem(&long, time).len(), 60 + 20);
}
#[test]
fn rotations() {
let image = vec!['a', 'b', 'c', 'd', 'e', 'f'];
let turned = |rotation| {
let mut pixels = image.clone();
let size = rotate(&mut pixels, 3, 2, rotation);
(size, pixels.into_iter().collect::<String>())
};
assert_eq!(turned(Rotation::None), ((3, 2), "abcdef".into()));
assert_eq!(turned(Rotation::Cw90), ((2, 3), "daebfc".into()));
assert_eq!(turned(Rotation::Cw180), ((3, 2), "fedcba".into()));
assert_eq!(turned(Rotation::Cw270), ((2, 3), "cfbead".into()));
}
}