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
//! Modal Strict-focus confirmation, drawn like the session overlay.
//!
//! [`ask`] runs a nested message loop so the card can paint and accept
//! clicks. The caller must ignore other session commands until it returns,
//! otherwise a second Stop or Skip would open another card on top.

use std::sync::Once;

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::Input::KeyboardAndMouse::{VK_ESCAPE, VK_RETURN};
use windows::Win32::UI::WindowsAndMessaging::*;

use crate::ui::wide;

const CLASS: &str = "TaskbarFocusConfirm";
const W: i32 = 440;
const H: i32 = 228;

fn rgb(r: u8, g: u8, b: u8) -> COLORREF {
    COLORREF((b as u32) << 16 | (g as u32) << 8 | r as u32)
}

fn darken(c: COLORREF) -> COLORREF {
    let r = ((c.0 & 0xFF) as u8 as u16 * 3 / 4) as u8;
    let g = (((c.0 >> 8) & 0xFF) as u8 as u16 * 3 / 4) as u8;
    let b = (((c.0 >> 16) & 0xFF) as u8 as u16 * 3 / 4) as u8;
    rgb(r, g, b)
}

fn accent() -> COLORREF {
    rgb(0xE8, 0x56, 0x3F)
}

unsafe fn make_font(height: i32, weight: i32) -> HFONT {
    let face = wide("Segoe UI");
    let mut lf = LOGFONTW {
        lfHeight: -height,
        lfWeight: weight,
        lfQuality: CLEARTYPE_QUALITY,
        ..Default::default()
    };
    let name: Vec<u16> = face.as_pcwstr().as_wide().to_vec();
    for (i, c) in name.iter().take(31).enumerate() {
        lf.lfFaceName[i] = *c;
    }
    CreateFontIndirectW(&lf)
}

fn keep_rect() -> RECT {
    RECT {
        left: W - 168,
        top: H - 58,
        right: W - 24,
        bottom: H - 22,
    }
}

fn action_rect() -> RECT {
    RECT {
        left: 24,
        top: H - 58,
        right: 24 + 168,
        bottom: H - 22,
    }
}

fn hit(rc: RECT, x: i32, y: i32) -> bool {
    x >= rc.left && x < rc.right && y >= rc.top && y < rc.bottom
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Which {
    Keep,
    Action,
}

struct State {
    eyebrow: String,
    title: String,
    body: String,
    keep: String,
    action: String,
    font_eyebrow: HFONT,
    font_title: HFONT,
    font_body: HFONT,
    pressed: Option<Which>,
    accepted: *mut bool,
    finished: *mut bool,
}

fn register() {
    static ONCE: Once = Once::new();
    ONCE.call_once(|| unsafe {
        let Ok(instance) = GetModuleHandleW(None) else {
            return;
        };
        let class = wide(CLASS);
        let wc = WNDCLASSW {
            lpfnWndProc: Some(wndproc),
            hInstance: instance.into(),
            lpszClassName: class.as_pcwstr(),
            hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
            hIcon: crate::ui::app::shared_icon(),
            hbrBackground: HBRUSH(GetStockObject(BLACK_BRUSH).0),
            ..Default::default()
        };
        RegisterClassW(&wc);
    });
}

/// What is asked, and what the two buttons say.
pub struct Question<'a> {
    pub eyebrow: &'a str,
    pub title: &'a str,
    pub body: &'a str,
    /// The button that changes nothing.
    pub keep: &'a str,
    pub action: &'a str,
}

thread_local! {
    /// The card currently waiting for an answer.
    static OPEN: std::cell::Cell<HWND> = std::cell::Cell::new(HWND::default());
}

/// Whether a card is waiting for an answer.
pub fn is_open() -> bool {
    !OPEN.get().is_invalid()
}

/// Close an open card as if it had been declined.
pub fn cancel() {
    let open = OPEN.get();
    if !open.is_invalid() {
        unsafe {
            let _ = DestroyWindow(open);
        }
    }
}

/// Ask before something that is hard to take back. `true` means the user chose
/// the action. Escape and Enter decline.
pub fn ask(owner: HWND, q: &Question) -> bool {
    register();
    unsafe {
        let Ok(instance) = GetModuleHandleW(None) else {
            return false;
        };
        let work = crate::ui::alert::monitor_work(owner);
        let x = work.left + ((work.right - work.left) - W) / 2;
        let y = work.top + ((work.bottom - work.top) - H) / 2;

        let mut accepted = false;
        let mut finished = false;

        let hwnd = match CreateWindowExW(
            WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
            wide(CLASS).as_pcwstr(),
            wide(q.title).as_pcwstr(),
            WS_POPUP | WS_VISIBLE,
            x,
            y,
            W,
            H,
            Some(owner),
            None,
            Some(instance.into()),
            None,
        ) {
            Ok(h) => h,
            Err(_) => return false,
        };

        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 {
            eyebrow: q.eyebrow.to_string(),
            title: q.title.to_string(),
            body: q.body.to_string(),
            keep: q.keep.to_string(),
            action: q.action.to_string(),
            font_eyebrow: make_font(13, FW_SEMIBOLD.0 as i32),
            font_title: make_font(26, FW_SEMIBOLD.0 as i32),
            font_body: make_font(16, FW_NORMAL.0 as i32),
            pressed: None,
            accepted: &mut accepted,
            finished: &mut finished,
        });
        SetWindowLongPtrW(hwnd, GWLP_USERDATA, Box::into_raw(st) as isize);
        let _ = SetForegroundWindow(hwnd);
        OPEN.set(hwnd);

        let mut msg = MSG::default();
        loop {
            match GetMessageW(&mut msg, None, 0, 0).0 {
                0 => {
                    PostQuitMessage(msg.wParam.0 as i32);
                    break;
                }
                -1 => break,
                _ => {}
            }
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
            if finished || !IsWindow(Some(hwnd)).as_bool() {
                break;
            }
        }
        OPEN.set(HWND::default());
        accepted
    }
}

unsafe fn paint_pill(
    hdc: HDC,
    rc: RECT,
    fill: COLORREF,
    text: &str,
    text_color: COLORREF,
    font: HFONT,
) {
    let brush = CreateSolidBrush(fill);
    let pen = CreatePen(PS_SOLID, 1, fill);
    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());

    SetBkMode(hdc, TRANSPARENT);
    SetTextColor(hdc, text_color);
    let old = SelectObject(hdc, font.into());
    let mut label: Vec<u16> = text.encode_utf16().collect();
    let mut text_rc = rc;
    DrawTextW(
        hdc,
        &mut label,
        &mut text_rc,
        DT_CENTER | DT_VCENTER | DT_SINGLELINE,
    );
    SelectObject(hdc, old);
}

unsafe fn finish(hwnd: HWND, accepted: bool) {
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
    if !ptr.is_null() {
        *(*ptr).accepted = accepted;
        *(*ptr).finished = true;
    }
    let _ = DestroyWindow(hwnd);
}

unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
    match msg {
        WM_PAINT => {
            if ptr.is_null() {
                return DefWindowProcW(hwnd, msg, wparam, lparam);
            }
            let st = &*ptr;
            let mut ps = PAINTSTRUCT::default();
            let hdc = BeginPaint(hwnd, &mut ps);
            let mut rc = RECT::default();
            let _ = GetClientRect(hwnd, &mut rc);
            let bg = CreateSolidBrush(rgb(0x22, 0x20, 0x1E));
            FillRect(hdc, &rc, bg);
            let _ = DeleteObject(bg.into());

            let stripe = RECT {
                left: 0,
                top: 0,
                right: rc.right,
                bottom: 5,
            };
            let stripe_brush = CreateSolidBrush(accent());
            FillRect(hdc, &stripe, stripe_brush);
            let _ = DeleteObject(stripe_brush.into());

            SetBkMode(hdc, TRANSPARENT);
            crate::ui::paint_header(
                hdc,
                RECT {
                    left: 24,
                    top: 26,
                    right: rc.right - 24,
                    bottom: 50,
                },
                st.font_eyebrow,
                rgb(0xD2, 0xCB, 0xC4),
                &st.eyebrow,
            );
            let old = SelectObject(hdc, st.font_eyebrow.into());

            SelectObject(hdc, st.font_title.into());
            SetTextColor(hdc, rgb(0xF7, 0xF5, 0xF2));
            let mut title: Vec<u16> = st.title.encode_utf16().collect();
            let mut title_rc = RECT {
                left: 24,
                top: 60,
                right: rc.right - 24,
                bottom: 104,
            };
            DrawTextW(hdc, &mut title, &mut title_rc, DT_LEFT | DT_WORDBREAK);

            SelectObject(hdc, st.font_body.into());
            SetTextColor(hdc, rgb(0xA8, 0xA2, 0x9C));
            let mut body: Vec<u16> = st.body.encode_utf16().collect();
            let mut body_rc = RECT {
                left: 24,
                top: 108,
                right: rc.right - 24,
                bottom: rc.bottom - 74,
            };
            DrawTextW(hdc, &mut body, &mut body_rc, DT_LEFT | DT_WORDBREAK);

            let keep_fill = if st.pressed == Some(Which::Keep) {
                rgb(0xE0, 0xDC, 0xD6)
            } else {
                rgb(0xF7, 0xF5, 0xF2)
            };
            paint_pill(
                hdc,
                keep_rect(),
                keep_fill,
                &st.keep,
                rgb(0x1C, 0x1A, 0x18),
                st.font_body,
            );
            let action_fill = if st.pressed == Some(Which::Action) {
                darken(accent())
            } else {
                accent()
            };
            paint_pill(
                hdc,
                action_rect(),
                action_fill,
                &st.action,
                rgb(0xFF, 0xFF, 0xFF),
                st.font_body,
            );
            SelectObject(hdc, old);
            let _ = EndPaint(hwnd, &ps);
            LRESULT(0)
        }
        WM_LBUTTONDOWN => {
            if ptr.is_null() {
                return LRESULT(0);
            }
            let x = (lparam.0 as i32) & 0xFFFF;
            let y = ((lparam.0 as i32) >> 16) & 0xFFFF;
            let which = if hit(keep_rect(), x, y) {
                Some(Which::Keep)
            } else if hit(action_rect(), x, y) {
                Some(Which::Action)
            } else {
                None
            };
            (*ptr).pressed = which;
            if which.is_some() {
                let _ = InvalidateRect(Some(hwnd), None, true);
            }
            LRESULT(0)
        }
        WM_LBUTTONUP => {
            if ptr.is_null() {
                return LRESULT(0);
            }
            let x = (lparam.0 as i32) & 0xFFFF;
            let y = ((lparam.0 as i32) >> 16) & 0xFFFF;
            let was = (*ptr).pressed;
            (*ptr).pressed = None;
            let _ = InvalidateRect(Some(hwnd), None, true);
            match was {
                Some(Which::Keep) if hit(keep_rect(), x, y) => finish(hwnd, false),
                Some(Which::Action) if hit(action_rect(), x, y) => finish(hwnd, true),
                _ => {}
            }
            LRESULT(0)
        }
        WM_KEYDOWN if wparam.0 == VK_ESCAPE.0 as usize || wparam.0 == VK_RETURN.0 as usize => {
            finish(hwnd, false);
            LRESULT(0)
        }
        WM_DESTROY => {
            if !ptr.is_null() {
                let st = Box::from_raw(ptr);
                *st.finished = true;
                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),
    }
}