taskbar-focus 0.5.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Drawing in the Windows 11 style for windows built from classic controls:
//! rounded surfaces, switches and buttons.
//!
//! GDI draws curves without anti-aliasing, which leaves rounded corners and
//! round switch knobs visibly jagged. Each shape is therefore drawn at four
//! times its size onto the colour it will sit on, then scaled down with
//! averaging. Text is drawn afterwards at normal size, so it keeps ClearType.

use windows::Win32::Foundation::{COLORREF, RECT};
use windows::Win32::Graphics::Gdi::{
    CreateCompatibleBitmap, CreateCompatibleDC, CreateDIBSection, CreateFontIndirectW,
    CreateSolidBrush, DeleteDC, DeleteObject, DrawTextW, Ellipse, FillRect, GdiFlush, GetDC,
    GetStockObject, GetTextFaceW, ReleaseDC, RoundRect, SelectObject, SetBkMode, SetBrushOrgEx,
    SetStretchBltMode, SetTextColor, StretchBlt, ANTIALIASED_QUALITY, BITMAPINFO, BITMAPINFOHEADER,
    BI_RGB, DEFAULT_CHARSET, DIB_RGB_COLORS, DT_CENTER, DT_NOPREFIX, DT_SINGLELINE, DT_VCENTER,
    HALFTONE, HBITMAP, HDC, HFONT, LOGFONTW, NULL_PEN, SRCCOPY, TRANSPARENT,
};
use windows::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSMICON};

/// How many times larger shapes are drawn before being scaled down.
const SCALE: i32 = 4;

/// `0xRRGGBB`, the way colours are usually written, as a GDI colour.
pub const fn rgb(c: u32) -> COLORREF {
    COLORREF(((c & 0xFF) << 16) | (c & 0xFF00) | ((c >> 16) & 0xFF))
}

pub const BACKGROUND: u32 = 0xF3F3F3;
pub const CARD: u32 = 0xFBFBFB;
pub const CARD_EDGE: u32 = 0xE5E5E5;
pub const FIELD: u32 = 0xFFFFFF;
pub const FIELD_UNDERLINE: u32 = 0x8A8A8A;
pub const SELECTED: u32 = 0xE9E9E9;
pub const TEXT: u32 = 0x1B1B1B;
pub const TEXT_SECONDARY: u32 = 0x5F5F5F;
pub const TEXT_DISABLED: u32 = 0xA0A0A0;

/// Something drawn by [`smooth`], in the coordinates of the area it covers.
pub enum Shape {
    /// A rounded rectangle, optionally with a one-pixel edge in another colour.
    Rounded {
        rect: RECT,
        radius: i32,
        fill: u32,
        edge: Option<u32>,
    },
    Circle {
        x: i32,
        y: i32,
        diameter: i32,
        fill: u32,
    },
    /// A plain rectangle, for underlines and stripes.
    Bar { rect: RECT, fill: u32 },
}

/// Draw `shapes` smoothly over `area` of `hdc`, which is first filled with
/// `background`.
///
/// # Safety
/// `hdc` must be a valid device context.
pub unsafe fn smooth(hdc: HDC, area: RECT, background: u32, shapes: &[Shape]) {
    let (w, h) = (area.right - area.left, area.bottom - area.top);
    if w <= 0 || h <= 0 {
        return;
    }
    let big = CreateCompatibleDC(Some(hdc));
    let bitmap = CreateCompatibleBitmap(hdc, w * SCALE, h * SCALE);
    let old_bitmap = SelectObject(big, bitmap.into());
    let old_pen = SelectObject(big, GetStockObject(NULL_PEN));
    fill(big, scaled(rect(0, 0, w, h), 0, 0), background);
    let local = |r: RECT| scaled(r, area.left, area.top);
    for shape in shapes {
        match *shape {
            Shape::Rounded {
                rect: r,
                radius,
                fill: colour,
                edge,
            } => {
                let r = local(r);
                let round = radius * 2 * SCALE;
                if let Some(edge) = edge {
                    rounded(big, r, round, edge);
                    let inner = RECT {
                        left: r.left + SCALE,
                        top: r.top + SCALE,
                        right: r.right - SCALE,
                        bottom: r.bottom - SCALE,
                    };
                    rounded(big, inner, (round - 2 * SCALE).max(0), colour);
                } else {
                    rounded(big, r, round, colour);
                }
            }
            Shape::Circle {
                x,
                y,
                diameter,
                fill: colour,
            } => {
                let r = local(rect(x, y, x + diameter, y + diameter));
                let brush = CreateSolidBrush(rgb(colour));
                let old = SelectObject(big, brush.into());
                let _ = Ellipse(big, r.left, r.top, r.right + 1, r.bottom + 1);
                SelectObject(big, old);
                let _ = DeleteObject(brush.into());
            }
            Shape::Bar { rect: r, fill: c } => fill(big, local(r), c),
        }
    }
    SetStretchBltMode(hdc, HALFTONE);
    let _ = SetBrushOrgEx(hdc, 0, 0, None);
    let _ = StretchBlt(
        hdc,
        area.left,
        area.top,
        w,
        h,
        Some(big),
        0,
        0,
        w * SCALE,
        h * SCALE,
        SRCCOPY,
    );
    SelectObject(big, old_pen);
    SelectObject(big, old_bitmap);
    let _ = DeleteObject(bitmap.into());
    let _ = DeleteDC(big);
}

pub const fn rect(left: i32, top: i32, right: i32, bottom: i32) -> RECT {
    RECT {
        left,
        top,
        right,
        bottom,
    }
}

fn scaled(r: RECT, dx: i32, dy: i32) -> RECT {
    rect(
        (r.left - dx) * SCALE,
        (r.top - dy) * SCALE,
        (r.right - dx) * SCALE,
        (r.bottom - dy) * SCALE,
    )
}

unsafe fn fill(hdc: HDC, r: RECT, colour: u32) {
    let brush = CreateSolidBrush(rgb(colour));
    FillRect(hdc, &r, brush);
    let _ = DeleteObject(brush.into());
}

unsafe fn rounded(hdc: HDC, r: RECT, round: i32, colour: u32) {
    let brush = CreateSolidBrush(rgb(colour));
    let old = SelectObject(hdc, brush.into());
    let _ = RoundRect(hdc, r.left, r.top, r.right + 1, r.bottom + 1, round, round);
    SelectObject(hdc, old);
    let _ = DeleteObject(brush.into());
}

/// Width and height of a switch's track.
pub const SWITCH_W: i32 = 40;
pub const SWITCH_H: i32 = 20;

/// How a control is being interacted with right now.
#[derive(Clone, Copy, Default)]
pub struct Look {
    pub enabled: bool,
    pub hot: bool,
    pub pressed: bool,
    /// Keyboard focus, shown only when Windows says focus cues are wanted.
    pub focus: bool,
}

/// The shapes of an on/off switch whose track's top-left corner is at `x`,
/// `y`, followed by a focus ring when it has keyboard focus.
pub fn switch(x: i32, y: i32, on: bool, look: Look, accent: u32) -> Vec<Shape> {
    let track = rect(x, y, x + SWITCH_W, y + SWITCH_H);
    let mut shapes = Vec::new();
    if look.focus {
        shapes.push(Shape::Rounded {
            rect: rect(x - 3, y - 3, x + SWITCH_W + 3, y + SWITCH_H + 3),
            radius: SWITCH_H / 2 + 3,
            fill: CARD,
            edge: Some(TEXT),
        });
    }
    let knob = if look.hot || look.pressed { 14 } else { 12 };
    let (track_fill, edge, knob_fill) = match (on, look.enabled) {
        (true, true) => (
            if look.hot { lighten(accent) } else { accent },
            None,
            0xFFFFFF,
        ),
        (true, false) => (0xC5C5C5, None, 0xFFFFFF),
        (false, true) => (
            if look.hot { 0xEDEDED } else { CARD },
            Some(0x8A8A8A),
            0x5D5D5D,
        ),
        (false, false) => (CARD, Some(0xC5C5C5), 0xC5C5C5),
    };
    shapes.push(Shape::Rounded {
        rect: track,
        radius: SWITCH_H / 2,
        fill: track_fill,
        edge,
    });
    let centre = if on { x + SWITCH_W - 10 } else { x + 10 };
    shapes.push(Shape::Circle {
        x: centre - knob / 2,
        y: y + (SWITCH_H - knob) / 2,
        diameter: knob,
        fill: knob_fill,
    });
    shapes
}

/// The shapes of a button filling `area`. `primary` is the accent-coloured
/// button that does what the window is for.
pub fn button(area: RECT, primary: bool, look: Look, accent: u32) -> Vec<Shape> {
    let (fill, edge) = match (primary, look.enabled) {
        (true, true) if look.pressed => (darken(accent), None),
        (true, true) if look.hot => (lighten(accent), None),
        (true, true) => (accent, None),
        (true, false) => (0xBFBFBF, None),
        (false, _) if look.pressed => (0xF5F5F5, Some(CARD_EDGE)),
        (false, _) if look.hot => (0xF6F6F6, Some(CARD_EDGE)),
        (false, _) => (CARD, Some(CARD_EDGE)),
    };
    let mut shapes = Vec::new();
    let inner = if look.focus {
        shapes.push(Shape::Rounded {
            rect: area,
            radius: 6,
            fill: BACKGROUND,
            edge: Some(TEXT),
        });
        rect(area.left + 3, area.top + 3, area.right - 3, area.bottom - 3)
    } else {
        area
    };
    shapes.push(Shape::Rounded {
        rect: inner,
        radius: 4,
        fill,
        edge,
    });
    shapes
}

/// The shapes of a text box filling `area`, with the accent underline it gets
/// while it has the keyboard focus.
pub fn text_box(area: RECT, focused: bool, enabled: bool, accent: u32) -> Vec<Shape> {
    let underline = match (focused, enabled) {
        (true, _) => accent,
        (false, true) => FIELD_UNDERLINE,
        (false, false) => CARD_EDGE,
    };
    let thick = if focused { 2 } else { 1 };
    vec![
        Shape::Rounded {
            rect: area,
            radius: 4,
            fill: if enabled { FIELD } else { CARD },
            edge: Some(CARD_EDGE),
        },
        Shape::Bar {
            rect: rect(
                area.left + 3,
                area.bottom - thick,
                area.right - 3,
                area.bottom,
            ),
            fill: underline,
        },
    ]
}

fn channel(c: u32, shift: u32, f: impl Fn(u32) -> u32) -> u32 {
    f((c >> shift) & 0xFF).min(255) << shift
}

fn lighten(c: u32) -> u32 {
    let up = |v: u32| v + (255 - v) / 8;
    channel(c, 16, up) | channel(c, 8, up) | channel(c, 0, up)
}

fn darken(c: u32) -> u32 {
    let down = |v: u32| v * 7 / 8;
    channel(c, 16, down) | channel(c, 8, down) | channel(c, 0, down)
}

/// The user's accent colour as `0xRRGGBB`, in the darker shade Windows 11
/// fills switches and buttons with on a light background.
///
/// Windows offers no plain Win32 call for it. It is read from the palette the
/// shell keeps under `HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Accent`,
/// whose fifth entry is that shade. Without the palette, the default Windows
/// 11 blue is used.
pub fn accent() -> u32 {
    const DEFAULT: u32 = 0x005FB8;
    const DARK_1: usize = 4;
    let palette = crate::os::registry::Key::open_read(
        r"Software\Microsoft\Windows\CurrentVersion\Explorer\Accent",
    )
    .and_then(|key| key.get_binary("AccentPalette"));
    match palette
        .as_deref()
        .and_then(|p| p.get(DARK_1 * 4..DARK_1 * 4 + 3))
    {
        Some([r, g, b]) => (u32::from(*r) << 16) | (u32::from(*g) << 8) | u32::from(*b),
        _ => DEFAULT,
    }
}

/// The system icon font, which is where the glyphs of the settings window and the tray menu come
/// from.
///
/// Windows 11 ships Segoe Fluent Icons and Windows 10 shipped Segoe MDL2
/// Assets; the two use the same code points for the glyphs used here. GDI
/// substitutes silently when a face is missing, drawing empty boxes, so each
/// candidate is asked for by name and then checked against what was actually
/// created.
///
/// # Safety
/// Calls GDI; the caller owns and must delete the returned font.
pub unsafe fn icon_font(base: &LOGFONTW) -> HFONT {
    for face in ["Segoe Fluent Icons", "Segoe MDL2 Assets", "Segoe UI Symbol"] {
        let mut lf = *base;
        set_face(&mut lf, face);
        let font = CreateFontIndirectW(&lf);
        if font_is(font, face) {
            return font;
        }
        let _ = DeleteObject(font.into());
    }
    CreateFontIndirectW(base)
}

/// Whether `font` really is the typeface it asked for.
///
/// # Safety
/// `font` must be a valid font handle.
pub unsafe fn font_is(font: HFONT, face: &str) -> bool {
    let hdc = GetDC(None);
    if hdc.is_invalid() {
        return false;
    }
    let old = SelectObject(hdc, font.into());
    let mut name = [0u16; 32];
    let n = GetTextFaceW(hdc, Some(&mut name));
    SelectObject(hdc, old);
    ReleaseDC(None, hdc);
    n > 1 && String::from_utf16_lossy(&name[..n as usize - 1]) == face
}

/// Name the typeface a font description asks for.
pub fn set_face(lf: &mut LOGFONTW, name: &str) {
    lf.lfFaceName = [0; 32];
    for (slot, ch) in lf.lfFaceName.iter_mut().zip(name.encode_utf16()) {
        *slot = ch;
    }
}

/// A glyph of the icon font as a bitmap with transparency, drawn in `colour`,
/// for the icon column of a menu. It is the size of a small icon, 16 pixels at
/// normal scaling.
///
/// Menus keep the bitmap they are given, so each glyph and colour is drawn
/// once and kept for the life of the process. A failed drawing is not kept,
/// so the next menu tries again.
pub fn glyph_bitmap(glyph: &str, colour: u32) -> HBITMAP {
    use std::collections::HashMap;
    use std::sync::Mutex;
    static CACHE: Mutex<Option<HashMap<(String, u32), isize>>> = Mutex::new(None);
    let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
    let cache = cache.get_or_insert_with(HashMap::new);
    let key = (glyph.to_string(), colour);
    if let Some(&raw) = cache.get(&key) {
        return HBITMAP(raw as *mut _);
    }
    let raw = unsafe { draw_glyph(glyph, colour) };
    if raw != 0 {
        cache.insert(key, raw);
    }
    HBITMAP(raw as *mut _)
}

/// How strongly [`draw_glyph`] darkens the soft edges of a glyph. 1 leaves
/// them as measured; higher values make strokes look heavier.
const GLYPH_CONTRAST: f32 = 1.5;

/// Draw a glyph for [`glyph_bitmap`].
///
/// At 16 pixels Windows draws this font without smoothing, so curves and
/// diagonals come out as hard steps beside crisp straight lines. The glyph is
/// therefore drawn [`SCALE`] times larger, white on black, and each pixel of
/// the result takes the average brightness of the pixels it covers as its
/// opacity, the way Windows' own menu icons are smoothed. Partly covered
/// pixels are then darkened by [`GLYPH_CONTRAST`], so that the thin strokes
/// read as solid lines rather than grey ones.
unsafe fn draw_glyph(glyph: &str, colour: u32) -> isize {
    let size = GetSystemMetrics(SM_CXSMICON).max(16);
    let big = size * SCALE;
    let Some((large, large_bits)) = dib(big) else {
        return 0;
    };
    let Some((bitmap, bits)) = dib(size) else {
        let _ = DeleteObject(large.into());
        return 0;
    };
    let dc = CreateCompatibleDC(None);
    let old_bitmap = SelectObject(dc, large.into());
    let base = LOGFONTW {
        lfHeight: -big,
        lfWeight: 400,
        lfCharSet: DEFAULT_CHARSET,
        lfQuality: ANTIALIASED_QUALITY,
        ..Default::default()
    };
    let font = icon_font(&base);
    let old_font = SelectObject(dc, font.into());
    SetBkMode(dc, TRANSPARENT);
    SetTextColor(dc, rgb(0xFFFFFF));
    let mut text: Vec<u16> = glyph.encode_utf16().collect();
    let mut area = rect(0, 0, big, big);
    DrawTextW(
        dc,
        &mut text,
        &mut area,
        DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX,
    );
    let _ = GdiFlush();
    let source = std::slice::from_raw_parts(large_bits, (big * big) as usize);
    let pixels = std::slice::from_raw_parts_mut(bits, (size * size) as usize);
    let (r, g, b) = ((colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF);
    let (size, scale) = (size as usize, SCALE as usize);
    for (index, p) in pixels.iter_mut().enumerate() {
        let (x, y) = (index % size * scale, index / size * scale);
        let total: u32 = (0..scale)
            .flat_map(|dy| (0..scale).map(move |dx| (dx, dy)))
            .map(|(dx, dy)| brightness(source[(y + dy) * size * scale + x + dx]))
            .sum();
        let coverage = total as f32 / (scale * scale * 255) as f32;
        let a = (coverage.powf(1.0 / GLYPH_CONTRAST) * 255.0).round() as u32;
        *p = (a << 24) | ((r * a / 255) << 16) | ((g * a / 255) << 8) | (b * a / 255);
    }
    SelectObject(dc, old_font);
    let _ = DeleteObject(font.into());
    SelectObject(dc, old_bitmap);
    let _ = DeleteDC(dc);
    let _ = DeleteObject(large.into());
    bitmap.0 as isize
}

/// The brightest channel of a pixel drawn white on black.
fn brightness(pixel: u32) -> u32 {
    (pixel & 0xFF)
        .max((pixel >> 8) & 0xFF)
        .max((pixel >> 16) & 0xFF)
}

/// A blank square 32-bit bitmap, top row first, and its pixels.
unsafe fn dib(size: i32) -> Option<(HBITMAP, *mut u32)> {
    let info = BITMAPINFO {
        bmiHeader: BITMAPINFOHEADER {
            biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
            biWidth: size,
            biHeight: -size,
            biPlanes: 1,
            biBitCount: 32,
            biCompression: BI_RGB.0,
            ..Default::default()
        },
        ..Default::default()
    };
    let screen = GetDC(None);
    let mut bits = std::ptr::null_mut();
    let bitmap = CreateDIBSection(Some(screen), &info, DIB_RGB_COLORS, &mut bits, None, 0);
    ReleaseDC(None, screen);
    bitmap.ok().map(|b| (b, bits as *mut u32))
}