taskbar-focus 0.5.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! The Win32 user interface: tray icon, taskbar title window, settings.
//!
//! This layer owns no policy. It turns clicks, hotkeys and timer ticks into
//! [`crate::cli::Command`]s for the orchestrator, and renders whatever
//! [`crate::orchestrator::UiEvent`]s come back.

pub mod alert;
pub mod app;
pub mod confirm;
pub mod fluent;
pub mod hotkeys;
pub mod icon;
pub mod lock_card;
pub mod mini;
pub mod settings;
pub mod shortcuts;
pub mod tray;

use windows::core::PCWSTR;

/// A NUL-terminated UTF-16 string that stays alive as long as you hold it.
pub struct WideStr(Vec<u16>);

impl WideStr {
    pub fn new(s: &str) -> Self {
        WideStr(s.encode_utf16().chain(std::iter::once(0)).collect())
    }

    pub fn as_pcwstr(&self) -> PCWSTR {
        PCWSTR(self.0.as_ptr())
    }
}

pub fn wide(s: &str) -> WideStr {
    WideStr::new(s)
}

/// How large pop-up headers draw the application icon, in pixels.
const HEADER_ICON: i32 = 20;

/// The application icon at `size` pixels, picked from the sizes in the
/// executable rather than scaled from a larger one.
///
/// Each size is loaded once and kept for the life of the process, like
/// [`app::shared_icon`]; only a few sizes are ever asked for.
pub fn app_icon(size: i32) -> windows::Win32::UI::WindowsAndMessaging::HICON {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};
    use windows::Win32::System::LibraryLoader::GetModuleHandleW;
    use windows::Win32::UI::WindowsAndMessaging::{LoadImageW, HICON, IMAGE_ICON, LR_DEFAULTCOLOR};
    static ICONS: OnceLock<Mutex<HashMap<i32, isize>>> = OnceLock::new();
    let mut icons = ICONS
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let raw = *icons.entry(size).or_insert_with(|| unsafe {
        let instance = GetModuleHandleW(None).unwrap_or_default();
        LoadImageW(
            Some(instance.into()),
            PCWSTR(1 as *const u16),
            IMAGE_ICON,
            size,
            size,
            LR_DEFAULTCOLOR,
        )
        .map_or_else(|_| app::shared_icon().0 as isize, |h| h.0 as isize)
    });
    HICON(raw as *mut _)
}

/// The application icon as a bitmap with transparency, at the size menus show
/// icons, for the first line of the tray menu.
pub fn menu_icon() -> windows::Win32::Graphics::Gdi::HBITMAP {
    use std::sync::OnceLock;
    use windows::Win32::Graphics::Gdi::{
        CreateCompatibleDC, CreateDIBSection, DeleteDC, GetDC, ReleaseDC, SelectObject, BITMAPINFO,
        BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HBITMAP,
    };
    use windows::Win32::UI::WindowsAndMessaging::{
        DrawIconEx, GetSystemMetrics, DI_NORMAL, SM_CXSMICON,
    };
    static BITMAP: OnceLock<isize> = OnceLock::new();
    let raw = *BITMAP.get_or_init(|| unsafe {
        let size = GetSystemMetrics(SM_CXSMICON).max(16);
        let info = BITMAPINFO {
            bmiHeader: BITMAPINFOHEADER {
                biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
                biWidth: size,
                biHeight: -size,
                biPlanes: 1,
                biBitCount: 32,
                biCompression: BI_RGB.0,
                ..Default::default()
            },
            ..Default::default()
        };
        let screen = GetDC(None);
        let mut bits = std::ptr::null_mut();
        let bitmap = CreateDIBSection(Some(screen), &info, DIB_RGB_COLORS, &mut bits, None, 0);
        let bitmap = match bitmap {
            Ok(b) => b,
            Err(_) => {
                ReleaseDC(None, screen);
                return 0;
            }
        };
        let dc = CreateCompatibleDC(Some(screen));
        let old = SelectObject(dc, bitmap.into());
        let _ = DrawIconEx(dc, 0, 0, app_icon(size), size, size, 0, None, DI_NORMAL);
        SelectObject(dc, old);
        let _ = DeleteDC(dc);
        ReleaseDC(None, screen);
        bitmap.0 as isize
    });
    HBITMAP(raw as *mut _)
}

/// Paint the first line of a pop-up: the application icon, then the app's name
/// and `topic`, as in "TASKBAR FOCUS ยท PC LOCK". The icon sits at the left of
/// `row`, centred in its height.
///
/// # Safety
/// `hdc` must be a device context being painted.
pub unsafe fn paint_header(
    hdc: windows::Win32::Graphics::Gdi::HDC,
    row: windows::Win32::Foundation::RECT,
    font: windows::Win32::Graphics::Gdi::HFONT,
    color: windows::Win32::Foundation::COLORREF,
    topic: &str,
) {
    use windows::Win32::Graphics::Gdi::{
        DrawTextW, SelectObject, SetBkMode, SetTextColor, DT_END_ELLIPSIS, DT_LEFT, DT_NOPREFIX,
        DT_SINGLELINE, DT_VCENTER, TRANSPARENT,
    };
    use windows::Win32::UI::WindowsAndMessaging::{DrawIconEx, DI_NORMAL};
    let top = row.top + (row.bottom - row.top - HEADER_ICON) / 2;
    let _ = DrawIconEx(
        hdc,
        row.left,
        top,
        app_icon(HEADER_ICON),
        HEADER_ICON,
        HEADER_ICON,
        0,
        None,
        DI_NORMAL,
    );
    let old = SelectObject(hdc, font.into());
    SetTextColor(hdc, color);
    SetBkMode(hdc, TRANSPARENT);
    let label = format!("{} \u{00B7} {topic}", crate::APP_NAME.to_uppercase());
    let mut units: Vec<u16> = label.encode_utf16().collect();
    let mut rc = row;
    rc.left += HEADER_ICON + 8;
    DrawTextW(
        hdc,
        &mut units,
        &mut rc,
        DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS,
    );
    SelectObject(hdc, old);
}