use std::sync::mpsc::Sender;
pub(crate) const SUPPORTED: bool = cfg!(windows);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) enum TrayEvent {
Open,
TogglePause,
Screenshot,
RegionScreenshot,
Quit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum WatchItem {
None,
Pause,
Resume,
}
pub(crate) struct Tray {
#[cfg(windows)]
icon: imp::Icon,
}
impl Tray {
#[cfg_attr(not(windows), allow(unused_variables))]
pub(crate) fn new(events: Sender<TrayEvent>, ctx: egui::Context) -> Option<Self> {
#[cfg(windows)]
return imp::Icon::new(events, ctx).map(|icon| Self { icon });
#[cfg(not(windows))]
None
}
#[cfg_attr(not(windows), allow(unused_variables, clippy::unused_self))]
pub(crate) fn update(&self, tip: &str, watch: WatchItem) {
#[cfg(windows)]
self.icon.update(tip, watch);
}
#[cfg_attr(not(windows), allow(unused_variables, clippy::unused_self))]
pub(crate) fn notify(&self, title: &str, text: &str) {
#[cfg(windows)]
self.icon.notify(title, text);
}
}
#[cfg(windows)]
mod imp {
use std::cell::{Cell, RefCell};
use std::sync::mpsc::Sender;
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::Shell::{
NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_SHOWTIP, NIF_TIP, NIIF_LARGE_ICON,
NIIF_RESPECT_QUIET_TIME, NIIF_USER, NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETVERSION,
NIN_BALLOONUSERCLICK, NIN_SELECT, NOTIFY_ICON_DATA_FLAGS, NOTIFY_ICON_MESSAGE,
NOTIFYICON_VERSION_4, NOTIFYICONDATAW, Shell_NotifyIconW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
AppendMenuW, CreatePopupMenu, CreateWindowExW, DefWindowProcW, DestroyIcon, DestroyMenu,
DestroyWindow, GWLP_USERDATA, GetSystemMetrics, GetWindowLongPtrW, HICON, IDI_APPLICATION,
IMAGE_ICON, LR_DEFAULTCOLOR, LoadIconW, LoadImageW, MF_SEPARATOR, MF_STRING, PostMessageW,
RegisterClassW, RegisterWindowMessageW, SM_CXICON, SM_CXSMICON, SM_CYICON, SM_CYSMICON,
SM_MENUDROPALIGNMENT, SetForegroundWindow, SetMenuDefaultItem, SetWindowLongPtrW,
TPM_LEFTALIGN, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTALIGN, TPM_RIGHTBUTTON,
TrackPopupMenuEx, WM_APP, WM_CONTEXTMENU, WM_NULL, WNDCLASSW, WS_OVERLAPPED,
};
use super::{TrayEvent, WatchItem};
const CALLBACK: u32 = WM_APP + 1;
const NIN_KEYSELECT: u32 = NIN_SELECT | 1;
const ICON_ID: u32 = 1;
const APP_ICON: u16 = 1;
const OPEN: usize = 1;
const TOGGLE: usize = 2;
const QUIT: usize = 3;
const SCREENSHOT: usize = 4;
const REGION: usize = 5;
pub struct Icon {
hwnd: HWND,
state: *mut State,
}
struct State {
events: Sender<TrayEvent>,
ctx: egui::Context,
watch: Cell<WatchItem>,
tip: RefCell<String>,
small: HICON,
large: HICON,
taskbar_created: u32,
}
impl Icon {
pub fn new(events: Sender<TrayEvent>, ctx: egui::Context) -> Option<Self> {
let class = wide("hdrshot tray");
unsafe {
let instance = GetModuleHandleW(std::ptr::null());
let class_info = WNDCLASSW {
lpfnWndProc: Some(window_proc),
hInstance: instance,
lpszClassName: class.as_ptr(),
..std::mem::zeroed()
};
RegisterClassW(&class_info);
let hwnd = CreateWindowExW(
0,
class.as_ptr(),
wide("hdrshot").as_ptr(),
WS_OVERLAPPED,
0,
0,
0,
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
instance,
std::ptr::null(),
);
if hwnd.is_null() {
return None;
}
let load = |w, h| {
let icon = LoadImageW(
instance,
APP_ICON as usize as *const u16,
IMAGE_ICON,
GetSystemMetrics(w),
GetSystemMetrics(h),
LR_DEFAULTCOLOR,
);
if icon.is_null() {
LoadIconW(std::ptr::null_mut(), IDI_APPLICATION)
} else {
icon
}
};
let state = Box::into_raw(Box::new(State {
events,
ctx,
watch: Cell::new(WatchItem::None),
tip: RefCell::new("hdrshot".to_owned()),
small: load(SM_CXSMICON, SM_CYSMICON),
large: load(SM_CXICON, SM_CYICON),
taskbar_created: RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()),
}));
SetWindowLongPtrW(hwnd, GWLP_USERDATA, state as isize);
add(hwnd, &*state);
Some(Self { hwnd, state })
}
}
fn state(&self) -> &State {
unsafe { &*self.state }
}
pub fn update(&self, tip: &str, watch: WatchItem) {
let state = self.state();
state.watch.set(watch);
if *state.tip.borrow() == tip {
return;
}
*state.tip.borrow_mut() = tip.to_owned();
let mut data = data(self.hwnd, NIF_TIP | NIF_SHOWTIP);
copy(&mut data.szTip, tip);
notify_icon(NIM_MODIFY, &data);
}
pub fn notify(&self, title: &str, text: &str) {
let mut data = data(self.hwnd, NIF_INFO);
copy(&mut data.szInfoTitle, title);
copy(&mut data.szInfo, text);
data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON | NIIF_RESPECT_QUIET_TIME;
data.hBalloonIcon = self.state().large;
notify_icon(NIM_MODIFY, &data);
}
}
impl Drop for Icon {
fn drop(&mut self) {
notify_icon(NIM_DELETE, &data(self.hwnd, 0));
unsafe {
SetWindowLongPtrW(self.hwnd, GWLP_USERDATA, 0);
DestroyWindow(self.hwnd);
let state = Box::from_raw(self.state);
DestroyIcon(state.small);
DestroyIcon(state.large);
}
}
}
fn add(hwnd: HWND, state: &State) {
let mut data = data(hwnd, NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP);
data.uCallbackMessage = CALLBACK;
data.hIcon = state.small;
copy(&mut data.szTip, &state.tip.borrow());
if notify_icon(NIM_ADD, &data) {
data.Anonymous.uVersion = NOTIFYICON_VERSION_4;
notify_icon(NIM_SETVERSION, &data);
}
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
let state = unsafe { (GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const State).as_ref() };
let Some(state) = state else {
return unsafe { DefWindowProcW(hwnd, message, wparam, lparam) };
};
if message == CALLBACK {
match lparam as u32 & 0xffff {
NIN_SELECT | NIN_KEYSELECT | NIN_BALLOONUSERCLICK => state.send(TrayEvent::Open),
WM_CONTEXTMENU => {
let x = (wparam & 0xffff) as i16 as i32;
let y = ((wparam >> 16) & 0xffff) as i16 as i32;
if let Some(event) = menu(hwnd, state.watch.get(), x, y) {
state.send(event);
}
}
_ => {}
}
return 0;
}
if message == state.taskbar_created {
add(hwnd, state);
return 0;
}
unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
}
impl State {
fn send(&self, event: TrayEvent) {
if self.events.send(event).is_ok() {
self.ctx.request_repaint();
}
}
}
fn menu(hwnd: HWND, watch: WatchItem, x: i32, y: i32) -> Option<TrayEvent> {
unsafe {
let menu = CreatePopupMenu();
if menu.is_null() {
return None;
}
AppendMenuW(menu, MF_STRING, OPEN, wide("Open hdrshot").as_ptr());
AppendMenuW(
menu,
MF_STRING,
SCREENSHOT,
wide("Take an HDR screenshot").as_ptr(),
);
AppendMenuW(
menu,
MF_STRING,
REGION,
wide("Take a region screenshot").as_ptr(),
);
let watch_label = match watch {
WatchItem::None => None,
WatchItem::Pause => Some("Pause watching"),
WatchItem::Resume => Some("Resume watching"),
};
if let Some(label) = watch_label {
AppendMenuW(menu, MF_STRING, TOGGLE, wide(label).as_ptr());
}
AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null());
AppendMenuW(menu, MF_STRING, QUIT, wide("Quit hdrshot").as_ptr());
SetMenuDefaultItem(menu, OPEN as u32, 0);
let align = if GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0 {
TPM_RIGHTALIGN
} else {
TPM_LEFTALIGN
};
SetForegroundWindow(hwnd);
let choice = TrackPopupMenuEx(
menu,
align | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY,
x,
y,
hwnd,
std::ptr::null(),
);
PostMessageW(hwnd, WM_NULL, 0, 0);
DestroyMenu(menu);
match choice as usize {
OPEN => Some(TrayEvent::Open),
TOGGLE => Some(TrayEvent::TogglePause),
SCREENSHOT => Some(TrayEvent::Screenshot),
REGION => Some(TrayEvent::RegionScreenshot),
QUIT => Some(TrayEvent::Quit),
_ => None,
}
}
}
fn data(hwnd: HWND, flags: NOTIFY_ICON_DATA_FLAGS) -> NOTIFYICONDATAW {
NOTIFYICONDATAW {
cbSize: size_of::<NOTIFYICONDATAW>() as u32,
hWnd: hwnd,
uID: ICON_ID,
uFlags: flags,
..Default::default()
}
}
fn notify_icon(message: NOTIFY_ICON_MESSAGE, data: &NOTIFYICONDATAW) -> bool {
unsafe { Shell_NotifyIconW(message, data) != 0 }
}
fn copy(field: &mut [u16], text: &str) {
let mut units: Vec<u16> = text.encode_utf16().take(field.len() - 1).collect();
if units.last().is_some_and(|u| (0xd800..0xdc00).contains(u)) {
units.pop();
}
field[..units.len()].copy_from_slice(&units);
field[units.len()] = 0;
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain([0]).collect()
}
#[cfg(test)]
mod tests {
use super::copy;
#[test]
fn text_is_cut_to_fit() {
let mut field = [1; 8];
copy(&mut field, "hdrshot: watching");
assert_eq!(String::from_utf16(&field[..7]).unwrap(), "hdrshot");
assert_eq!(field[7], 0);
let mut field = [1; 4];
copy(&mut field, "ab\u{1F600}");
assert_eq!(field[..3], [u16::from(b'a'), u16::from(b'b'), 0]);
}
}
}