use windows::core::PCWSTR;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
use windows::Win32::Graphics::Gdi::{
BeginPaint, BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, CreateFontIndirectW,
CreateSolidBrush, DeleteDC, DeleteObject, DrawTextW, EndPaint, FillRect, GetDC, InvalidateRect,
PtInRect, RedrawWindow, ReleaseDC, SelectObject, SetBkColor, SetBkMode, SetTextColor,
DT_CALCRECT, DT_CENTER, DT_END_ELLIPSIS, DT_LEFT, DT_NOPREFIX, DT_RIGHT, DT_SINGLELINE,
DT_VCENTER, DT_WORDBREAK, HBRUSH, HDC, HFONT, LOGFONTW, PAINTSTRUCT, RDW_ALLCHILDREN,
RDW_ERASE, RDW_INVALIDATE, SRCCOPY, TRANSPARENT,
};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::SystemServices::SS_ENDELLIPSIS;
use windows::Win32::UI::Controls::{
SetScrollInfo, BST_CHECKED, CDDS_PREPAINT, CDIS_FOCUS, CDIS_HOT, CDIS_SELECTED, CDRF_DODEFAULT,
CDRF_SKIPDEFAULT, DRAWITEMSTRUCT, EM_SETCUEBANNER, EM_SETSEL, NMCUSTOMDRAW, NM_CUSTOMDRAW,
ODS_SELECTED, TOOLTIPS_CLASSW, TTF_IDISHWND, TTF_SUBCLASS, TTM_ADDTOOLW, TTM_SETMAXTIPWIDTH,
TTS_ALWAYSTIP, TTTOOLINFOW, WC_BUTTONW, WC_COMBOBOXW, WC_EDITW, WC_LISTBOXW, WC_STATICW,
};
use windows::Win32::UI::Input::KeyboardAndMouse::{
EnableWindow, GetFocus, IsWindowEnabled, SetFocus, VK_ESCAPE,
};
use windows::Win32::UI::WindowsAndMessaging::*;
use crate::config::{Config, LengthPreset, Preset, Shortcuts, WakePolicy};
use crate::lock::settings::{DayLock, LockSettings};
use crate::os::localtime::{format_time, parse_time, DAY_NAMES};
use crate::ui::app::App;
use crate::ui::fluent::{self, rect, rgb, Look, Shape};
use crate::ui::shortcuts::{self, Place};
use crate::ui::wide;
const CLASS: &str = "TaskbarFocusSettings";
const PANE_CLASS: &str = "TaskbarFocusSettingsPane";
const ID_SAVE: usize = 1;
const ID_CANCEL: usize = 2;
const ID_SAVE_AS: usize = 3;
const ID_DEFAULTS: usize = 4;
const ID_SEARCH: usize = 10;
const ID_NAV: usize = 11;
const ID_TITLE: usize = 12;
const ID_EMPTY: usize = 13;
const ID_STATUS: usize = 14;
const ID_PRESET: usize = 100;
const ID_NAME: usize = 101;
const ID_FOCUS: usize = 102;
const ID_SHORT: usize = 103;
const ID_LONG: usize = 104;
const ID_SESSIONS: usize = 105;
const ID_SEQUENCE: usize = 110;
const ID_AUTO_BREAK: usize = 111;
const ID_AUTO_FOCUS: usize = 112;
const ID_REPEAT_CYCLES: usize = 116;
const ID_STRICT: usize = 113;
const ID_RESTORE_SESSION: usize = 114;
const ID_WAKE: usize = 115;
const ID_DND: usize = 120;
const ID_DND_SHORT_BREAK: usize = 121;
const ID_MUTE_TRAY: usize = 122;
const ID_MUTE_WINDOW: usize = 123;
const ID_MINI: usize = 131;
const ID_TOPMOST: usize = 132;
const ID_NOTIFY: usize = 140;
const ID_N_FS: usize = 141;
const ID_N_FE: usize = 142;
const ID_N_BS: usize = 143;
const ID_N_BE: usize = 144;
const ID_ALERT_TOAST: usize = 145;
const ID_REQUIRE_DISMISS: usize = 146;
const ID_ALERT_OVERLAY: usize = 147;
const ID_ALERT_FLASH: usize = 148;
const ID_FLASH_LENGTH: usize = 149;
const ID_MUTE: usize = 150;
const ID_S_FS: usize = 151;
const ID_S_FE: usize = 152;
const ID_S_BS: usize = 153;
const ID_S_BE: usize = 154;
const ID_HOTKEYS: usize = 160;
const ID_HK_TOGGLE: usize = 161;
const ID_HK_SKIP: usize = 162;
const ID_LOCK_DAY: usize = 170;
const ID_LOCK_TIME: usize = 180;
const ID_LOCK_STRICT: usize = 190;
const ID_LOCK_NUMBER: usize = 200;
const ID_AUTOSTART: usize = 210;
const ID_KEYS: usize = 220;
const ID_KEY: usize = 230;
struct LockNumber {
label: &'static str,
max: i64,
min: i64,
icon: &'static str,
desc: &'static str,
get: fn(&LockSettings) -> i64,
set: fn(&mut LockSettings, i64),
}
const LOCK_NUMBERS: [LockNumber; 8] = [
LockNumber {
label: "Cutoff (minutes)",
min: 0,
max: 720,
icon: "\u{E916}",
desc: "How long before a lock it can no longer be postponed or skipped.",
get: |s| s.cutoff_minutes,
set: |s, v| s.cutoff_minutes = v,
},
LockNumber {
label: "Postpone by (minutes)",
min: 1,
max: 240,
icon: "\u{E823}",
desc: "How much one postponement adds to the lock time.",
get: |s| s.postpone_minutes,
set: |s, v| s.postpone_minutes = v,
},
LockNumber {
label: "Postponements per day",
min: 0,
max: 10,
icon: "\u{E9D5}",
desc: "How often one day's lock can be postponed.",
get: |s| s.max_postponements,
set: |s, v| s.max_postponements = v,
},
LockNumber {
label: "Locked period (minutes)",
min: 0,
max: 120,
icon: "\u{E72E}",
desc: "Unlocking sooner locks the PC again. 0 locks once.",
get: |s| s.locked_minutes,
set: |s, v| s.locked_minutes = v,
},
LockNumber {
label: "Warn before cutoff (min)",
min: 0,
max: 120,
icon: "\u{EA8F}",
desc: "0 shows no warning before the cutoff.",
get: |s| s.warn_before_cutoff_minutes,
set: |s, v| s.warn_before_cutoff_minutes = v,
},
LockNumber {
label: "Warn before lock (min)",
min: 0,
max: 30,
icon: "\u{EA8F}",
desc: "No longer than the cutoff. 0 shows no warning.",
get: |s| s.warn_before_lock_minutes,
set: |s, v| s.warn_before_lock_minutes = v,
},
LockNumber {
label: "Return window (minutes)",
min: 0,
max: 240,
icon: "\u{E81C}",
desc: "Returning this long after a missed lock still locks the PC.",
get: |s| s.return_window_minutes,
set: |s, v| s.return_window_minutes = v,
},
LockNumber {
label: "Relock delay (seconds)",
min: 5,
max: 300,
icon: "\u{E916}",
desc: "Time between unlocking too early and locking again.",
get: |s| s.relock_delay_seconds,
set: |s, v| s.relock_delay_seconds = v,
},
];
const FIRST_ADVANCED: usize = 4;
const PAGES: [&str; 9] = [
"General",
"Timer",
"Sequence",
"Notifications",
"Do Not Disturb",
"Sounds",
"Timer window",
"Hotkeys",
"PC lock",
];
const PAGE_GENERAL: usize = 0;
const PAGE_TIMER: usize = 1;
const PAGE_SEQUENCE: usize = 2;
const PAGE_NOTIFICATIONS: usize = 3;
const PAGE_DND: usize = 4;
const PAGE_SOUNDS: usize = 5;
const PAGE_WINDOW: usize = 6;
const PAGE_HOTKEYS: usize = 7;
const PAGE_LOCK: usize = 8;
const CLIENT_W: i32 = 900;
const CLIENT_H: i32 = 640;
const PAD: i32 = 4;
const SIDEBAR_W: i32 = 248;
const NAV_ROW: i32 = 36;
const NAV_Y: i32 = 72;
const SEARCH_BOX: RECT = rect(12, 20, SIDEBAR_W - 12, 52);
const CONTENT_X: i32 = SIDEBAR_W + 4;
const TITLE_Y: i32 = 20;
const PANE_Y: i32 = 76;
const FOOTER_H: i32 = 64;
const FOOTER_Y: i32 = CLIENT_H - FOOTER_H;
const PANE_W: i32 = CLIENT_W - CONTENT_X - 8;
const PANE_H: i32 = FOOTER_Y - PANE_Y;
const ITEM_W: i32 = PANE_W - 17 - 20;
const CAP_W: i32 = 300;
const CARD_X: i32 = 16;
const CARD_Y: i32 = 14;
const TEXT_X: i32 = 56;
const FIELD_W: i32 = 200;
const SWITCH_CTL_W: i32 = 92;
const FIELD_H: i32 = 32;
const EDIT_H: i32 = 20;
const GAP: i32 = 4;
const INDENT: i32 = 32;
const CAPTION_ID: usize = 10_000;
const DESC_ID: usize = 20_000;
const PAGE_ICONS: [&str; 9] = [
"\u{E713}", "\u{E916}", "\u{E8EE}", "\u{EA8F}", "\u{E708}", "\u{E767}", "\u{E7F4}", "\u{E765}",
"\u{E72E}",
];
#[derive(PartialEq)]
enum Kind {
Header,
Check,
Field,
Note,
Day,
}
mod paint_as {
pub const CARD: isize = 0;
pub const CARD_GREY: isize = 1;
pub const PAGE: isize = 2;
pub const PAGE_GREY: isize = 3;
pub const WINDOW_GREY: isize = 4;
pub const FIELD: isize = 5;
}
struct Item {
page: usize,
section: usize,
kind: Kind,
hwnd: HWND,
caption: HWND,
desc: HWND,
day_controls: [HWND; 2],
icon: &'static str,
indent: i32,
ctl_h: i32,
search: String,
}
struct Card {
rect: RECT,
icon: &'static str,
control: HWND,
toggles: bool,
}
struct Field {
rect: RECT,
edit: HWND,
}
struct State {
app: *mut App,
font: HFONT,
small: HFONT,
bold: HFONT,
title: HFONT,
icons: HFONT,
tooltip: HWND,
pane: HWND,
page_bg: HBRUSH,
card: HBRUSH,
field: HBRUSH,
accent: u32,
items: Vec<Item>,
cards: Vec<Card>,
fields: Vec<Field>,
page: usize,
scroll: i32,
content_h: i32,
presets: Vec<Preset>,
current: usize,
}
pub fn open(owner: HWND, app: *mut App) -> Option<HWND> {
unsafe {
let instance = GetModuleHandleW(None).ok()?;
let class = wide(CLASS);
RegisterClassW(&WNDCLASSW {
lpfnWndProc: Some(wndproc),
hInstance: instance.into(),
lpszClassName: class.as_pcwstr(),
hCursor: LoadCursorW(None, IDC_ARROW).ok()?,
hIcon: crate::ui::app::shared_icon(),
..Default::default()
});
let pane_class = wide(PANE_CLASS);
RegisterClassW(&WNDCLASSW {
lpfnWndProc: Some(pane_wndproc),
hInstance: instance.into(),
lpszClassName: pane_class.as_pcwstr(),
hCursor: LoadCursorW(None, IDC_ARROW).ok()?,
..Default::default()
});
let style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN;
let mut rc = RECT {
left: 0,
top: 0,
right: CLIENT_W,
bottom: CLIENT_H,
};
let _ = AdjustWindowRect(&mut rc, style, false);
let title = wide(&format!("{} Settings", crate::APP_NAME));
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE::default(),
class.as_pcwstr(),
title.as_pcwstr(),
style,
CW_USEDEFAULT,
CW_USEDEFAULT,
rc.right - rc.left,
rc.bottom - rc.top,
Some(owner),
None,
Some(instance.into()),
None,
)
.ok()?;
let pane = CreateWindowExW(
WS_EX_CONTROLPARENT,
pane_class.as_pcwstr(),
PCWSTR::null(),
WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_CLIPCHILDREN,
CONTENT_X,
PANE_Y,
PANE_W,
PANE_H,
Some(hwnd),
None,
Some(instance.into()),
None,
)
.ok()?;
let config = (*app).config().clone();
let presets = config.presets.clone();
let current = presets
.iter()
.position(|p| p.name == config.preset().name)
.unwrap_or(0);
let fonts = gui_fonts();
let ptr = Box::into_raw(Box::new(State {
app,
font: fonts.body,
small: fonts.small,
bold: fonts.bold,
title: fonts.title,
icons: fonts.icons,
tooltip: make_tooltip(hwnd),
pane,
page_bg: CreateSolidBrush(rgb(fluent::BACKGROUND)),
card: CreateSolidBrush(rgb(fluent::CARD)),
field: CreateSolidBrush(rgb(fluent::FIELD)),
accent: fluent::accent(),
items: Vec::new(),
cards: Vec::new(),
fields: Vec::new(),
page: 0,
scroll: 0,
content_h: 0,
presets,
current,
}));
SetWindowLongPtrW(hwnd, GWLP_USERDATA, ptr as isize);
SetWindowLongPtrW(pane, GWLP_USERDATA, ptr as isize);
build(hwnd, &mut *ptr, &config);
relayout(hwnd, &mut *ptr);
sync_dependencies((*ptr).pane);
refresh_status(hwnd);
let _ = ShowWindow(hwnd, SW_SHOW);
let _ = SetForegroundWindow(hwnd);
Some(hwnd)
}
}
struct Fonts {
body: HFONT,
small: HFONT,
bold: HFONT,
title: HFONT,
icons: HFONT,
}
fn gui_fonts() -> Fonts {
unsafe {
let mut ncm = NONCLIENTMETRICSW {
cbSize: std::mem::size_of::<NONCLIENTMETRICSW>() as u32,
..Default::default()
};
let ok = SystemParametersInfoW(
SPI_GETNONCLIENTMETRICS,
ncm.cbSize,
Some(&mut ncm as *mut _ as *mut _),
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
)
.is_ok();
let base: LOGFONTW = if ok {
ncm.lfMessageFont
} else {
LOGFONTW::default()
};
let sized = |height: i32, weight: i32, faces: &[&str]| {
let mut lf = base;
lf.lfHeight = -height;
lf.lfWeight = weight;
text_font(&lf, faces)
};
let text = ["Segoe UI Variable Text", "Segoe UI"];
let display = ["Segoe UI Variable Display", "Segoe UI"];
let mut icon_lf = base;
icon_lf.lfHeight = -16;
icon_lf.lfWeight = 400;
Fonts {
body: sized(14, 400, &text),
small: sized(12, 400, &text),
bold: sized(14, 600, &text),
title: sized(28, 600, &display),
icons: fluent::icon_font(&icon_lf),
}
}
}
unsafe fn text_font(base: &LOGFONTW, faces: &[&str]) -> HFONT {
for face in faces {
let mut lf = *base;
fluent::set_face(&mut lf, face);
let font = CreateFontIndirectW(&lf);
if fluent::font_is(font, face) {
return font;
}
let _ = DeleteObject(font.into());
}
CreateFontIndirectW(base)
}
unsafe fn make_tooltip(parent: HWND) -> HWND {
let h = CreateWindowExW(
WINDOW_EX_STYLE::default(),
TOOLTIPS_CLASSW,
PCWSTR::null(),
WINDOW_STYLE(TTS_ALWAYSTIP),
0,
0,
0,
0,
Some(parent),
None,
None,
None,
)
.unwrap_or_default();
if !h.is_invalid() {
SendMessageW(h, TTM_SETMAXTIPWIDTH, None, Some(LPARAM(320)));
}
h
}
std::thread_local! {
static TIP_TEXT: std::cell::RefCell<Vec<Vec<u16>>> =
const { std::cell::RefCell::new(Vec::new()) };
}
unsafe fn tip(tooltip: HWND, control: HWND, text: &str) {
if tooltip.is_invalid() || control.is_invalid() || text.is_empty() {
return;
}
let ptr = TIP_TEXT.with(|c| {
let mut v = c.borrow_mut();
v.push(text.encode_utf16().chain(std::iter::once(0)).collect());
v.last_mut().unwrap().as_mut_ptr()
});
let ti = TTTOOLINFOW {
cbSize: std::mem::size_of::<TTTOOLINFOW>() as u32,
uFlags: TTF_IDISHWND | TTF_SUBCLASS,
hwnd: GetParent(control).unwrap_or_default(),
uId: control.0 as usize,
lpszText: windows::core::PWSTR(ptr),
..Default::default()
};
SendMessageW(
tooltip,
TTM_ADDTOOLW,
None,
Some(LPARAM(&ti as *const _ as isize)),
);
}
#[allow(clippy::too_many_arguments)]
unsafe fn ctl(
parent: HWND,
class: PCWSTR,
text: &str,
style: WINDOW_STYLE,
x: i32,
y: i32,
w: i32,
h: i32,
id: usize,
font: HFONT,
) -> HWND {
let t = wide(text);
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE::default(),
class,
t.as_pcwstr(),
WS_CHILD | style,
x,
y,
w,
h,
Some(parent),
Some(HMENU(id as *mut _)),
None,
None,
)
.unwrap_or_default();
SendMessageW(
hwnd,
WM_SETFONT,
Some(WPARAM(font.0 as usize)),
Some(LPARAM(1)),
);
hwnd
}
unsafe fn painted_as(h: HWND, how: isize) {
if !h.is_invalid() {
SetWindowLongPtrW(h, GWLP_USERDATA, how);
}
}
struct Rows {
pane: HWND,
font: HFONT,
small: HFONT,
bold: HFONT,
tooltip: HWND,
page: usize,
section: usize,
items: Vec<Item>,
}
impl Rows {
unsafe fn header(&mut self, page: usize, title: &str) {
self.page = page;
self.section = self.items.len();
let h = ctl(
self.pane,
WC_STATICW,
title,
WINDOW_STYLE(0),
0,
0,
ITEM_W,
22,
0,
self.bold,
);
painted_as(h, paint_as::PAGE);
self.push(Row {
kind: Kind::Header,
hwnd: h,
ctl_h: 22,
label: title,
..Row::default()
});
}
unsafe fn check(
&mut self,
icon: &'static str,
id: usize,
label: &str,
on: bool,
desc: &str,
help: &str,
) {
self.check_at(icon, 0, id, label, on, desc, help);
}
unsafe fn sub_check(
&mut self,
icon: &'static str,
id: usize,
label: &str,
on: bool,
help: &str,
) {
self.check_at(icon, INDENT, id, label, on, "", help);
}
#[allow(clippy::too_many_arguments)]
unsafe fn check_at(
&mut self,
icon: &'static str,
indent: i32,
id: usize,
label: &str,
on: bool,
desc: &str,
help: &str,
) {
let h = self.switch(id, label, on, SWITCH_CTL_W);
tip(self.tooltip, h, help);
let caption = self.caption(label, id);
let d = self.description(desc, id);
self.push(Row {
kind: Kind::Check,
hwnd: h,
caption,
desc: d,
icon,
indent,
ctl_h: FIELD_H,
label,
description: desc,
help,
..Row::default()
});
}
unsafe fn switch(&self, id: usize, label: &str, on: bool, width: i32) -> HWND {
let h = ctl(
self.pane,
WC_BUTTONW,
label,
WINDOW_STYLE(BS_AUTOCHECKBOX as u32 | WS_TABSTOP.0),
0,
0,
width,
FIELD_H,
id,
self.font,
);
let state = if on { BST_CHECKED.0 as usize } else { 0 };
SendMessageW(h, BM_SETCHECK, Some(WPARAM(state)), None);
h
}
unsafe fn edit(&self, id: usize, value: &str, width: i32) -> HWND {
let e = ctl(
self.pane,
WC_EDITW,
value,
WINDOW_STYLE(WS_TABSTOP.0 | ES_AUTOHSCROLL as u32),
0,
0,
width,
EDIT_H,
id,
self.font,
);
painted_as(e, paint_as::FIELD);
e
}
unsafe fn field(
&mut self,
icon: &'static str,
id: usize,
label: &str,
value: &str,
desc: &str,
help: &str,
) {
let caption = self.caption(label, id);
let e = self.edit(id, value, FIELD_W);
tip(self.tooltip, e, help);
let d = self.description(desc, id);
self.push(Row {
kind: Kind::Field,
hwnd: e,
caption,
desc: d,
icon,
ctl_h: EDIT_H,
label,
description: desc,
help,
..Row::default()
});
}
#[allow(clippy::too_many_arguments)]
unsafe fn combo(
&mut self,
icon: &'static str,
id: usize,
label: &str,
options: &[&str],
selected: usize,
desc: &str,
help: &str,
) {
let caption = self.caption(label, id);
let h = ctl(
self.pane,
WC_COMBOBOXW,
"",
WINDOW_STYLE(CBS_DROPDOWNLIST as u32 | WS_TABSTOP.0 | WS_VSCROLL.0),
0,
0,
FIELD_W,
240,
id,
self.font,
);
SendMessageW(
h,
CB_SETITEMHEIGHT,
Some(WPARAM(usize::MAX)),
Some(LPARAM(FIELD_H as isize - 6)),
);
SendMessageW(h, CB_SETITEMHEIGHT, Some(WPARAM(0)), Some(LPARAM(24)));
for o in options {
let t = wide(o);
SendMessageW(
h,
CB_ADDSTRING,
None,
Some(LPARAM(t.as_pcwstr().0 as isize)),
);
}
SendMessageW(h, CB_SETCURSEL, Some(WPARAM(selected)), None);
tip(self.tooltip, h, help);
let d = self.description(desc, id);
self.push(Row {
kind: Kind::Field,
hwnd: h,
caption,
desc: d,
icon,
ctl_h: 240,
label,
description: desc,
help,
..Row::default()
});
}
unsafe fn day(&mut self, index: usize, lock: &DayLock) {
let name = DAY_NAMES[index];
let on = self.switch(ID_LOCK_DAY + index, name, lock.enabled, 48);
tip(self.tooltip, on, "Lock the PC on this day.");
let caption = self.caption(name, ID_LOCK_DAY + index);
let time = self.edit(ID_LOCK_TIME + index, &format_time(lock.time), 100);
tip(self.tooltip, time, "For example 5:45 PM or 17:45.");
let strict = self.switch(ID_LOCK_STRICT + index, "Strict", lock.strict, 104);
let help = "After the cutoff, Exit is refused and this day's lock cannot be \
changed until its locked period ends.";
tip(self.tooltip, strict, help);
self.push(Row {
kind: Kind::Day,
hwnd: on,
caption,
day_controls: [time, strict],
ctl_h: FIELD_H,
label: name,
description: "lock time strict",
help,
..Row::default()
});
}
unsafe fn note(&mut self, text: &str) {
let h = ctl(
self.pane,
WC_STATICW,
text,
WINDOW_STYLE(0),
0,
0,
ITEM_W,
16,
0,
self.small,
);
painted_as(h, paint_as::PAGE_GREY);
self.push(Row {
kind: Kind::Note,
hwnd: h,
label: text,
..Row::default()
});
}
unsafe fn caption(&self, label: &str, id: usize) -> HWND {
let h = ctl(
self.pane,
WC_STATICW,
label,
WINDOW_STYLE(SS_ENDELLIPSIS.0),
0,
0,
CAP_W,
EDIT_H,
id + CAPTION_ID,
self.font,
);
painted_as(h, paint_as::CARD);
h
}
unsafe fn description(&self, text: &str, id: usize) -> HWND {
if text.is_empty() {
return HWND::default();
}
let h = ctl(
self.pane,
WC_STATICW,
text,
WINDOW_STYLE(0),
0,
0,
CAP_W,
16,
id + DESC_ID,
self.small,
);
painted_as(h, paint_as::CARD_GREY);
h
}
fn push(&mut self, row: Row) {
let section = if row.kind == Kind::Header {
self.items.len()
} else {
self.section
};
let heading = self
.items
.get(section)
.map(|h| h.search.clone())
.unwrap_or_default();
self.items.push(Item {
page: self.page,
section,
search: format!(
"{} {} {} {} {}",
PAGES[self.page], heading, row.label, row.description, row.help
)
.to_lowercase(),
kind: row.kind,
hwnd: row.hwnd,
caption: row.caption,
desc: row.desc,
day_controls: row.day_controls,
icon: row.icon,
indent: row.indent,
ctl_h: row.ctl_h,
});
}
}
struct Row<'a> {
kind: Kind,
hwnd: HWND,
caption: HWND,
desc: HWND,
day_controls: [HWND; 2],
icon: &'static str,
indent: i32,
ctl_h: i32,
label: &'a str,
description: &'a str,
help: &'a str,
}
impl Default for Row<'_> {
fn default() -> Self {
Row {
kind: Kind::Note,
hwnd: HWND::default(),
caption: HWND::default(),
desc: HWND::default(),
day_controls: [HWND::default(); 2],
icon: "",
indent: 0,
ctl_h: 0,
label: "",
description: "",
help: "",
}
}
}
unsafe fn build(hwnd: HWND, st: &mut State, cfg: &Config) {
let f = st.font;
let search = ctl(
hwnd,
WC_EDITW,
"",
WINDOW_STYLE(WS_VISIBLE.0 | WS_TABSTOP.0 | ES_AUTOHSCROLL as u32),
SEARCH_BOX.left + 12,
SEARCH_BOX.top + (FIELD_H - EDIT_H) / 2,
SEARCH_BOX.right - SEARCH_BOX.left - 44,
EDIT_H,
ID_SEARCH,
f,
);
painted_as(search, paint_as::FIELD);
let keys = &cfg.shortcuts;
let cue = wide(&format!(
"Search settings{}",
key_hint(keys, &keys.settings.search)
));
SendMessageW(
search,
EM_SETCUEBANNER,
Some(WPARAM(1)),
Some(LPARAM(cue.as_pcwstr().0 as isize)),
);
tip(
st.tooltip,
search,
"Type a word to see every matching setting from all pages at once.",
);
let nav = ctl(
hwnd,
WC_LISTBOXW,
"",
WINDOW_STYLE(
WS_VISIBLE.0
| WS_TABSTOP.0
| LBS_NOTIFY as u32
| LBS_HASSTRINGS as u32
| LBS_OWNERDRAWFIXED as u32
| LBS_NOINTEGRALHEIGHT as u32,
),
8,
NAV_Y,
SIDEBAR_W - 16,
NAV_ROW * PAGES.len() as i32,
ID_NAV,
f,
);
SendMessageW(
nav,
LB_SETITEMHEIGHT,
Some(WPARAM(0)),
Some(LPARAM(NAV_ROW as isize)),
);
for p in PAGES {
let t = wide(p);
SendMessageW(
nav,
LB_ADDSTRING,
None,
Some(LPARAM(t.as_pcwstr().0 as isize)),
);
}
SendMessageW(nav, LB_SETCURSEL, Some(WPARAM(0)), None);
let title = ctl(
hwnd,
WC_STATICW,
PAGES[0],
WINDOW_STYLE(WS_VISIBLE.0),
CONTENT_X,
TITLE_Y,
PANE_W,
40,
ID_TITLE,
st.title,
);
painted_as(title, paint_as::PAGE);
let status = ctl(
hwnd,
WC_STATICW,
"",
WINDOW_STYLE(WS_VISIBLE.0),
20,
FOOTER_Y - 52,
SIDEBAR_W - 40,
36,
ID_STATUS,
st.small,
);
painted_as(status, paint_as::WINDOW_GREY);
let tooltip = st.tooltip;
let by = FOOTER_Y + (FOOTER_H - FIELD_H) / 2;
let b = |x: i32, w: i32, text: &str, id: usize, help: &str| {
let h = ctl(
hwnd,
WC_BUTTONW,
text,
WINDOW_STYLE(WS_VISIBLE.0 | WS_TABSTOP.0),
x,
by,
w,
FIELD_H,
id,
f,
);
tip(tooltip, h, help);
};
b(20, 140, "Restore defaults", ID_DEFAULTS,
"Reset every setting on this window to its original value. Nothing is saved until you press Save.");
let right = CLIENT_W - 20;
b(
right - 104 - 8 - 104 - 8 - 168,
168,
"Save as new preset",
ID_SAVE_AS,
"Keep the current preset untouched and store these timer lengths under the name above.",
);
b(
right - 104 - 8 - 104,
104,
"Save",
ID_SAVE,
&format!(
"Apply these settings and close.{}",
key_hint(keys, &keys.settings.save)
),
);
b(
right - 104,
104,
"Cancel",
ID_CANCEL,
&format!(
"Close without saving.{}",
key_hint(keys, &keys.settings.close)
),
);
let empty = ctl(
st.pane,
WC_STATICW,
"Nothing matches that. Try a shorter word.",
WINDOW_STYLE(0),
0,
0,
ITEM_W,
20,
ID_EMPTY,
st.small,
);
painted_as(empty, paint_as::PAGE_GREY);
let mut rows = Rows {
pane: st.pane,
font: st.font,
small: st.small,
bold: st.bold,
tooltip: st.tooltip,
page: 0,
section: 0,
items: Vec::new(),
};
build_rows(&mut rows, st, cfg);
st.items = rows.items;
}
unsafe fn build_rows(r: &mut Rows, st: &State, cfg: &Config) {
let p = st.presets[st.current.min(st.presets.len() - 1)].clone();
let names: Vec<&str> = st.presets.iter().map(|p| p.name.as_str()).collect();
r.header(PAGE_GENERAL, "Startup");
r.check(
"\u{E7E8}",
ID_AUTOSTART,
"Start with Windows",
crate::os::autostart::is_on(),
"Opens the app when you sign in. A PC lock only happens while it runs.",
"Adds one value to the startup list of your own Windows account.",
);
r.header(PAGE_TIMER, "Preset");
r.combo(
"\u{E8FD}",
ID_PRESET,
"Preset",
&names,
st.current,
"The set of lengths the timer runs with.",
"Switch between saved presets. Edit the boxes below and press Save to \
change this preset, or Save as new preset to keep both.",
);
r.field(
"\u{E8EC}",
ID_NAME,
"Preset name",
&p.name,
"Shown in the tray menu and usable with --preset.",
"Renaming here and pressing Save renames the preset.",
);
r.header(PAGE_TIMER, "Lengths");
r.field(
"\u{E916}",
ID_FOCUS,
"Focus (minutes)",
&num(p.focus_minutes),
"Fractions are allowed, e.g. 0.5 for 30 seconds.",
"How long one focus session lasts.",
);
r.field(
"\u{EC32}",
ID_SHORT,
"Short break (minutes)",
&num(p.short_break_minutes),
"Taken after most focus sessions.",
"The break taken after most focus sessions.",
);
r.field(
"\u{E823}",
ID_LONG,
"Long break (minutes)",
&num(p.long_break_minutes),
"Taken after every Nth focus session.",
"The longer break taken after every Nth focus session.",
);
r.field(
"\u{E9D5}",
ID_SESSIONS,
"Sessions per long break",
&p.sessions_before_long_break.to_string(),
"4 is the classic Pomodoro cadence.",
"How many focus sessions to complete before earning a long break.",
);
r.header(PAGE_SEQUENCE, "Automatic sequence");
r.check(
"\u{E8EE}",
ID_SEQUENCE,
"Run the Pomodoro sequence",
cfg.behavior.sequence_enabled,
"Turn this off to use the app as a plain manual timer.",
"Master switch for focus, break and long break running one after another.",
);
r.sub_check(
"\u{EC32}",
ID_AUTO_BREAK,
"Start a break when focus ends",
cfg.behavior.auto_start_break,
"When a focus session completes, begin the break automatically.",
);
r.sub_check(
"\u{E916}",
ID_AUTO_FOCUS,
"Start focus when a break ends",
cfg.behavior.auto_start_focus,
"When a break completes, begin the next focus session automatically.",
);
r.sub_check(
"\u{E8EE}",
ID_REPEAT_CYCLES,
"Start another cycle after a long break",
cfg.behavior.repeat_cycles,
"When the long break ends, begin a new focus session even if \
“Start focus when a break ends” is off.",
);
r.header(PAGE_SEQUENCE, "Interruptions");
r.check(
"\u{E72E}",
ID_STRICT,
"Strict focus",
cfg.behavior.strict_focus,
"Confirm before stopping or skipping a running focus session.",
"Ask for confirmation before stopping or skipping a running focus session, \
so a stray click cannot end it. Breaks are never guarded.",
);
r.check(
"\u{E81C}",
ID_RESTORE_SESSION,
"Restore an interrupted session on restart",
cfg.behavior.restore_session_on_restart,
"It always comes back paused, never running.",
"If the app closes mid-session, bring the remaining time back next time it starts.",
);
r.combo(
"\u{E7E8}",
ID_WAKE,
"After sleep",
&[
"Count the time asleep",
"Ignore the time asleep",
"Pause the timer",
],
match cfg.behavior.wake_policy {
WakePolicy::CountSleep => 0,
WakePolicy::IgnoreSleep => 1,
WakePolicy::Pause => 2,
},
"What a running timer does when the machine wakes up.",
"Counting the time asleep means a 25 minute session started before a two \
hour nap is simply over.",
);
r.header(PAGE_NOTIFICATIONS, "Windows notifications");
r.check(
"\u{EA8F}",
ID_NOTIFY,
"Show notifications",
cfg.notifications.enabled,
"Master switch for all notifications.",
"Turn this off to make the app silent in the notification centre.",
);
r.sub_check(
"\u{E916}",
ID_N_FS,
"Focus started",
cfg.notifications.events.focus_start,
"Notify when a focus session begins.",
);
r.sub_check(
"\u{E7C1}",
ID_N_FE,
"Focus ended",
cfg.notifications.events.focus_end,
"Notify when a focus session completes.",
);
r.sub_check(
"\u{EC32}",
ID_N_BS,
"Break started",
cfg.notifications.events.break_start,
"Notify when a break begins.",
);
r.sub_check(
"\u{E823}",
ID_N_BE,
"Break ended",
cfg.notifications.events.break_end,
"Notify when a break completes.",
);
r.header(PAGE_NOTIFICATIONS, "When a session ends");
r.note(
"Pick any combination. Options that need another switch stay dimmed \
until that switch is on. Overlay and flash still work under Do Not \
Disturb.",
);
r.check(
"\u{EA8F}",
ID_ALERT_TOAST,
"Tray toast",
cfg.alerts.toast,
"Needs “Show notifications” above.",
"Posts the usual Windows toast when a focus or break ends. Disabled \
while Show notifications is off.",
);
r.check(
"\u{E7F4}",
ID_ALERT_OVERLAY,
"Centre overlay",
cfg.alerts.overlay,
"A large card in the middle of the screen.",
"A dimmed backdrop and centred card that is hard to miss.",
);
r.sub_check(
"\u{E769}",
ID_REQUIRE_DISMISS,
"Wait for dismiss — pauses the timer",
cfg.alerts.require_dismiss,
"Needs Centre overlay. Keeps the card open and pauses until Continue.",
);
r.check(
"\u{E706}",
ID_ALERT_FLASH,
"Screen flash",
cfg.alerts.flash,
"A colour pulse across every screen.",
"A colour pulse across every screen. Short is two quick pulses; Extra long is eight slower ones.",
);
r.combo(
"\u{E706}",
ID_FLASH_LENGTH,
"Flash length",
&["Short", "Normal", "Long", "Extra long"],
cfg.alerts.flash_length.index(),
"How long the screen flash runs.",
"Needs Screen flash. Short is two quick pulses; Extra long is eight slower ones.",
);
r.header(PAGE_DND, "Muting");
r.check(
"\u{E708}",
ID_DND,
"Mute notifications during focus",
cfg.dnd.enabled,
"Do Not Disturb goes on with focus and off with a break.",
"Switch Windows Do Not Disturb on when focus starts and off when a break starts.",
);
r.sub_check(
"\u{E708}",
ID_DND_SHORT_BREAK,
"Keep it on during short breaks",
cfg.dnd.keep_on_short_break,
"Only a long break turns Do Not Disturb off. Needs muting during focus.",
);
r.note(
"Your priority apps and contacts still get through - Windows keeps \
applying your own priority list, which this app never touches.",
);
r.header(PAGE_DND, "Muted indicator");
r.note("Only used while muting during focus is switched on.");
r.sub_check(
"\u{EA8F}",
ID_MUTE_TRAY,
"Add a separate bell beside the clock",
cfg.dnd.mute_tray_icon,
"A second tray icon, present only while muted. Needs muting during focus.",
);
r.sub_check(
"\u{E7ED}",
ID_MUTE_WINDOW,
"Show a muted bell in the timer window",
cfg.dnd.mute_window,
"Next to the countdown. Needs muting during focus.",
);
r.note(
"Windows only shows its own muted icon for changes made from the taskbar. \
These draw the same crossed-out bell instead. The timer icon stays \
dedicated to progress because it cannot show both legibly.",
);
r.header(PAGE_SOUNDS, "Alert sounds");
r.note(
"Plays the Windows Asterisk sound from your scheme. Mute system sounds \
in Windows if you want silence.",
);
r.check(
"\u{E74F}",
ID_MUTE,
"Mute all sounds",
cfg.sounds.muted,
"When on, the switches below do nothing.",
"Silences every cue without forgetting which ones you had chosen.",
);
r.sub_check(
"\u{E916}",
ID_S_FS,
"Focus started",
cfg.sounds.events.focus_start,
"Play a cue when a focus session begins.",
);
r.sub_check(
"\u{E7C1}",
ID_S_FE,
"Focus ended",
cfg.sounds.events.focus_end,
"Play a cue when a focus session completes.",
);
r.sub_check(
"\u{EC32}",
ID_S_BS,
"Break started",
cfg.sounds.events.break_start,
"Play a cue when a break begins.",
);
r.sub_check(
"\u{E823}",
ID_S_BE,
"Break ended",
cfg.sounds.events.break_end,
"Play a cue when a break completes.",
);
r.header(PAGE_WINDOW, "Compact timer");
r.check(
"\u{E7F4}",
ID_MINI,
"Show the compact timer window",
cfg.display.mini_window,
"A small resizable countdown you can click to start or pause.",
"Drag its edges to shrink it to roughly the height of a taskbar button, \
or make it large. Click it to start or pause.",
);
r.sub_check(
"\u{E718}",
ID_TOPMOST,
"Keep it above other windows",
cfg.display.always_on_top,
"Needs the compact timer window. Stays visible over other apps.",
);
r.note("The tray icon always stays visible; these are extra readouts.");
r.header(PAGE_HOTKEYS, "Global hotkeys");
r.check(
"\u{E765}",
ID_HOTKEYS,
"Enable global hotkeys",
cfg.hotkeys.enabled,
"Hotkeys work from any application.",
"If another program already owns a combination, you will be told.",
);
r.field(
"\u{E768}",
ID_HK_TOGGLE,
"Start / pause",
&cfg.hotkeys.toggle,
"For example Ctrl+Alt+F. Leave blank to disable.",
"A modifier is required.",
);
r.field(
"\u{E893}",
ID_HK_SKIP,
"Skip to next",
&cfg.hotkeys.skip,
"For example Ctrl+Alt+B. Leave blank to disable.",
"A modifier is required.",
);
r.header(PAGE_HOTKEYS, "Keyboard shortcuts");
r.check(
"\u{E765}",
ID_KEYS,
"Use keyboard shortcuts",
cfg.shortcuts.enabled,
"Clear any key below to remove just that shortcut.",
"Keys that work while the app's menu or one of its windows is open.",
);
let mut place = None;
for (i, key) in shortcuts::ALL.iter().enumerate() {
if place != Some(key.place) {
place = Some(key.place);
let (title, note) = match key.place {
Place::Menu => (
"Tray menu",
"One letter or digit, pressed while the menu is open. The presets in \
the Preset menu are numbered 1 to 9.",
),
Place::TimerWindow => (
"Timer window",
"Any key, pressed while the timer window is in front.",
),
Place::Settings => (
"Settings window",
"Needs Ctrl, Alt or Win, unless it is Esc or a function key. Changes \
here take effect after Save.",
),
};
r.header(PAGE_HOTKEYS, title);
r.note(note);
}
r.field(
key.icon,
ID_KEY + i,
key.label,
(key.get)(&cfg.shortcuts),
"",
"Leave blank to remove this shortcut.",
);
}
r.header(PAGE_LOCK, "Days");
for index in 0..7 {
r.day(index, cfg.lock.day(index));
}
for (i, n) in LOCK_NUMBERS.iter().enumerate() {
match i {
0 => r.header(PAGE_LOCK, "Timing"),
FIRST_ADVANCED => r.header(PAGE_LOCK, "Advanced"),
_ => {}
}
let limits = format!("From {} to {}.", n.min, n.max);
let value = (n.get)(&cfg.lock).to_string();
r.field(n.icon, ID_LOCK_NUMBER + i, n.label, &value, n.desc, &limits);
}
}
unsafe fn query(hwnd: HWND) -> String {
text_of(hwnd, ID_SEARCH).trim().to_lowercase()
}
unsafe fn relayout(hwnd: HWND, st: &mut State) {
let q = query(hwnd);
let mut visible = vec![false; st.items.len()];
if q.is_empty() {
for (i, it) in st.items.iter().enumerate() {
visible[i] = it.page == st.page;
}
} else {
for i in 0..st.items.len() {
if st.items[i].kind != Kind::Header && st.items[i].search.contains(&q) {
visible[i] = true;
visible[st.items[i].section] = true;
}
}
}
let focus = GetFocus();
let mut cards = Vec::new();
let mut fields = Vec::new();
let mut y = PAD;
for (i, it) in st.items.iter().enumerate() {
if !visible[i] {
hide(it);
continue;
}
let (next, card) = place(it, y, &mut fields);
y = next;
if let Some(rect) = card {
cards.push(Card {
rect,
icon: it.icon,
control: it.hwnd,
toggles: it.kind == Kind::Check,
});
}
}
st.cards = cards;
st.fields = fields;
st.content_h = y;
let none = !visible.iter().any(|v| *v);
if let Ok(h) = GetDlgItem(Some(st.pane), ID_EMPTY as i32) {
let _ = SetWindowPos(h, None, 2, PAD, ITEM_W, 20, SWP_NOZORDER);
let _ = ShowWindow(h, if none { SW_SHOW } else { SW_HIDE });
}
if !focus.is_invalid() && !IsWindowVisible(focus).as_bool() {
let fallback = if q.is_empty() { ID_NAV } else { ID_SEARCH };
if let Ok(h) = GetDlgItem(Some(hwnd), fallback as i32) {
let _ = SetFocus(Some(h));
}
}
let heading = if q.is_empty() {
PAGES[st.page]
} else {
"Search results"
};
if let Ok(nav) = GetDlgItem(Some(hwnd), ID_NAV as i32) {
let sel = if q.is_empty() { st.page as isize } else { -1 };
SendMessageW(nav, LB_SETCURSEL, Some(WPARAM(sel as usize)), None);
}
if let Ok(h) = GetDlgItem(Some(hwnd), ID_TITLE as i32) {
let t = wide(heading);
let _ = SetWindowTextW(h, t.as_pcwstr());
let _ = InvalidateRect(Some(h), None, true);
}
st.scroll = 0;
set_scroll_range(st);
let _ = RedrawWindow(
Some(st.pane),
None,
None,
RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN,
);
}
unsafe fn hide(it: &Item) {
for h in [
it.hwnd,
it.caption,
it.desc,
it.day_controls[0],
it.day_controls[1],
] {
if !h.is_invalid() {
let _ = ShowWindow(h, SW_HIDE);
}
}
}
unsafe fn text_height(h: HWND, width: i32) -> i32 {
let mut buf = [0u16; 512];
let n = GetWindowTextW(h, &mut buf) as usize;
let dc = GetDC(Some(h));
let font = HFONT(SendMessageW(h, WM_GETFONT, None, None).0 as *mut _);
let old = SelectObject(dc, font.into());
let mut rc = rect(0, 0, width, 0);
DrawTextW(
dc,
&mut buf[..n],
&mut rc,
DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX,
);
SelectObject(dc, old);
ReleaseDC(Some(h), dc);
rc.bottom.max(16)
}
unsafe fn place(it: &Item, y: i32, fields: &mut Vec<Field>) -> (i32, Option<RECT>) {
let show = |h: HWND, x: i32, y: i32, w: i32, hh: i32| {
if !h.is_invalid() {
let _ = SetWindowPos(h, None, x, y, w, hh, SWP_NOZORDER);
let _ = ShowWindow(h, SW_SHOW);
}
};
let mut text_box = |edit: HWND, x: i32, top: i32, w: i32| {
let frame = rect(x, top, x + w, top + FIELD_H);
show(edit, x + 11, top + (FIELD_H - EDIT_H) / 2, w - 22, EDIT_H);
fields.push(Field { rect: frame, edit });
};
let left = it.indent;
let right = ITEM_W;
let card = |top: i32, bottom: i32| rect(left, top, right, bottom);
match it.kind {
Kind::Header => {
let y = if y > PAD { y + 22 } else { y };
show(it.hwnd, 2, y, ITEM_W, 22);
(y + 30, None)
}
Kind::Note => {
let width = ITEM_W - left - 4;
let h = text_height(it.hwnd, width);
show(it.hwnd, left + 2, y + 2, width, h);
(y + h + 14, None)
}
Kind::Check | Kind::Field => {
let control_w = if it.kind == Kind::Check {
SWITCH_CTL_W
} else {
FIELD_W
};
let text_x = left + TEXT_X;
let text_w = right - 16 - control_w - 24 - text_x;
let desc_h = if it.desc.is_invalid() {
0
} else {
text_height(it.desc, text_w)
};
let block = EDIT_H + if desc_h > 0 { desc_h + 2 } else { 0 };
let card_h = (block + CARD_Y * 2).max(FIELD_H + 20);
let top = y + (card_h - block) / 2;
show(it.caption, text_x, top, text_w, EDIT_H);
if desc_h > 0 {
show(it.desc, text_x, top + EDIT_H + 2, text_w, desc_h);
}
let control_x = right - 16 - control_w;
let control_y = y + (card_h - FIELD_H) / 2;
match it.kind {
Kind::Check => show(it.hwnd, control_x, control_y, control_w, FIELD_H),
_ if it.ctl_h > FIELD_H => show(it.hwnd, control_x, control_y, control_w, it.ctl_h),
_ => text_box(it.hwnd, control_x, control_y, control_w),
}
let bottom = y + card_h;
(bottom + GAP, Some(card(y, bottom)))
}
Kind::Day => {
let card_h = FIELD_H + 20;
let control_y = y + 10;
show(it.hwnd, left + 8, control_y, 48, FIELD_H);
show(
it.caption,
left + 68,
y + (card_h - EDIT_H) / 2,
120,
EDIT_H,
);
text_box(it.day_controls[0], left + 196, control_y, 122);
show(
it.day_controls[1],
right - 16 - 104,
control_y,
104,
FIELD_H,
);
let bottom = y + card_h;
(bottom + GAP, Some(card(y, bottom)))
}
}
}
unsafe fn set_scroll_range(st: &State) {
let mut rc = RECT::default();
let _ = GetClientRect(st.pane, &mut rc);
let si = SCROLLINFO {
cbSize: std::mem::size_of::<SCROLLINFO>() as u32,
fMask: SIF_RANGE | SIF_PAGE | SIF_POS,
nMin: 0,
nMax: (st.content_h + 16 - 1).max(0),
nPage: rc.bottom as u32,
nPos: st.scroll,
..Default::default()
};
SetScrollInfo(st.pane, SB_VERT, &si, true);
}
unsafe fn scroll_to(st: &mut State, pos: i32) {
let mut rc = RECT::default();
let _ = GetClientRect(st.pane, &mut rc);
let max = (st.content_h + 16 - rc.bottom).max(0);
let pos = pos.clamp(0, max);
let dy = st.scroll - pos;
if dy == 0 {
return;
}
st.scroll = pos;
ScrollWindowEx(
st.pane,
0,
dy,
None,
None,
None,
None,
SW_SCROLLCHILDREN | SW_INVALIDATE | SW_ERASE,
);
set_scroll_range(st);
}
unsafe fn paint_pane(st: &State, hwnd: HWND, hdc: HDC) {
let mut client = RECT::default();
let _ = GetClientRect(hwnd, &mut client);
let (w, h) = (client.right, client.bottom);
if w <= 0 || h <= 0 {
return;
}
let mem = CreateCompatibleDC(Some(hdc));
let bitmap = CreateCompatibleBitmap(hdc, w, h);
let old_bitmap = SelectObject(mem, bitmap.into());
FillRect(mem, &client, st.page_bg);
let on_screen = |r: &RECT| {
let r = rect(r.left, r.top - st.scroll, r.right, r.bottom - st.scroll);
(r.bottom > 0 && r.top < h).then_some(r)
};
let old_font = SelectObject(mem, st.icons.into());
SetBkMode(mem, TRANSPARENT);
for c in &st.cards {
let Some(r) = on_screen(&c.rect) else {
continue;
};
fluent::smooth(
mem,
r,
fluent::BACKGROUND,
&[Shape::Rounded {
rect: r,
radius: 6,
fill: fluent::CARD,
edge: Some(fluent::CARD_EDGE),
}],
);
let enabled = IsWindowEnabled(c.control).as_bool();
SetTextColor(
mem,
rgb(if enabled {
fluent::TEXT
} else {
fluent::TEXT_DISABLED
}),
);
draw_icon(mem, c.icon, r.left + CARD_X, r.top, 24, r.bottom - r.top);
}
SelectObject(mem, old_font);
let focus = GetFocus();
for f in &st.fields {
let Some(r) = on_screen(&f.rect) else {
continue;
};
let enabled = IsWindowEnabled(f.edit).as_bool();
let shapes = fluent::text_box(r, focus == f.edit, enabled, st.accent);
fluent::smooth(mem, r, fluent::CARD, &shapes);
}
let _ = BitBlt(hdc, 0, 0, w, h, Some(mem), 0, 0, SRCCOPY);
SelectObject(mem, old_bitmap);
let _ = DeleteObject(bitmap.into());
let _ = DeleteDC(mem);
}
unsafe fn draw_icon(hdc: HDC, icon: &str, x: i32, y: i32, w: i32, h: i32) {
if icon.is_empty() {
return;
}
let mut glyph: Vec<u16> = icon.encode_utf16().collect();
let mut rc = rect(x, y, x + w, y + h);
DrawTextW(
hdc,
&mut glyph,
&mut rc,
DT_CENTER | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX,
);
}
unsafe fn paint_nav_item(st: &State, dis: &DRAWITEMSTRUCT) {
let rc = dis.rcItem;
let mut shapes = Vec::new();
if dis.itemState.0 & ODS_SELECTED.0 != 0 {
shapes.push(Shape::Rounded {
rect: rect(rc.left, rc.top + 2, rc.right, rc.bottom - 2),
radius: 4,
fill: fluent::SELECTED,
edge: None,
});
let mid = (rc.top + rc.bottom) / 2;
shapes.push(Shape::Rounded {
rect: rect(rc.left, mid - 8, rc.left + 3, mid + 8),
radius: 1,
fill: st.accent,
edge: None,
});
}
fluent::smooth(dis.hDC, rc, fluent::BACKGROUND, &shapes);
let mut text = [0u16; 64];
let n = SendMessageW(
dis.hwndItem,
LB_GETTEXT,
Some(WPARAM(dis.itemID as usize)),
Some(LPARAM(text.as_mut_ptr() as isize)),
)
.0;
if n <= 0 {
return;
}
SetBkMode(dis.hDC, TRANSPARENT);
SetTextColor(dis.hDC, rgb(fluent::TEXT));
let old_font = SelectObject(dis.hDC, st.icons.into());
draw_icon(
dis.hDC,
PAGE_ICONS
.get(dis.itemID as usize)
.copied()
.unwrap_or_default(),
rc.left + 14,
rc.top,
20,
rc.bottom - rc.top,
);
SelectObject(dis.hDC, st.font.into());
let mut text_rc = rect(rc.left + 48, rc.top, rc.right - 8, rc.bottom);
DrawTextW(
dis.hDC,
&mut text[..n as usize],
&mut text_rc,
DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS,
);
SelectObject(dis.hDC, old_font);
}
unsafe fn shows_focus(h: HWND) -> bool {
let state = SendMessageW(h, WM_QUERYUISTATE, None, None).0 as u32;
state & UISF_HIDEFOCUS == 0
}
unsafe fn is_checkbox(h: HWND) -> bool {
let mut class = [0u16; 16];
let n = GetClassNameW(h, &mut class) as usize;
let style = GetWindowLongW(h, GWL_STYLE) as u32 & BS_TYPEMASK as u32;
String::from_utf16_lossy(&class[..n]).eq_ignore_ascii_case("Button")
&& style == BS_AUTOCHECKBOX as u32
}
unsafe fn custom_draw(st: &State, lparam: LPARAM) -> LRESULT {
let cd = &*(lparam.0 as *const NMCUSTOMDRAW);
if cd.hdr.code != NM_CUSTOMDRAW {
return LRESULT(0);
}
let h = cd.hdr.hwndFrom;
let id = cd.hdr.idFrom;
let is_switch = is_checkbox(h);
let is_button = [ID_SAVE, ID_CANCEL, ID_SAVE_AS, ID_DEFAULTS].contains(&id);
if !is_switch && !is_button {
return LRESULT(CDRF_DODEFAULT as isize);
}
if cd.dwDrawStage != CDDS_PREPAINT {
return LRESULT(CDRF_DODEFAULT as isize);
}
let rc = cd.rc;
let look = Look {
enabled: IsWindowEnabled(h).as_bool(),
hot: cd.uItemState.0 & CDIS_HOT.0 != 0,
pressed: cd.uItemState.0 & CDIS_SELECTED.0 != 0,
focus: cd.uItemState.0 & CDIS_FOCUS.0 != 0 && shows_focus(h),
};
let mut buf = [0u16; 64];
let n = GetWindowTextW(h, &mut buf) as usize;
let mut label: Vec<u16> = buf[..n].to_vec();
SetBkMode(cd.hdc, TRANSPARENT);
let old_font = SelectObject(cd.hdc, st.font.into());
if is_switch {
let on = SendMessageW(h, BM_GETCHECK, None, None).0 == BST_CHECKED.0 as isize;
let x = rc.right - fluent::SWITCH_W - 4;
let y = rc.top + (rc.bottom - rc.top - fluent::SWITCH_H) / 2;
fluent::smooth(
cd.hdc,
rc,
fluent::CARD,
&fluent::switch(x, y, on, look, st.accent),
);
let day_switch = (ID_LOCK_DAY..ID_LOCK_DAY + 7).contains(&id);
let strict = (ID_LOCK_STRICT..ID_LOCK_STRICT + 7).contains(&id);
if !day_switch {
if !strict {
label = if on { "On" } else { "Off" }.encode_utf16().collect();
}
SetTextColor(
cd.hdc,
rgb(if look.enabled {
fluent::TEXT
} else {
fluent::TEXT_DISABLED
}),
);
let mut text_rc = rect(rc.left, rc.top, x - 12, rc.bottom);
DrawTextW(
cd.hdc,
&mut label,
&mut text_rc,
DT_RIGHT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX,
);
}
} else {
let primary = id == ID_SAVE;
fluent::smooth(
cd.hdc,
rc,
fluent::BACKGROUND,
&fluent::button(rc, primary, look, st.accent),
);
let colour = match (primary, look.enabled) {
(true, true) => 0xFFFFFF,
(false, true) => fluent::TEXT,
(_, false) => fluent::TEXT_DISABLED,
};
SetTextColor(cd.hdc, rgb(colour));
let mut text_rc = rc;
DrawTextW(
cd.hdc,
&mut label,
&mut text_rc,
DT_CENTER | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX,
);
}
SelectObject(cd.hdc, old_font);
LRESULT(CDRF_SKIPDEFAULT as isize)
}
unsafe fn repaint_field(st: &State, edit: HWND) {
if let Some(f) = st.fields.iter().find(|f| f.edit == edit) {
let r = rect(
f.rect.left,
f.rect.top - st.scroll,
f.rect.right,
f.rect.bottom - st.scroll,
);
let _ = InvalidateRect(Some(st.pane), Some(&r), false);
}
}
pub fn shortcut(hwnd: HWND, msg: &MSG, keys: &Shortcuts) -> bool {
unsafe {
if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {
return false;
}
if msg.hwnd != hwnd && !IsChild(hwnd, msg.hwnd).as_bool() {
return false;
}
let wants = SendMessageW(
msg.hwnd,
WM_GETDLGCODE,
Some(WPARAM(msg.wParam.0)),
Some(LPARAM(msg as *const MSG as isize)),
);
if wants.0 as u32 & DLGC_WANTMESSAGE != 0 {
return false;
}
let vk = msg.wParam.0 as u32;
let set = &keys.settings;
let is = |value: &String| shortcuts::pressed(keys, value, vk);
if is(&set.search) {
if let Ok(search) = GetDlgItem(Some(hwnd), ID_SEARCH as i32) {
let _ = SetFocus(Some(search));
SendMessageW(search, EM_SETSEL, Some(WPARAM(0)), Some(LPARAM(-1)));
}
} else if is(&set.save) {
SendMessageW(hwnd, WM_COMMAND, Some(WPARAM(ID_SAVE)), None);
} else if is(&set.close) {
SendMessageW(hwnd, WM_COMMAND, Some(WPARAM(ID_CANCEL)), None);
} else if is(&set.next_page) {
turn_page(hwnd, 1);
} else if is(&set.previous_page) {
turn_page(hwnd, -1);
} else {
return msg.message == WM_KEYDOWN && vk == u32::from(VK_ESCAPE.0);
}
true
}
}
fn key_hint(keys: &Shortcuts, value: &str) -> String {
match (keys.enabled, value.trim()) {
(true, key) if !key.is_empty() => format!(" ({key})"),
_ => String::new(),
}
}
unsafe fn turn_page(hwnd: HWND, step: i32) {
if !query(hwnd).is_empty() {
if let Ok(search) = GetDlgItem(Some(hwnd), ID_SEARCH as i32) {
let _ = SetWindowTextW(search, PCWSTR::null());
}
}
let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
if ptr.is_null() {
return;
}
let st = &mut *ptr;
let pages = PAGES.len() as i32;
st.page = (st.page as i32 + step).rem_euclid(pages) as usize;
relayout(hwnd, st);
}
pub fn refresh_status(hwnd: HWND) {
unsafe {
let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
if ptr.is_null() {
return;
}
let app = &*(*ptr).app;
let dnd = app.orch.dnd_status();
let text = format!("{} \u{2022} {}", app.orch.tooltip(), dnd);
if let Ok(h) = GetDlgItem(Some(hwnd), ID_STATUS as i32) {
let w = wide(&text);
let _ = SetWindowTextW(h, w.as_pcwstr());
}
}
}
fn num(v: f64) -> String {
if (v.fract()).abs() < 1e-9 {
format!("{}", v as i64)
} else {
format!("{v}")
}
}
unsafe fn text_of(parent: HWND, id: usize) -> String {
let h = GetDlgItem(Some(parent), id as i32).unwrap_or_default();
if h.is_invalid() {
return String::new();
}
let mut buf = [0u16; 256];
let n = GetWindowTextW(h, &mut buf);
String::from_utf16_lossy(&buf[..n as usize])
}
unsafe fn sync_dependencies(pane: HWND) {
let set_enabled = |id: usize, enabled: bool| {
if let Ok(control) = GetDlgItem(Some(pane), id as i32) {
let _ = EnableWindow(control, enabled);
}
};
let sequence = checked(pane, ID_SEQUENCE);
set_enabled(ID_AUTO_BREAK, sequence);
set_enabled(ID_AUTO_FOCUS, sequence);
set_enabled(ID_REPEAT_CYCLES, sequence);
let notifications = checked(pane, ID_NOTIFY);
for id in [ID_N_FS, ID_N_FE, ID_N_BS, ID_N_BE, ID_ALERT_TOAST] {
set_enabled(id, notifications);
}
set_enabled(ID_REQUIRE_DISMISS, checked(pane, ID_ALERT_OVERLAY));
let dnd = checked(pane, ID_DND);
set_enabled(ID_DND_SHORT_BREAK, dnd);
set_enabled(ID_MUTE_TRAY, dnd);
set_enabled(ID_MUTE_WINDOW, dnd);
let sounds_unmuted = !checked(pane, ID_MUTE);
for id in [ID_S_FS, ID_S_FE, ID_S_BS, ID_S_BE] {
set_enabled(id, sounds_unmuted);
}
set_enabled(ID_FLASH_LENGTH, checked(pane, ID_ALERT_FLASH));
set_enabled(ID_TOPMOST, checked(pane, ID_MINI));
let hotkeys = checked(pane, ID_HOTKEYS);
set_enabled(ID_HK_TOGGLE, hotkeys);
set_enabled(ID_HK_SKIP, hotkeys);
let keys = checked(pane, ID_KEYS);
for i in 0..shortcuts::ALL.len() {
set_enabled(ID_KEY + i, keys);
}
let _ = RedrawWindow(
Some(pane),
None,
None,
RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN,
);
}
unsafe fn checked(parent: HWND, id: usize) -> bool {
let h = GetDlgItem(Some(parent), id as i32).unwrap_or_default();
!h.is_invalid() && SendMessageW(h, BM_GETCHECK, None, None).0 == BST_CHECKED.0 as isize
}
unsafe fn set_checked(parent: HWND, id: usize, on: bool) {
if let Ok(h) = GetDlgItem(Some(parent), id as i32) {
SendMessageW(
h,
BM_SETCHECK,
Some(WPARAM(if on { BST_CHECKED.0 as usize } else { 0 })),
None,
);
}
}
unsafe fn combo_index(parent: HWND, id: usize) -> usize {
let h = GetDlgItem(Some(parent), id as i32).unwrap_or_default();
if h.is_invalid() {
return 0;
}
let i = SendMessageW(h, CB_GETCURSEL, None, None).0;
if i < 0 {
0
} else {
i as usize
}
}
fn parse_minutes(s: &str) -> Result<f64, ()> {
s.trim()
.parse::<f64>()
.ok()
.filter(|v| v.is_finite() && *v > 0.0)
.ok_or(())
}
unsafe fn read_preset(pane: HWND, base: &Preset) -> Result<Preset, &'static str> {
let name = text_of(pane, ID_NAME).trim().to_string();
Ok(Preset {
name: if name.is_empty() {
base.name.clone()
} else {
name
},
focus_minutes: parse_minutes(&text_of(pane, ID_FOCUS)).map_err(|_| "Focus (minutes)")?,
short_break_minutes: parse_minutes(&text_of(pane, ID_SHORT))
.map_err(|_| "Short break (minutes)")?,
long_break_minutes: parse_minutes(&text_of(pane, ID_LONG))
.map_err(|_| "Long break (minutes)")?,
sessions_before_long_break: text_of(pane, ID_SESSIONS)
.trim()
.parse::<u32>()
.ok()
.filter(|n| *n > 0)
.ok_or("Sessions per long break")?,
})
}
unsafe fn read_lock(pane: HWND, lock: &mut LockSettings) -> Result<(), String> {
for (index, name) in DAY_NAMES.iter().enumerate() {
let time = parse_time(&text_of(pane, ID_LOCK_TIME + index))
.ok_or_else(|| format!("{name}'s lock needs a time such as 5:45 PM or 17:45."))?;
*lock.day_mut(index) = DayLock {
enabled: checked(pane, ID_LOCK_DAY + index),
time,
strict: checked(pane, ID_LOCK_STRICT + index),
};
}
for (i, n) in LOCK_NUMBERS.iter().enumerate() {
let value = text_of(pane, ID_LOCK_NUMBER + i)
.trim()
.parse()
.ok()
.filter(|v| (n.min..=n.max).contains(v))
.ok_or_else(|| {
let (label, min, max) = (n.label, n.min, n.max);
format!("\"{label}\" needs a whole number from {min} to {max}.")
})?;
(n.set)(lock, value);
}
let max = lock.max_warn_before_lock();
if lock.warn_before_lock_minutes > max {
return Err(format!(
"\"Warn before lock (min)\" cannot be longer than the cutoff, so at most {max}."
));
}
Ok(())
}
unsafe fn collect(st: &mut State, save_as_new: bool) -> Result<Config, String> {
let pane = st.pane;
let app = &mut *st.app;
let mut cfg = app.config().clone();
let idx = st.current.min(st.presets.len().saturating_sub(1));
read_lock(pane, &mut cfg.lock)?;
let edited = read_preset(pane, &st.presets[idx])
.map_err(|field| format!("\"{field}\" needs a number greater than zero."))?;
if save_as_new && !st.presets.iter().any(|p| p.name == edited.name) {
st.presets.push(edited.clone());
} else {
st.presets[idx] = edited.clone();
}
cfg.presets = st.presets.clone();
cfg.active_preset = edited.name;
cfg.behavior.sequence_enabled = checked(pane, ID_SEQUENCE);
cfg.behavior.auto_start_break = checked(pane, ID_AUTO_BREAK);
cfg.behavior.auto_start_focus = checked(pane, ID_AUTO_FOCUS);
cfg.behavior.repeat_cycles = checked(pane, ID_REPEAT_CYCLES);
cfg.behavior.strict_focus = checked(pane, ID_STRICT);
cfg.behavior.restore_session_on_restart = checked(pane, ID_RESTORE_SESSION);
cfg.behavior.wake_policy = match combo_index(pane, ID_WAKE) {
1 => WakePolicy::IgnoreSleep,
2 => WakePolicy::Pause,
_ => WakePolicy::CountSleep,
};
cfg.dnd.enabled = checked(pane, ID_DND);
cfg.dnd.keep_on_short_break = checked(pane, ID_DND_SHORT_BREAK);
cfg.dnd.mute_tray_icon = checked(pane, ID_MUTE_TRAY);
cfg.dnd.mute_window = checked(pane, ID_MUTE_WINDOW);
cfg.display.mini_window = checked(pane, ID_MINI);
cfg.display.always_on_top = checked(pane, ID_TOPMOST);
cfg.notifications.enabled = checked(pane, ID_NOTIFY);
cfg.notifications.events.focus_start = checked(pane, ID_N_FS);
cfg.notifications.events.focus_end = checked(pane, ID_N_FE);
cfg.notifications.events.break_start = checked(pane, ID_N_BS);
cfg.notifications.events.break_end = checked(pane, ID_N_BE);
cfg.alerts.toast = checked(pane, ID_ALERT_TOAST);
cfg.alerts.overlay = checked(pane, ID_ALERT_OVERLAY);
cfg.alerts.flash = checked(pane, ID_ALERT_FLASH);
cfg.alerts.require_dismiss = checked(pane, ID_REQUIRE_DISMISS);
cfg.sounds.muted = checked(pane, ID_MUTE);
cfg.sounds.events.focus_start = checked(pane, ID_S_FS);
cfg.sounds.events.focus_end = checked(pane, ID_S_FE);
cfg.sounds.events.break_start = checked(pane, ID_S_BS);
cfg.sounds.events.break_end = checked(pane, ID_S_BE);
cfg.alerts.flash_length = LengthPreset::from_index(combo_index(pane, ID_FLASH_LENGTH));
cfg.hotkeys.enabled = checked(pane, ID_HOTKEYS);
cfg.hotkeys.toggle = text_of(pane, ID_HK_TOGGLE).trim().to_string();
cfg.hotkeys.skip = text_of(pane, ID_HK_SKIP).trim().to_string();
cfg.shortcuts.enabled = checked(pane, ID_KEYS);
for (i, key) in shortcuts::ALL.iter().enumerate() {
let mut value = text_of(pane, ID_KEY + i).trim().to_string();
if key.place == Place::Menu {
value = value.to_uppercase();
}
*(key.slot)(&mut cfg.shortcuts) = value;
}
shortcuts::validate(&cfg.shortcuts)?;
Ok(cfg)
}
unsafe fn show_preset(st: &State) {
let Some(p) = st.presets.get(st.current) else {
return;
};
for (id, val) in [
(ID_NAME, p.name.clone()),
(ID_FOCUS, num(p.focus_minutes)),
(ID_SHORT, num(p.short_break_minutes)),
(ID_LONG, num(p.long_break_minutes)),
(ID_SESSIONS, p.sessions_before_long_break.to_string()),
] {
if let Ok(h) = GetDlgItem(Some(st.pane), id as i32) {
let t = wide(&val);
let _ = SetWindowTextW(h, t.as_pcwstr());
}
}
}
unsafe fn restore_defaults(st: &mut State) {
let pane = st.pane;
let d = Config::default();
st.presets = d.presets.clone();
st.current = 0;
if let Ok(h) = GetDlgItem(Some(pane), ID_PRESET as i32) {
SendMessageW(h, CB_RESETCONTENT, None, None);
for p in &st.presets {
let t = wide(&p.name);
SendMessageW(
h,
CB_ADDSTRING,
None,
Some(LPARAM(t.as_pcwstr().0 as isize)),
);
}
SendMessageW(h, CB_SETCURSEL, Some(WPARAM(0)), None);
}
show_preset(st);
for (id, v) in [
(ID_SEQUENCE, d.behavior.sequence_enabled),
(ID_AUTO_BREAK, d.behavior.auto_start_break),
(ID_AUTO_FOCUS, d.behavior.auto_start_focus),
(ID_REPEAT_CYCLES, d.behavior.repeat_cycles),
(ID_STRICT, d.behavior.strict_focus),
(ID_RESTORE_SESSION, d.behavior.restore_session_on_restart),
(ID_DND, d.dnd.enabled),
(ID_DND_SHORT_BREAK, d.dnd.keep_on_short_break),
(ID_MUTE_TRAY, d.dnd.mute_tray_icon),
(ID_MUTE_WINDOW, d.dnd.mute_window),
(ID_MINI, d.display.mini_window),
(ID_TOPMOST, d.display.always_on_top),
(ID_NOTIFY, d.notifications.enabled),
(ID_N_FS, d.notifications.events.focus_start),
(ID_N_FE, d.notifications.events.focus_end),
(ID_N_BS, d.notifications.events.break_start),
(ID_N_BE, d.notifications.events.break_end),
(ID_MUTE, d.sounds.muted),
(ID_S_FS, d.sounds.events.focus_start),
(ID_S_FE, d.sounds.events.focus_end),
(ID_S_BS, d.sounds.events.break_start),
(ID_S_BE, d.sounds.events.break_end),
(ID_ALERT_TOAST, d.alerts.toast),
(ID_ALERT_OVERLAY, d.alerts.overlay),
(ID_ALERT_FLASH, d.alerts.flash),
(ID_REQUIRE_DISMISS, d.alerts.require_dismiss),
(ID_HOTKEYS, d.hotkeys.enabled),
(ID_AUTOSTART, false),
] {
set_checked(pane, id, v);
}
let set_text = |id: usize, text: &str| {
if let Ok(h) = GetDlgItem(Some(pane), id as i32) {
let _ = SetWindowTextW(h, wide(text).as_pcwstr());
}
};
for index in 0..7 {
let lock = d.lock.day(index);
set_checked(pane, ID_LOCK_DAY + index, lock.enabled);
set_checked(pane, ID_LOCK_STRICT + index, lock.strict);
set_text(ID_LOCK_TIME + index, &format_time(lock.time));
}
for (i, n) in LOCK_NUMBERS.iter().enumerate() {
set_text(ID_LOCK_NUMBER + i, &(n.get)(&d.lock).to_string());
}
set_checked(pane, ID_KEYS, d.shortcuts.enabled);
for (i, key) in shortcuts::ALL.iter().enumerate() {
set_text(ID_KEY + i, (key.get)(&d.shortcuts));
}
if let Ok(h) = GetDlgItem(Some(pane), ID_WAKE as i32) {
let sel = match d.behavior.wake_policy {
WakePolicy::CountSleep => 0,
WakePolicy::IgnoreSleep => 1,
WakePolicy::Pause => 2,
};
SendMessageW(h, CB_SETCURSEL, Some(WPARAM(sel)), None);
}
if let Ok(h) = GetDlgItem(Some(pane), ID_FLASH_LENGTH as i32) {
SendMessageW(
h,
CB_SETCURSEL,
Some(WPARAM(d.alerts.flash_length.index())),
None,
);
}
for (id, v) in [
(ID_HK_TOGGLE, d.hotkeys.toggle),
(ID_HK_SKIP, d.hotkeys.skip),
] {
if let Ok(h) = GetDlgItem(Some(pane), id as i32) {
let t = wide(&v);
let _ = SetWindowTextW(h, t.as_pcwstr());
}
}
}
unsafe fn paint_static(st: &State, in_pane: bool, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
let child = HWND(lparam.0 as *mut _);
let how = GetWindowLongPtrW(child, GWLP_USERDATA);
let hdc = HDC(wparam.0 as *mut _);
let enabled = IsWindowEnabled(child).as_bool() && linked_enabled(child);
let colour = match how {
_ if !enabled => fluent::TEXT_DISABLED,
paint_as::CARD_GREY | paint_as::PAGE_GREY | paint_as::WINDOW_GREY => fluent::TEXT_SECONDARY,
_ => fluent::TEXT,
};
SetTextColor(hdc, rgb(colour));
let brush = match how {
paint_as::FIELD if enabled => {
SetBkColor(hdc, rgb(fluent::FIELD));
st.field
}
paint_as::FIELD => {
SetBkColor(hdc, rgb(fluent::CARD));
st.card
}
paint_as::CARD | paint_as::CARD_GREY if in_pane => {
SetBkMode(hdc, TRANSPARENT);
st.card
}
_ => {
SetBkMode(hdc, TRANSPARENT);
st.page_bg
}
};
LRESULT(brush.0 as isize)
}
unsafe fn linked_enabled(child: HWND) -> bool {
let id = GetDlgCtrlID(child) as usize;
let owner = match id {
DESC_ID.. => id - DESC_ID,
CAPTION_ID.. => id - CAPTION_ID,
_ => return true,
};
let Ok(parent) = GetParent(child) else {
return true;
};
match GetDlgItem(Some(parent), owner as i32) {
Ok(h) => IsWindowEnabled(h).as_bool(),
Err(_) => true,
}
}
unsafe fn click_pane(st: &State, x: i32, y: i32) {
let point = POINT {
x,
y: y + st.scroll,
};
if let Some(f) = st
.fields
.iter()
.find(|f| PtInRect(&f.rect, point).as_bool())
{
let _ = SetFocus(Some(f.edit));
return;
}
let Some(card) = st.cards.iter().find(|c| PtInRect(&c.rect, point).as_bool()) else {
return;
};
if !card.toggles || !IsWindowEnabled(card.control).as_bool() {
return;
}
let _ = SetFocus(Some(card.control));
let id = GetDlgCtrlID(card.control) as usize;
let pane = st.pane;
set_checked(pane, id, !checked(pane, id));
SendMessageW(
pane,
WM_COMMAND,
Some(WPARAM(id | ((BN_CLICKED as usize) << 16))),
Some(LPARAM(card.control.0 as isize)),
);
}
unsafe extern "system" fn pane_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_COMMAND => {
let code = ((wparam.0 >> 16) & 0xFFFF) as u32;
if code == EN_SETFOCUS || code == EN_KILLFOCUS {
repaint_field(st, HWND(lparam.0 as *mut _));
}
if let Ok(parent) = GetParent(hwnd) {
SendMessageW(parent, WM_COMMAND, Some(wparam), Some(lparam));
}
LRESULT(0)
}
WM_NOTIFY => custom_draw(st, lparam),
WM_ERASEBKGND => LRESULT(1),
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
let hdc = BeginPaint(hwnd, &mut ps);
paint_pane(st, hwnd, hdc);
let _ = EndPaint(hwnd, &ps);
LRESULT(0)
}
WM_LBUTTONDOWN => {
let x = (lparam.0 & 0xFFFF) as i16 as i32;
let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;
click_pane(st, x, y);
LRESULT(0)
}
WM_CTLCOLORSTATIC | WM_CTLCOLOREDIT => paint_static(st, true, wparam, lparam),
WM_VSCROLL => {
let mut si = SCROLLINFO {
cbSize: std::mem::size_of::<SCROLLINFO>() as u32,
fMask: SIF_ALL,
..Default::default()
};
let _ = GetScrollInfo(hwnd, SB_VERT, &mut si);
let pos = match SCROLLBAR_COMMAND((wparam.0 & 0xFFFF) as i32) {
SB_LINEUP => st.scroll - 28,
SB_LINEDOWN => st.scroll + 28,
SB_PAGEUP => st.scroll - si.nPage as i32,
SB_PAGEDOWN => st.scroll + si.nPage as i32,
SB_THUMBTRACK | SB_THUMBPOSITION => si.nTrackPos,
SB_TOP => 0,
SB_BOTTOM => st.content_h,
_ => st.scroll,
};
scroll_to(st, pos);
LRESULT(0)
}
WM_MOUSEWHEEL => {
let delta = ((wparam.0 >> 16) & 0xFFFF) as i16;
scroll_to(st, st.scroll - delta as i32 * 48 / 120);
LRESULT(0)
}
_ => DefWindowProcW(hwnd, msg, wparam, lparam),
}
}
unsafe fn paint_window(st: &State, hdc: HDC) {
FillRect(hdc, &rect(0, 0, CLIENT_W, CLIENT_H), st.page_bg);
fluent::smooth(
hdc,
rect(0, FOOTER_Y, CLIENT_W, FOOTER_Y + 1),
fluent::CARD_EDGE,
&[],
);
let focused = GetDlgCtrlID(GetFocus()) as usize == ID_SEARCH;
fluent::smooth(
hdc,
SEARCH_BOX,
fluent::BACKGROUND,
&fluent::text_box(SEARCH_BOX, focused, true, st.accent),
);
let old_font = SelectObject(hdc, st.icons.into());
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, rgb(fluent::TEXT_SECONDARY));
draw_icon(
hdc,
"\u{E721}",
SEARCH_BOX.right - 32,
SEARCH_BOX.top,
24,
SEARCH_BOX.bottom - SEARCH_BOX.top,
);
SelectObject(hdc, old_font);
}
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);
}
match msg {
WM_ERASEBKGND => LRESULT(1),
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
let hdc = BeginPaint(hwnd, &mut ps);
paint_window(&*ptr, hdc);
let _ = EndPaint(hwnd, &ps);
LRESULT(0)
}
WM_NOTIFY => custom_draw(&*ptr, lparam),
WM_LBUTTONDOWN => {
let point = POINT {
x: (lparam.0 & 0xFFFF) as i16 as i32,
y: ((lparam.0 >> 16) & 0xFFFF) as i16 as i32,
};
if PtInRect(&SEARCH_BOX, point).as_bool() {
if let Ok(h) = GetDlgItem(Some(hwnd), ID_SEARCH as i32) {
let _ = SetFocus(Some(h));
}
}
LRESULT(0)
}
WM_CTLCOLORSTATIC | WM_CTLCOLOREDIT => paint_static(&*ptr, false, wparam, lparam),
WM_CTLCOLORLISTBOX => {
SetBkMode(HDC(wparam.0 as *mut _), TRANSPARENT);
LRESULT((*ptr).page_bg.0 as isize)
}
WM_DRAWITEM => {
let dis = &*(lparam.0 as *const DRAWITEMSTRUCT);
if dis.CtlID == ID_NAV as u32 && dis.itemID != u32::MAX {
paint_nav_item(&*ptr, dis);
}
LRESULT(1)
}
WM_COMMAND => {
let id = wparam.0 & 0xFFFF;
let code = ((wparam.0 >> 16) & 0xFFFF) as u32;
let st = &mut *ptr;
match (id, code) {
(ID_SEARCH, EN_CHANGE) => relayout(hwnd, st),
(ID_SEARCH, EN_SETFOCUS | EN_KILLFOCUS) => {
let _ = InvalidateRect(Some(hwnd), Some(&SEARCH_BOX), false);
}
(ID_NAV, LBN_SELCHANGE) => {
let sel = SendMessageW(
GetDlgItem(Some(hwnd), ID_NAV as i32).unwrap_or_default(),
LB_GETCURSEL,
None,
None,
)
.0;
if sel >= 0 {
st.page = sel as usize;
relayout(hwnd, st);
}
}
(ID_PRESET, CBN_SELCHANGE) => {
let idx = st.current.min(st.presets.len().saturating_sub(1));
if let Ok(p) = read_preset(st.pane, &st.presets[idx]) {
st.presets[idx] = p;
}
st.current = combo_index(st.pane, ID_PRESET);
show_preset(st);
}
(ID_DEFAULTS, BN_CLICKED) => {
restore_defaults(st);
sync_dependencies(st.pane);
}
(
ID_SEQUENCE | ID_NOTIFY | ID_ALERT_OVERLAY | ID_ALERT_FLASH | ID_DND | ID_MUTE
| ID_MINI | ID_HOTKEYS | ID_KEYS | ID_S_FS | ID_S_FE | ID_S_BS | ID_S_BE,
BN_CLICKED,
) => sync_dependencies(st.pane),
(ID_SAVE | ID_SAVE_AS, BN_CLICKED) => match collect(st, id == ID_SAVE_AS) {
Ok(cfg) => {
let autostart = crate::os::autostart::set(checked(st.pane, ID_AUTOSTART));
(*st.app).apply_config(cfg);
if let Err(why) = autostart {
let msg = wide(&format!(
"Start with Windows: {why}\n\nEverything else has been saved."
));
let cap = wide(crate::APP_NAME);
MessageBoxW(
Some(hwnd),
msg.as_pcwstr(),
cap.as_pcwstr(),
MB_OK | MB_ICONWARNING,
);
}
let _ = DestroyWindow(hwnd);
}
Err(problem) => {
let msg = wide(&format!("{problem}\n\nNothing has been saved."));
let cap = wide(crate::APP_NAME);
MessageBoxW(
Some(hwnd),
msg.as_pcwstr(),
cap.as_pcwstr(),
MB_OK | MB_ICONWARNING,
);
}
},
(ID_CANCEL, BN_CLICKED) => {
let _ = DestroyWindow(hwnd);
}
_ => {}
}
LRESULT(0)
}
WM_CLOSE => {
let _ = DestroyWindow(hwnd);
LRESULT(0)
}
WM_DESTROY => {
let st = Box::from_raw(ptr);
TIP_TEXT.with(|c| c.borrow_mut().clear());
for font in [st.font, st.small, st.bold, st.title, st.icons] {
let _ = DeleteObject(font.into());
}
for brush in [st.page_bg, st.card, st.field] {
let _ = DeleteObject(brush.into());
}
(*st.app).on_settings_closed();
SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
LRESULT(0)
}
_ => DefWindowProcW(hwnd, msg, wparam, lparam),
}
}