taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! Keyboard shortcuts inside the app's own menu and windows, which the user
//! can change or remove on the Hotkeys page of the settings window.
//!
//! [`ALL`] lists every shortcut once, with its label and where it is stored, so
//! the settings window, the checks on saving and the places that react to a
//! key all agree on what exists.

use windows::Win32::UI::Input::KeyboardAndMouse::{
    GetKeyState, MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN, VK_CONTROL, VK_LWIN, VK_MENU, VK_RWIN,
    VK_SHIFT,
};

use crate::config::Shortcuts;
use crate::ui::hotkeys;

/// Where a shortcut works, which decides what it may be.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Place {
    /// A line of the tray menu: one letter or digit.
    Menu,
    /// The compact timer window: any key, with or without modifiers.
    TimerWindow,
    /// The settings window: a key that does not get in the way of typing.
    Settings,
}

/// One changeable shortcut.
pub struct Shortcut {
    pub place: Place,
    pub label: &'static str,
    pub icon: &'static str,
    pub get: fn(&Shortcuts) -> &String,
    pub slot: fn(&mut Shortcuts) -> &mut String,
}

/// Every changeable shortcut, in the order the settings window shows them.
pub const ALL: [Shortcut; 19] = [
    Shortcut {
        place: Place::Menu,
        label: "Start focus",
        icon: "\u{E768}",
        get: |s| &s.menu.start_focus,
        slot: |s| &mut s.menu.start_focus,
    },
    Shortcut {
        place: Place::Menu,
        label: "Pause / resume",
        icon: "\u{E769}",
        get: |s| &s.menu.pause,
        slot: |s| &mut s.menu.pause,
    },
    Shortcut {
        place: Place::Menu,
        label: "Skip to next",
        icon: "\u{E893}",
        get: |s| &s.menu.skip,
        slot: |s| &mut s.menu.skip,
    },
    Shortcut {
        place: Place::Menu,
        label: "Stop",
        icon: "\u{E71A}",
        get: |s| &s.menu.stop,
        slot: |s| &mut s.menu.stop,
    },
    Shortcut {
        place: Place::Menu,
        label: "Start break",
        icon: "\u{EC32}",
        get: |s| &s.menu.start_break,
        slot: |s| &mut s.menu.start_break,
    },
    Shortcut {
        place: Place::Menu,
        label: "Preset menu",
        icon: "\u{E8FD}",
        get: |s| &s.menu.preset,
        slot: |s| &mut s.menu.preset,
    },
    Shortcut {
        place: Place::Menu,
        label: "Postpone the PC lock",
        icon: "\u{E823}",
        get: |s| &s.menu.postpone_lock,
        slot: |s| &mut s.menu.postpone_lock,
    },
    Shortcut {
        place: Place::Menu,
        label: "Skip the PC lock",
        icon: "\u{E711}",
        get: |s| &s.menu.skip_lock,
        slot: |s| &mut s.menu.skip_lock,
    },
    Shortcut {
        place: Place::Menu,
        label: "End the locked period",
        icon: "\u{E785}",
        get: |s| &s.menu.end_lock,
        slot: |s| &mut s.menu.end_lock,
    },
    Shortcut {
        place: Place::Menu,
        label: "Show or hide the timer window",
        icon: "\u{E7F4}",
        get: |s| &s.menu.timer_window,
        slot: |s| &mut s.menu.timer_window,
    },
    Shortcut {
        place: Place::Menu,
        label: "Reset the timer window's size",
        icon: "\u{E72C}",
        get: |s| &s.menu.reset_window,
        slot: |s| &mut s.menu.reset_window,
    },
    Shortcut {
        place: Place::Menu,
        label: "Settings",
        icon: "\u{E713}",
        get: |s| &s.menu.settings,
        slot: |s| &mut s.menu.settings,
    },
    Shortcut {
        place: Place::Menu,
        label: "Exit",
        icon: "\u{E7E8}",
        get: |s| &s.menu.exit,
        slot: |s| &mut s.menu.exit,
    },
    Shortcut {
        place: Place::TimerWindow,
        label: "Start, pause or resume",
        icon: "\u{E768}",
        get: |s| &s.timer_window.start_pause,
        slot: |s| &mut s.timer_window.start_pause,
    },
    Shortcut {
        place: Place::Settings,
        label: "Search settings",
        icon: "\u{E721}",
        get: |s| &s.settings.search,
        slot: |s| &mut s.settings.search,
    },
    Shortcut {
        place: Place::Settings,
        label: "Save",
        icon: "\u{E74E}",
        get: |s| &s.settings.save,
        slot: |s| &mut s.settings.save,
    },
    Shortcut {
        place: Place::Settings,
        label: "Close without saving",
        icon: "\u{E711}",
        get: |s| &s.settings.close,
        slot: |s| &mut s.settings.close,
    },
    Shortcut {
        place: Place::Settings,
        label: "Next page",
        icon: "\u{E76C}",
        get: |s| &s.settings.next_page,
        slot: |s| &mut s.settings.next_page,
    },
    Shortcut {
        place: Place::Settings,
        label: "Previous page",
        icon: "\u{E76B}",
        get: |s| &s.settings.previous_page,
        slot: |s| &mut s.settings.previous_page,
    },
];

/// The letter or digit of a tray menu line, or `None` when it has been
/// removed or shortcuts are off.
pub fn menu_letter(keys: &Shortcuts, value: &str) -> Option<char> {
    if !keys.enabled {
        return None;
    }
    letter(value)
}

/// `value` as a single letter or digit, upper case.
fn letter(value: &str) -> Option<char> {
    let mut chars = value.trim().chars();
    match (chars.next(), chars.next()) {
        (Some(c), None) if c.is_ascii_alphanumeric() => Some(c.to_ascii_uppercase()),
        _ => None,
    }
}

/// Whether the key `vk`, just pressed with the modifiers now held down, is the
/// shortcut `value`. Always false while shortcuts are off.
pub fn pressed(keys: &Shortcuts, value: &str, vk: u32) -> bool {
    if !keys.enabled {
        return false;
    }
    let Some(accel) = hotkeys::parse_any(value) else {
        return false;
    };
    accel.vk == vk && accel.modifiers == held_modifiers()
}

/// The modifier keys held down right now, as `MOD_*` flags.
pub fn held_modifiers() -> u32 {
    let down = |vk: u16| unsafe { GetKeyState(i32::from(vk)) } < 0;
    let mut held = 0;
    if down(VK_CONTROL.0) {
        held |= MOD_CONTROL.0;
    }
    if down(VK_MENU.0) {
        held |= MOD_ALT.0;
    }
    if down(VK_SHIFT.0) {
        held |= MOD_SHIFT.0;
    }
    if down(VK_LWIN.0) || down(VK_RWIN.0) {
        held |= MOD_WIN.0;
    }
    held
}

/// Check shortcuts typed into the settings window, naming the first problem.
///
/// Tray menu lines need one letter or digit, and no two may share one. Keys
/// in the settings window need Ctrl, Alt or Win, unless they are Esc or a
/// function key, so that typing in a text box never triggers one. No two keys
/// of the same window may be the same.
pub fn validate(keys: &Shortcuts) -> Result<(), String> {
    let mut seen: Vec<(Place, String, &str)> = Vec::new();
    for s in &ALL {
        let value = (s.get)(keys).trim();
        if value.is_empty() {
            continue;
        }
        let normal = match s.place {
            Place::Menu => match letter(value) {
                Some(c) => c.to_string(),
                None => {
                    return Err(format!(
                        "\"{}\" in the tray menu needs one letter or digit, or nothing.",
                        s.label
                    ))
                }
            },
            place => match hotkeys::parse_any(value) {
                Some(a) if place == Place::Settings && !typing_safe(a) => {
                    return Err(format!(
                        "\"{}\" needs Ctrl, Alt or Win with {value}, so that typing in \
                         Settings does not set it off.",
                        s.label
                    ))
                }
                Some(a) => format!("{}:{}", a.modifiers, a.vk),
                None => {
                    return Err(format!(
                        "\"{}\" needs a key such as Ctrl+K or Space, or nothing.",
                        s.label
                    ))
                }
            },
        };
        if let Some((_, _, other)) = seen.iter().find(|(p, n, _)| *p == s.place && *n == normal) {
            return Err(format!("\"{other}\" and \"{}\" both use {value}.", s.label));
        }
        seen.push((s.place, normal, s.label));
    }
    Ok(())
}

/// Whether a key in the settings window leaves typing alone.
pub fn typing_safe(a: hotkeys::Accelerator) -> bool {
    use windows::Win32::UI::Input::KeyboardAndMouse::{VK_ESCAPE, VK_F1, VK_F24};
    let with_command_key = a.modifiers & (MOD_CONTROL.0 | MOD_ALT.0 | MOD_WIN.0) != 0;
    let function_key = (u32::from(VK_F1.0)..=u32::from(VK_F24.0)).contains(&a.vk);
    with_command_key || function_key || a.vk == u32::from(VK_ESCAPE.0)
}