use std::sync::Once;
use windows::core::PCWSTR;
use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows::Win32::Graphics::Dwm::{
DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND,
};
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::*;
use crate::lock::{Action, Card, CardKind};
use crate::os::localtime::format_when;
use crate::ui::alert::monitor_work;
use crate::ui::wide;
const CLASS: &str = "TaskbarFocusLockCard";
const DIM_CLASS: &str = "TaskbarFocusLockDim";
pub const WM_LOCK_CARD: u32 = WM_APP + 4;
const W: i32 = 460;
const H: i32 = 248;
const GAP: i32 = 12;
#[derive(Clone, PartialEq, Eq)]
pub struct Content {
pub title: String,
pub body: String,
pub buttons: Vec<String>,
pub dim: bool,
}
impl Content {
pub fn notice(title: &str, body: &str) -> Self {
Content {
title: title.into(),
body: body.into(),
buttons: vec!["Dismiss".into()],
dim: true,
}
}
pub fn of(card: &Card, now: i64) -> Self {
let at = format_when(card.at, now);
let seconds = card.seconds.unwrap_or(0);
let (title, body) = match card.kind {
CardKind::Cutoff { passed: false } => (
format!("PC locks at {at}"),
format!(
"It can be postponed or skipped until {}.",
format_when(card.cutoff, now)
),
),
CardKind::Cutoff { passed: true } => (
format!("PC locks at {at}"),
"The cutoff has passed, so it can no longer be postponed or skipped.".into(),
),
CardKind::Upcoming => ("PC locks soon".into(), format!("It locks at {at}.")),
CardKind::Late => (
format!("PC locks in {seconds} s"),
format!("The lock was due at {at}."),
),
CardKind::Startup => (
format!("PC locks in {seconds} s"),
format!("The locked period lasts until {at}."),
),
CardKind::Relock => (
format!("Locked until {at}"),
format!("The PC locks again in {seconds} s."),
),
CardKind::Failed => (
"The PC did not lock".into(),
format!("Windows did not respond. Trying again until {at}."),
),
};
Content {
title,
body,
buttons: card.actions.iter().map(|a| label(*a, card)).collect(),
dim: card.seconds.is_none(),
}
}
}
fn label(action: Action, card: &Card) -> String {
match action {
Action::Postpone => format!("Postpone {} min", card.postpone_minutes),
Action::SkipLate => "Skip today".into(),
Action::EndPeriod => "End locked period".into(),
Action::Dismiss => "Dismiss".into(),
}
}
struct State {
content: Content,
font_eyebrow: HFONT,
font_title: HFONT,
font_body: HFONT,
dim: Option<HWND>,
pressed: Option<usize>,
}
fn rgb(r: u8, g: u8, b: u8) -> COLORREF {
COLORREF((b as u32) << 16 | (g as u32) << 8 | r as u32)
}
fn button_rect(index: usize, count: usize) -> RECT {
let width = 172;
let from_right = (count - 1 - index) as i32;
let right = W - 24 - from_right * (width + GAP);
RECT {
left: right - width,
top: H - 58,
right,
bottom: H - 22,
}
}
fn register_classes() {
static ONCE: Once = Once::new();
ONCE.call_once(|| unsafe {
let Ok(instance) = GetModuleHandleW(None) else {
return;
};
let cursor = LoadCursorW(None, IDC_ARROW).unwrap_or_default();
let card = wide(CLASS);
let dim = wide(DIM_CLASS);
let base = WNDCLASSW {
hInstance: instance.into(),
hCursor: cursor,
hbrBackground: HBRUSH(GetStockObject(BLACK_BRUSH).0),
..Default::default()
};
RegisterClassW(&WNDCLASSW {
lpfnWndProc: Some(wndproc),
lpszClassName: card.as_pcwstr(),
hIcon: crate::ui::app::shared_icon(),
..base
});
RegisterClassW(&WNDCLASSW {
lpfnWndProc: Some(dim_wndproc),
lpszClassName: dim.as_pcwstr(),
..base
});
});
}
unsafe fn make_font(height: i32, weight: i32) -> HFONT {
let mut lf = LOGFONTW {
lfHeight: -height,
lfWeight: weight,
lfQuality: CLEARTYPE_QUALITY,
..Default::default()
};
for (slot, unit) in lf.lfFaceName.iter_mut().zip("Segoe UI".encode_utf16()) {
*slot = unit;
}
CreateFontIndirectW(&lf)
}
pub fn show(owner: HWND, anchor: HWND, content: Content) -> Option<HWND> {
register_classes();
unsafe {
let instance = GetModuleHandleW(None).ok()?;
let work = monitor_work(anchor);
let dim = if content.dim {
show_dim(owner, &work, instance.into())
} else {
None
};
let hwnd = CreateWindowExW(
WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
wide(CLASS).as_pcwstr(),
wide(&content.title).as_pcwstr(),
WS_POPUP,
work.left + ((work.right - work.left) - W) / 2,
work.top + ((work.bottom - work.top) - H) / 2,
W,
H,
Some(owner),
None,
Some(instance.into()),
None,
);
let Ok(hwnd) = hwnd else {
if let Some(d) = dim {
let _ = DestroyWindow(d);
}
return None;
};
let pref = DWMWCP_ROUND;
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_WINDOW_CORNER_PREFERENCE,
&pref as *const _ as *const _,
std::mem::size_of_val(&pref) as u32,
);
let st = Box::new(State {
content,
font_eyebrow: make_font(13, FW_SEMIBOLD.0 as i32),
font_title: make_font(30, FW_SEMIBOLD.0 as i32),
font_body: make_font(17, FW_NORMAL.0 as i32),
dim,
pressed: None,
});
SetWindowLongPtrW(hwnd, GWLP_USERDATA, Box::into_raw(st) as isize);
let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
Some(hwnd)
}
}
unsafe fn show_dim(
owner: HWND,
work: &RECT,
instance: windows::Win32::Foundation::HINSTANCE,
) -> Option<HWND> {
let hwnd = CreateWindowExW(
WS_EX_TOOLWINDOW | WS_EX_LAYERED | WS_EX_NOACTIVATE,
wide(DIM_CLASS).as_pcwstr(),
PCWSTR::null(),
WS_POPUP | WS_VISIBLE,
work.left,
work.top,
work.right - work.left,
work.bottom - work.top,
Some(owner),
None,
Some(instance),
None,
)
.ok()?;
let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 120, LWA_ALPHA);
Some(hwnd)
}
pub fn update(hwnd: HWND, content: Content) {
unsafe {
let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
if ptr.is_null() || (*ptr).content == content {
return;
}
(*ptr).content = content;
let _ = InvalidateRect(Some(hwnd), None, false);
}
}
pub fn close(hwnd: HWND) {
unsafe {
let _ = DestroyWindow(hwnd);
}
}
unsafe fn text(
hdc: HDC,
font: HFONT,
color: COLORREF,
s: &str,
mut rc: RECT,
how: DRAW_TEXT_FORMAT,
) {
let old = SelectObject(hdc, font.into());
SetTextColor(hdc, color);
let mut units: Vec<u16> = s.encode_utf16().collect();
DrawTextW(hdc, &mut units, &mut rc, how | DT_NOPREFIX);
SelectObject(hdc, old);
}
unsafe fn fill(hdc: HDC, rc: RECT, color: COLORREF) {
let brush = CreateSolidBrush(color);
FillRect(hdc, &rc, brush);
let _ = DeleteObject(brush.into());
}
unsafe fn paint(hdc: HDC, st: &State) {
let accent = rgb(0xE8, 0x56, 0x3F);
let rect = |left, top, right, bottom| RECT {
left,
top,
right,
bottom,
};
fill(hdc, rect(0, 0, W, H), rgb(0x22, 0x20, 0x1E));
fill(hdc, rect(0, 0, W, 5), accent);
fill(hdc, rect(28, H - 74, W - 28, H - 73), rgb(0x3A, 0x36, 0x32));
SetBkMode(hdc, TRANSPARENT);
crate::ui::paint_header(
hdc,
rect(28, 28, W - 28, 52),
st.font_eyebrow,
rgb(0xD2, 0xCB, 0xC4),
"PC LOCK",
);
text(
hdc,
st.font_title,
rgb(0xF7, 0xF5, 0xF2),
&st.content.title,
rect(28, 64, W - 28, 108),
DT_LEFT | DT_SINGLELINE | DT_END_ELLIPSIS,
);
text(
hdc,
st.font_body,
rgb(0xA8, 0xA2, 0x9C),
&st.content.body,
rect(28, 118, W - 28, H - 78),
DT_LEFT | DT_WORDBREAK,
);
let count = st.content.buttons.len();
for (i, label) in st.content.buttons.iter().enumerate() {
let main = i + 1 == count;
let pressed = st.pressed == Some(i);
let color = match (main, pressed) {
(true, false) => accent,
(true, true) => rgb(0xAE, 0x40, 0x2F),
(false, false) => rgb(0x3A, 0x36, 0x32),
(false, true) => rgb(0x2C, 0x29, 0x26),
};
let rc = button_rect(i, count);
let brush = CreateSolidBrush(color);
let pen = CreatePen(PS_SOLID, 1, color);
let old_brush = SelectObject(hdc, brush.into());
let old_pen = SelectObject(hdc, pen.into());
let _ = RoundRect(hdc, rc.left, rc.top, rc.right, rc.bottom, 10, 10);
SelectObject(hdc, old_brush);
SelectObject(hdc, old_pen);
let _ = DeleteObject(brush.into());
let _ = DeleteObject(pen.into());
text(
hdc,
st.font_body,
rgb(0xFF, 0xFF, 0xFF),
label,
rc,
DT_CENTER | DT_VCENTER | DT_SINGLELINE,
);
}
}
unsafe fn button_at(st: &State, lparam: LPARAM) -> Option<usize> {
let x = (lparam.0 & 0xFFFF) as i16 as i32;
let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;
let count = st.content.buttons.len();
(0..count).find(|&i| {
let rc = button_rect(i, count);
x >= rc.left && x < rc.right && y >= rc.top && y < rc.bottom
})
}
unsafe extern "system" fn dim_wndproc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
DefWindowProcW(hwnd, msg, wparam, lparam)
}
unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
if ptr.is_null() {
return DefWindowProcW(hwnd, msg, wparam, lparam);
}
let st = &mut *ptr;
match msg {
WM_ERASEBKGND => LRESULT(1),
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
let hdc = BeginPaint(hwnd, &mut ps);
let buffer = CreateCompatibleDC(Some(hdc));
let bitmap = CreateCompatibleBitmap(hdc, W, H);
let old = SelectObject(buffer, bitmap.into());
paint(buffer, st);
let _ = BitBlt(hdc, 0, 0, W, H, Some(buffer), 0, 0, SRCCOPY);
SelectObject(buffer, old);
let _ = DeleteObject(bitmap.into());
let _ = DeleteDC(buffer);
let _ = EndPaint(hwnd, &ps);
LRESULT(0)
}
WM_LBUTTONDOWN => {
st.pressed = button_at(st, lparam);
let _ = InvalidateRect(Some(hwnd), None, false);
LRESULT(0)
}
WM_LBUTTONUP => {
let was = st.pressed.take();
let _ = InvalidateRect(Some(hwnd), None, false);
if let (Some(i), Ok(owner)) = (was, GetWindow(hwnd, GW_OWNER)) {
if button_at(st, lparam) == Some(i) {
let _ = PostMessageW(
Some(owner),
WM_LOCK_CARD,
WPARAM(i),
LPARAM(hwnd.0 as isize),
);
}
}
LRESULT(0)
}
WM_CLOSE => LRESULT(0),
WM_DESTROY => {
SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
let st = Box::from_raw(ptr);
if let Some(dim) = st.dim {
let _ = DestroyWindow(dim);
}
let _ = DeleteObject(st.font_eyebrow.into());
let _ = DeleteObject(st.font_title.into());
let _ = DeleteObject(st.font_body.into());
LRESULT(0)
}
_ => DefWindowProcW(hwnd, msg, wparam, lparam),
}
}