taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! The card for PC locks: warnings, countdowns and refusals.
//!
//! Like the alerts it is an ordinary top-most window, so Do Not Disturb cannot
//! hide it. It differs in that clicking outside never closes it. Countdown
//! cards do not dim the screen, because the dimmed area blocks every click and
//! a countdown is the only time left to use the PC.

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";

/// Posted to the owner when a button is clicked: `wparam` is its index.
pub const WM_LOCK_CARD: u32 = WM_APP + 4;

const W: i32 = 460;
const H: i32 = 248;
const GAP: i32 = 12;

/// What a card says.
#[derive(Clone, PartialEq, Eq)]
pub struct Content {
    pub title: String,
    pub body: String,
    pub buttons: Vec<String>,
    /// Darken the screen behind the card.
    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)
}

/// Buttons run from the right edge; the last one is rightmost.
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)
}

/// Show a card in the middle of the anchor's monitor.
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)
}

/// Replace what an open card says. The buttons keep their places.
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),
    }
}