hdrshot-gui 2.5.0

HDR image tool: desktop app for converting HDR screenshots and images
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
//! Region screenshots on Windows. The region shortcut, or the tray menu,
//! captures the screen with the mouse pointer and shows it frozen in a
//! window over it, dimmed. Dragging a box with the left button saves just
//! that part, in HDR like any screenshot; a click without dragging saves
//! the window under the pointer instead. Escape, a right click, switching
//! to another window or a minute without a choice cancels.
//!
//! The overlay is a plain Win32 window drawn with GDI, apart from the
//! app's egui window, so it works the same with the app in the tray. It
//! shows an SDR copy of the HDR picture, as GDI can only draw SDR.

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use rayon::prelude::*;

use crate::screenshot::{Options, Rect, Taken};

/// How wide and high a dragged box must be at least to count as one, in
/// pixels at 100% scale; a thinner drag is a click.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) const MIN_DRAG: i32 = 8;

/// Whether a region is being taken: the screen captured and the overlay
/// shown over it, or about to be.
static SHOWING: AtomicBool = AtomicBool::new(false);

/// Whether the overlay shows, or is about to. Other screenshots wait for
/// it, as they would capture it, dimmed.
pub(crate) fn showing() -> bool {
    SHOWING.load(Ordering::Acquire)
}

/// Marks the overlay as showing while this lives; `None` if it already
/// is, from the shortcut or the tray menu.
#[cfg_attr(not(windows), allow(dead_code))]
struct Showing;

#[cfg_attr(not(windows), allow(dead_code))]
impl Showing {
    fn begin() -> Option<Self> {
        SHOWING
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .ok()
            .map(|_| Self)
    }
}

impl Drop for Showing {
    fn drop(&mut self) {
        SHOWING.store(false, Ordering::Release);
    }
}

/// What the user chose on the overlay, in the overlay's coordinates: 0, 0
/// is the screen's top left pixel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) enum Pick {
    Cancel,
    /// Clicked without dragging: the window there.
    Point(i32, i32),
    /// Dragged a box.
    Area(Rect),
}

/// The box between where the drag started, `from`, and the pointer, `to`,
/// both pixels included, within a screen `width` by `height`.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn drag_rect(from: (i32, i32), to: (i32, i32), width: i32, height: i32) -> Rect {
    let clamp = |v: i32, max: i32| v.clamp(0, (max - 1).max(0));
    let (x0, x1) = (clamp(from.0, width), clamp(to.0, width));
    let (y0, y1) = (clamp(from.1, height), clamp(to.1, height));
    Rect {
        left: x0.min(x1),
        top: y0.min(y1),
        right: x0.max(x1) + 1,
        bottom: y0.max(y1) + 1,
    }
}

/// What releasing the button at `to` after pressing it at `from` picks: a
/// box at least `min` pixels wide and high, else a click where it was
/// pressed, so that a thin sliver isn't saved by a shaky click.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn pick(from: (i32, i32), to: (i32, i32), width: i32, height: i32, min: i32) -> Pick {
    let rect = drag_rect(from, to, width, height);
    if rect.width() >= min && rect.height() >= min {
        Pick::Area(rect)
    } else {
        Pick::Point(from.0, from.1)
    }
}

/// The first of `windows`, listed from the front with their places, that
/// holds the desktop point `(x, y)`.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn window_at<T: Copy>(windows: &[(T, Rect)], (x, y): (i32, i32)) -> Option<(T, Rect)> {
    windows
        .iter()
        .find(|(_, r)| (r.left..r.right).contains(&x) && (r.top..r.bottom).contains(&y))
        .copied()
}

/// The size label shown with the box, e.g. "1920 x 1080".
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn size_label(rect: Rect) -> String {
    format!("{} x {}", rect.width(), rect.height())
}

/// Where the size label, `label` wide and high, goes for the box
/// `selection` on a screen `width` by `height`: below the box at its left
/// edge, else above it, else inside its top left corner when the box fills
/// the screen; `gap` pixels from the box and always on the screen.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn label_place(
    selection: Rect,
    label: (i32, i32),
    width: i32,
    height: i32,
    gap: i32,
) -> (i32, i32) {
    let (w, h) = label;
    let fit_x = |x: i32| x.min(width - w).max(0);
    let fit_y = |y: i32| y.min(height - h).max(0);
    let below = selection.bottom + gap;
    let above = selection.top - gap - h;
    if below + h <= height {
        (fit_x(selection.left), below)
    } else if above >= 0 {
        (fit_x(selection.left), above)
    } else {
        (fit_x(selection.left + gap), fit_y(selection.top + gap))
    }
}

/// Below this, relative to SDR white, the preview shows a pixel as is;
/// brighter ones are rolled off smoothly into the rest of the range.
const KNEE: f32 = 0.9;

/// Highlight roll-off: `value` relative to SDR white (1.0) to 0..1, the
/// identity up to the knee, then approaching 1 without reaching it.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn roll_off(value: f32) -> f32 {
    if value <= KNEE {
        return value.max(0.0);
    }
    let x = (value - KNEE) / (1.0 - KNEE);
    KNEE + (1.0 - KNEE) * x / (1.0 + x)
}

/// How bright the dimmed part of the overlay is, out of 256.
const DIM: u32 = 110;

/// Fills `bright` with an 8-bit sRGB copy of `pixels` (half floats,
/// scRGB) as GDI takes it (0x00RRGGBB), and `dim` with the same darkened.
/// `white` is the scRGB value of SDR white, which shows as white; brighter
/// pixels are rolled off by their brightest channel, which keeps their hue.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn fill_preview(pixels: &[[u16; 4]], white: f32, bright: &mut [u32], dim: &mut [u32]) {
    // sRGB encoding by table, a hundredfold faster than `powf` per pixel.
    const STEPS: usize = 4096;
    let table: Vec<u8> = (0..STEPS)
        .map(|i| {
            let v = hdrshot_core::color::srgb_encode(i as f32 / (STEPS - 1) as f32);
            (v * 255.0).round() as u8
        })
        .collect();
    let scale = 1.0 / white.max(0.01);
    // Every half float relative to white, by table too; NaN is 0.
    let linear: Vec<f32> = (0..=u16::MAX)
        .map(|h| half::f16::from_bits(h).to_f32().max(0.0) * scale)
        .collect();
    let encode =
        |c: f32| u32::from(table[((c * (STEPS - 1) as f32 + 0.5) as usize).min(STEPS - 1)]);
    let darken = |c: u32| (c * DIM) >> 8;
    const CHUNK: usize = 16 * 1024;
    pixels
        .par_chunks(CHUNK)
        .zip(bright.par_chunks_mut(CHUNK))
        .zip(dim.par_chunks_mut(CHUNK))
        .for_each(|((pixels, bright), dim)| {
            for ((p, b), d) in pixels.iter().zip(bright).zip(dim) {
                let rgb = [p[0], p[1], p[2]].map(|h| linear[usize::from(h)]);
                let peak = rgb[0].max(rgb[1]).max(rgb[2]);
                let factor = if peak > KNEE && peak.is_finite() {
                    roll_off(peak) / peak
                } else if peak.is_finite() {
                    1.0
                } else {
                    0.0
                };
                let [r, g, bl] = rgb.map(|c| encode((c * factor).clamp(0.0, 1.0)));
                *b = (r << 16) | (g << 8) | bl;
                *d = (darken(r) << 16) | (darken(g) << 8) | darken(bl);
            }
        });
}

/// Takes a region screenshot after `delay`, on a thread of its own, and
/// sends the outcome; nothing when the user cancels.
#[cfg_attr(not(windows), allow(unused_variables))]
pub(crate) fn take_later(
    delay: Duration,
    options: Options,
    taken: std::sync::mpsc::Sender<Taken>,
    ctx: egui::Context,
) {
    std::thread::spawn(move || {
        std::thread::sleep(delay);
        #[cfg(windows)]
        let outcome = imp::take(&options);
        #[cfg(not(windows))]
        let outcome = Some(Err("Screenshots need Windows".to_owned()));
        if let Some(outcome) = outcome
            && taken.send(outcome).is_ok()
        {
            ctx.request_repaint();
        }
    });
}

/// The overlay and the region flow.
#[cfg(windows)]
pub(crate) mod imp {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    use windows::Win32::Devices::Display::{
        DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
        DISPLAYCONFIG_DEVICE_INFO_HEADER, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO,
        DISPLAYCONFIG_SDR_WHITE_LEVEL, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
        DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS,
        QueryDisplayConfig,
    };
    use windows::Win32::Foundation::{
        COLORREF, HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, SIZE, WPARAM,
    };
    use windows::Win32::Graphics::Dwm::{DWMWA_TRANSITIONS_FORCEDISABLED, DwmSetWindowAttribute};
    use windows::Win32::Graphics::Gdi::{
        BI_RGB, BITMAPINFO, BITMAPINFOHEADER, BeginPaint, BitBlt, CLEARTYPE_QUALITY,
        CLIP_DEFAULT_PRECIS, CreateCompatibleDC, CreateDIBSection, CreateFontW, CreateSolidBrush,
        DEFAULT_CHARSET, DIB_RGB_COLORS, DeleteDC, DeleteObject, EndPaint, FW_SEMIBOLD, FillRect,
        FrameRect, GetMonitorInfoW, GetTextExtentPoint32W, HBITMAP, HBRUSH, HDC, HGDIOBJ, HMONITOR,
        InvalidateRect, MONITOR_DEFAULTTOPRIMARY, MONITORINFO, MONITORINFOEXW, MonitorFromPoint,
        OUT_DEFAULT_PRECIS, PAINTSTRUCT, SRCCOPY, SelectObject, SetBkMode, SetTextColor,
        TRANSPARENT, TextOutW, UpdateWindow,
    };
    use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
    use windows::Win32::System::LibraryLoader::GetModuleHandleW;
    use windows::Win32::System::Threading::{AttachThreadInput, GetCurrentThreadId};
    use windows::Win32::UI::HiDpi::{
        DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, GetDpiForWindow, SetThreadDpiAwarenessContext,
    };
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        ReleaseCapture, SetCapture, SetFocus, VK_ESCAPE,
    };
    use windows::Win32::UI::WindowsAndMessaging::{
        BringWindowToTop, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW,
        EnumWindows, GWL_EXSTYLE, GetCursorPos, GetForegroundWindow, GetMessageW, GetWindowLongW,
        GetWindowThreadProcessId, IDC_CROSS, IsWindow, KillTimer, LoadCursorW, MSG,
        PostQuitMessage, RegisterClassExW, SW_SHOW, SetForegroundWindow, SetTimer, ShowWindow,
        WA_INACTIVE, WM_ACTIVATE, WM_CLOSE, WM_DISPLAYCHANGE, WM_DPICHANGED, WM_ERASEBKGND,
        WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
        WM_RBUTTONUP, WM_SYSKEYDOWN, WM_TIMER, WNDCLASSEXW, WS_EX_LAYERED, WS_EX_TOOLWINDOW,
        WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP,
    };
    use windows::core::{BOOL, PCWSTR, w};

    use super::{Pick, Showing, drag_rect, fill_preview, label_place, pick, size_label, window_at};
    use crate::screenshot::imp::{app_window, capture, game_of, save, window_rect};
    use crate::screenshot::{
        Area, Frame, Options, Rect, Shot, Taken, check_folder, shot_folder, window_area,
    };

    /// The overlay closes by itself after this long without a choice, so
    /// it can never be stuck over the screen.
    const TIMEOUT_MS: u32 = 60_000;
    const TIMER_ID: usize = 1;

    /// SDR white in scRGB when Windows doesn't say: 200 nits, near what
    /// Windows uses by default for SDR content on an HDR screen.
    const DEFAULT_SDR_WHITE: f32 = 2.5;

    /// What the hint at the top of the overlay says before dragging.
    const HINT: &str = "Drag a box to save it in HDR. Click to take a window. Escape cancels.";

    /// Freezes the screen with the pointer, lets the user pick a part of it
    /// and saves that part as the options say. `None` when cancelled.
    pub fn take(options: &Options) -> Option<Taken> {
        if let Err(e) = check_folder(options) {
            return Some(Err(e));
        }
        // Once at a time; other screenshots wait meanwhile.
        let showing = Showing::begin()?;
        // SAFETY: initializes COM for this thread, as saving needs; the
        // pointer call only reads.
        let monitor = unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
            let mut point = POINT::default();
            let _ = GetCursorPos(&mut point);
            MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY)
        };
        let frame = match capture(monitor) {
            Ok(frame) => frame,
            Err(e) => return Some(Err(e)),
        };
        let white = if frame.hdr {
            sdr_white(monitor).unwrap_or(DEFAULT_SDR_WHITE)
        } else {
            // Windows composes an SDR screen with white at 1.
            1.0
        };
        // The windows as they show now, before the overlay covers them: a
        // game in exclusive full screen can minimize once it shows, and
        // then no longer counts as one to take.
        // SAFETY: only reads.
        let front = unsafe { GetForegroundWindow() };
        let front_game = app_window(front).map(|window| (window, game_of(Some(window))));
        let windows = shown_windows();
        let picked = match show(&frame, monitor, white, front) {
            Ok(picked) => picked,
            Err(e) => return Some(Err(e)),
        };
        drop(showing);
        let (left, top) = (frame.left, frame.top);
        let (part, window, area) = match picked {
            Pick::Cancel => return None,
            Pick::Area(rect) => {
                let rect = Rect {
                    left: rect.left + left,
                    top: rect.top + top,
                    right: rect.right + left,
                    bottom: rect.bottom + top,
                };
                let center = (rect.left + rect.width() / 2, rect.top + rect.height() / 2);
                let window = window_at(&windows, center).map(|(window, _)| window);
                (Some(rect), window, Area::Region)
            }
            Pick::Point(x, y) => {
                let found = window_at(&windows, (x + left, y + top));
                let window = found.map(|(window, _)| window);
                let part = found.and_then(|(_, rect)| window_area(rect, frame.bounds()));
                let area = if part.is_some() {
                    Area::Window
                } else {
                    Area::Screen
                };
                (part, window, area)
            }
        };
        let cut = part.and_then(|rect| frame.crop(rect));
        let (frame, area) = match &cut {
            Some(cut) => (cut, area),
            None => (&frame, Area::Screen),
        };
        let game = match front_game {
            Some((front, game)) if window == Some(front) => game,
            _ => game_of(window),
        };
        Some(
            save(frame, &shot_folder(options, &game), &game).map(|path| Shot {
                path,
                game,
                hdr: frame.hdr,
                area,
            }),
        )
    }

    /// The app windows that show on the desktop and where, from the front
    /// back, leaving out those the pointer clicks through, such as a
    /// game's overlay.
    fn shown_windows() -> Vec<(HWND, Rect)> {
        unsafe extern "system" fn add(window: HWND, list: LPARAM) -> BOOL {
            // SAFETY: `list` is the vector below, borrowed for the call.
            let list = unsafe { &mut *(list.0 as *mut Vec<HWND>) };
            list.push(window);
            BOOL::from(true)
        }
        let mut all: Vec<HWND> = Vec::new();
        // SAFETY: the callback only pushes to `all`, which outlives the
        // call; EnumWindows lists top-level windows from the front back.
        unsafe {
            let _ = EnumWindows(Some(add), LPARAM((&raw mut all) as isize));
        }
        all.into_iter()
            .filter(|&window| app_window(window) == Some(window))
            .filter(|&window| {
                // SAFETY: only reads.
                let style = unsafe { GetWindowLongW(window, GWL_EXSTYLE) } as u32;
                let through = WS_EX_LAYERED.0 | WS_EX_TRANSPARENT.0;
                style & through != through
            })
            .filter_map(|window| Some((window, window_rect(window)?)))
            .collect()
    }

    /// Where `monitor` is on the desktop now, if it still is.
    fn monitor_rect(monitor: HMONITOR) -> Option<Rect> {
        let mut info = MONITORINFO {
            cbSize: size_of::<MONITORINFO>() as u32,
            ..Default::default()
        };
        // SAFETY: the struct's size is passed with it.
        if !unsafe { GetMonitorInfoW(monitor, &mut info) }.as_bool() {
            return None;
        }
        let r = info.rcMonitor;
        Some(Rect {
            left: r.left,
            top: r.top,
            right: r.right,
            bottom: r.bottom,
        })
    }

    /// SDR white on `monitor` in scRGB, as set with the SDR content
    /// brightness slider in Windows' HDR settings.
    fn sdr_white(monitor: HMONITOR) -> Option<f32> {
        // SAFETY: the structs' sizes are passed with them, and the arrays'
        // lengths with the arrays.
        unsafe {
            let mut info = MONITORINFOEXW::default();
            info.monitorInfo.cbSize = size_of::<MONITORINFOEXW>() as u32;
            if !GetMonitorInfoW(monitor, (&raw mut info).cast::<MONITORINFO>()).as_bool() {
                return None;
            }
            let (mut path_count, mut mode_count) = (0u32, 0u32);
            GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count)
                .ok()
                .ok()?;
            let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize];
            let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize];
            QueryDisplayConfig(
                QDC_ONLY_ACTIVE_PATHS,
                &mut path_count,
                paths.as_mut_ptr(),
                &mut mode_count,
                modes.as_mut_ptr(),
                None,
            )
            .ok()
            .ok()?;
            paths.truncate(path_count as usize);
            let name_end = |name: &[u16]| name.iter().position(|&c| c == 0).unwrap_or(name.len());
            let device = &info.szDevice[..name_end(&info.szDevice)];
            for path in &paths {
                let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME {
                    header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
                        r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
                        size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
                        adapterId: path.sourceInfo.adapterId,
                        id: path.sourceInfo.id,
                    },
                    ..Default::default()
                };
                if DisplayConfigGetDeviceInfo(&mut source.header) != 0 {
                    continue;
                }
                let name = &source.viewGdiDeviceName;
                if &name[..name_end(name)] != device {
                    continue;
                }
                let mut white = DISPLAYCONFIG_SDR_WHITE_LEVEL {
                    header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
                        r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL,
                        size: size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as u32,
                        adapterId: path.targetInfo.adapterId,
                        id: path.targetInfo.id,
                    },
                    SDRWhiteLevel: 0,
                };
                if DisplayConfigGetDeviceInfo(&mut white.header) == 0 && white.SDRWhiteLevel > 0 {
                    // In thousandths of 80 nits, which is 1 in scRGB.
                    return Some(white.SDRWhiteLevel as f32 / 1000.0);
                }
            }
            None
        }
    }

    /// A memory DC with a 32-bit top-down bitmap selected into it.
    struct Canvas {
        dc: HDC,
        bitmap: HBITMAP,
        old: HGDIOBJ,
        /// The DC's own font, once another is selected into it.
        old_font: Option<HGDIOBJ>,
    }

    impl Canvas {
        /// A canvas `width` by `height` and its pixels, 0x00RRGGBB, which
        /// live as long as it does.
        fn new(width: i32, height: i32) -> Option<(Self, *mut u32)> {
            // SAFETY: the bitmap is selected into the DC made here, and
            // both are freed in `drop`.
            unsafe {
                let dc = CreateCompatibleDC(None);
                if dc.is_invalid() {
                    return None;
                }
                let info = BITMAPINFO {
                    bmiHeader: BITMAPINFOHEADER {
                        biSize: size_of::<BITMAPINFOHEADER>() as u32,
                        biWidth: width,
                        // Negative for rows from the top down, as in a frame.
                        biHeight: -height,
                        biPlanes: 1,
                        biBitCount: 32,
                        biCompression: BI_RGB.0,
                        ..Default::default()
                    },
                    ..Default::default()
                };
                let mut bits = std::ptr::null_mut();
                let bitmap =
                    match CreateDIBSection(Some(dc), &info, DIB_RGB_COLORS, &mut bits, None, 0) {
                        Ok(bitmap) if !bits.is_null() => bitmap,
                        Ok(bitmap) => {
                            let _ = DeleteObject(bitmap.into());
                            let _ = DeleteDC(dc);
                            return None;
                        }
                        Err(_) => {
                            let _ = DeleteDC(dc);
                            return None;
                        }
                    };
                let old = SelectObject(dc, bitmap.into());
                Some((
                    Self {
                        dc,
                        bitmap,
                        old,
                        old_font: None,
                    },
                    bits.cast(),
                ))
            }
        }

        /// Draws text in `font` from now on, which must outlive the canvas.
        fn select_font(&mut self, font: HGDIOBJ) {
            // SAFETY: the DC is this canvas's; its own font is put back in
            // `drop`, so the DC never goes with `font` selected.
            let old = unsafe { SelectObject(self.dc, font) };
            self.old_font.get_or_insert(old);
        }
    }

    impl Drop for Canvas {
        fn drop(&mut self) {
            // SAFETY: frees what `new` made, the bitmap once it's no longer
            // selected.
            unsafe {
                if let Some(font) = self.old_font {
                    SelectObject(self.dc, font);
                }
                SelectObject(self.dc, self.old);
                let _ = DeleteDC(self.dc);
                let _ = DeleteObject(self.bitmap.into());
            }
        }
    }

    /// A GDI pen, brush or font, deleted with this.
    struct Object(HGDIOBJ);

    impl Drop for Object {
        fn drop(&mut self) {
            // SAFETY: made by this module and no longer selected anywhere:
            // the canvases are dropped first.
            unsafe {
                let _ = DeleteObject(self.0);
            }
        }
    }

    /// The overlay's state. Only used on its thread; the cells let the
    /// window procedure run again while it runs, as Windows calls it from
    /// within some of the calls it makes.
    struct Overlay {
        width: i32,
        height: i32,
        /// The frozen screen as is and dimmed.
        bright: Canvas,
        dim: Canvas,
        /// Where a frame is drawn before it goes to the screen in one go,
        /// so nothing flickers.
        back: Canvas,
        // After the canvases, so dropped once no DC holds them.
        _font: Object,
        border: Object,
        label: Object,
        /// Pixels between the box and its label, and around the label's
        /// text, for the screen's scale.
        gap: i32,
        pad: i32,
        /// The least width and height of a box, for the screen's scale.
        min_drag: i32,
        /// The screen shown and where it was on the desktop when captured.
        monitor: HMONITOR,
        bounds: Rect,
        /// Where the drag started, while dragging.
        anchor: Cell<Option<(i32, i32)>>,
        pointer: Cell<(i32, i32)>,
        picked: Cell<Option<Pick>>,
        /// Whether the overlay has had the focus, so losing it cancels.
        active: Cell<bool>,
        /// Whether the focus is watched: not while bringing the overlay to
        /// the front, which can take it away and back.
        watch_focus: Cell<bool>,
    }

    thread_local! {
        static OVERLAY: RefCell<Option<Rc<Overlay>>> = const { RefCell::new(None) };
    }

    fn current() -> Option<Rc<Overlay>> {
        OVERLAY.with(|o| o.borrow().clone())
    }

    fn wide(text: &str) -> Vec<u16> {
        text.encode_utf16().collect()
    }

    fn rect(r: Rect) -> RECT {
        RECT {
            left: r.left,
            top: r.top,
            right: r.right,
            bottom: r.bottom,
        }
    }

    impl Overlay {
        fn finish(&self, picked: Pick) {
            if self.picked.get().is_none() {
                self.picked.set(Some(picked));
            }
        }

        /// The box being dragged, if any.
        fn selection(&self) -> Option<Rect> {
            let anchor = self.anchor.get()?;
            Some(drag_rect(
                anchor,
                self.pointer.get(),
                self.width,
                self.height,
            ))
        }

        /// The size of `text` in the label font, with its padding.
        fn text_size(&self, text: &[u16]) -> (i32, i32) {
            let mut size = SIZE::default();
            // SAFETY: the font is selected into the back canvas.
            unsafe {
                let _ = GetTextExtentPoint32W(self.back.dc, text, &mut size);
            }
            (size.cx + 2 * self.pad, size.cy + 2 * self.pad)
        }

        /// The size label for `selection` and where it goes.
        fn size_label(&self, selection: Rect) -> (Vec<u16>, Rect) {
            let text = wide(&size_label(selection));
            let (w, h) = self.text_size(&text);
            let (x, y) = label_place(selection, (w, h), self.width, self.height, self.gap);
            let place = Rect {
                left: x,
                top: y,
                right: x + w,
                bottom: y + h,
            };
            (text, place)
        }

        /// The hint at the top and where it goes.
        fn hint(&self) -> (Vec<u16>, Rect) {
            let text = wide(HINT);
            let (w, h) = self.text_size(&text);
            let x = ((self.width - w) / 2).max(0);
            let y = self.gap * 4;
            let place = Rect {
                left: x,
                top: y,
                right: x + w,
                bottom: y + h,
            };
            (text, place)
        }

        /// The parts of the screen the box and its label (or the hint)
        /// cover now, to be drawn again when they change.
        fn drawn(&self) -> [Rect; 2] {
            match self.selection() {
                Some(selection) => [
                    Rect {
                        left: selection.left - 1,
                        top: selection.top - 1,
                        right: selection.right + 1,
                        bottom: selection.bottom + 1,
                    },
                    self.size_label(selection).1,
                ],
                None => {
                    let hint = self.hint().1;
                    [hint, hint]
                }
            }
        }

        fn invalidate(&self, hwnd: HWND, parts: [Rect; 2]) {
            for part in parts {
                // SAFETY: the window is this overlay's.
                unsafe {
                    let _ = InvalidateRect(Some(hwnd), Some(&rect(part)), false);
                }
            }
        }

        /// Draws a label: white text on a dark box.
        fn draw_label(&self, text: &[u16], place: Rect) {
            // SAFETY: draws on the back canvas with objects made here.
            unsafe {
                FillRect(self.back.dc, &rect(place), HBRUSH(self.label.0.0));
                let _ = TextOutW(
                    self.back.dc,
                    place.left + self.pad,
                    place.top + self.pad,
                    text,
                );
            }
        }

        fn paint(&self, hwnd: HWND) {
            // SAFETY: draws within BeginPaint and EndPaint, from canvases
            // the size of the window.
            unsafe {
                let mut ps = PAINTSTRUCT::default();
                let hdc = BeginPaint(hwnd, &mut ps);
                let clip = ps.rcPaint;
                let (cw, ch) = (clip.right - clip.left, clip.bottom - clip.top);
                let back = self.back.dc;
                let _ = BitBlt(
                    back,
                    clip.left,
                    clip.top,
                    cw,
                    ch,
                    Some(self.dim.dc),
                    clip.left,
                    clip.top,
                    SRCCOPY,
                );
                match self.selection() {
                    Some(selection) => {
                        let _ = BitBlt(
                            back,
                            selection.left,
                            selection.top,
                            selection.width(),
                            selection.height(),
                            Some(self.bright.dc),
                            selection.left,
                            selection.top,
                            SRCCOPY,
                        );
                        let frame = RECT {
                            left: selection.left - 1,
                            top: selection.top - 1,
                            right: selection.right + 1,
                            bottom: selection.bottom + 1,
                        };
                        FrameRect(back, &frame, HBRUSH(self.border.0.0));
                        let (text, place) = self.size_label(selection);
                        self.draw_label(&text, place);
                    }
                    None => {
                        let (text, place) = self.hint();
                        self.draw_label(&text, place);
                    }
                }
                if !hdc.is_invalid() {
                    let _ = BitBlt(
                        hdc,
                        clip.left,
                        clip.top,
                        cw,
                        ch,
                        Some(back),
                        clip.left,
                        clip.top,
                        SRCCOPY,
                    );
                }
                let _ = EndPaint(hwnd, &ps);
            }
        }
    }

    /// The pointer's place in a mouse message, which can be off the window
    /// while the mouse is captured.
    fn mouse_point(lparam: LPARAM) -> (i32, i32) {
        let x = i32::from((lparam.0 & 0xffff) as u16 as i16);
        let y = i32::from(((lparam.0 >> 16) & 0xffff) as u16 as i16);
        (x, y)
    }

    unsafe extern "system" fn window_proc(
        hwnd: HWND,
        msg: u32,
        wparam: WPARAM,
        lparam: LPARAM,
    ) -> LRESULT {
        let Some(o) = current() else {
            // SAFETY: the default handling, as for any message.
            return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
        };
        // SAFETY: Win32 calls on this overlay's own window.
        unsafe {
            match msg {
                WM_PAINT => o.paint(hwnd),
                // Painting covers all of it.
                WM_ERASEBKGND => return LRESULT(1),
                WM_LBUTTONDOWN => {
                    let before = o.drawn();
                    let point = mouse_point(lparam);
                    o.anchor.set(Some(point));
                    o.pointer.set(point);
                    SetCapture(hwnd);
                    o.invalidate(hwnd, before);
                    o.invalidate(hwnd, o.drawn());
                }
                WM_MOUSEMOVE => {
                    let point = mouse_point(lparam);
                    if o.anchor.get().is_some() && point != o.pointer.get() {
                        let before = o.drawn();
                        o.pointer.set(point);
                        o.invalidate(hwnd, before);
                        o.invalidate(hwnd, o.drawn());
                    } else {
                        o.pointer.set(point);
                    }
                }
                WM_LBUTTONUP => {
                    if let Some(anchor) = o.anchor.get() {
                        let to = mouse_point(lparam);
                        o.finish(pick(anchor, to, o.width, o.height, o.min_drag));
                    }
                    let _ = ReleaseCapture();
                }
                // On release, so that the release doesn't reach the window
                // below, e.g. opening a menu in it.
                WM_RBUTTONDOWN => {}
                WM_RBUTTONUP => o.finish(Pick::Cancel),
                // With Alt held too, as when switching windows is started.
                WM_KEYDOWN | WM_SYSKEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => {
                    o.finish(Pick::Cancel);
                }
                WM_ACTIVATE => {
                    if o.watch_focus.get() {
                        if (wparam.0 & 0xffff) as u32 == WA_INACTIVE {
                            if o.active.get() {
                                o.finish(Pick::Cancel);
                            }
                        } else {
                            o.active.set(true);
                        }
                    }
                    // Which gives the overlay the keyboard focus.
                    return DefWindowProcW(hwnd, msg, wparam, lparam);
                }
                // Only when the picture no longer matches the screen: a game
                // leaving full screen as the overlay shows sends this too.
                WM_DISPLAYCHANGE => {
                    if monitor_rect(o.monitor) != Some(o.bounds) {
                        o.finish(Pick::Cancel);
                    }
                }
                WM_TIMER | WM_CLOSE => o.finish(Pick::Cancel),
                // Stays where it is, covering its screen pixel for pixel.
                WM_DPICHANGED => {}
                _ => return DefWindowProcW(hwnd, msg, wparam, lparam),
            }
        }
        LRESULT(0)
    }

    /// Shows `frame`, captured from `monitor`, over it and waits for the
    /// user's choice. `front`, the window in front before, is put back in
    /// front after, unless the user switched to another one.
    fn show(frame: &Frame, monitor: HMONITOR, white: f32, front: HWND) -> Result<Pick, String> {
        let failed = || "Couldn't show the screen to choose a region on".to_owned();
        let (width, height) = (frame.width as i32, frame.height as i32);
        let count = frame.width * frame.height;
        let (bright, bright_bits) = Canvas::new(width, height).ok_or_else(failed)?;
        let (dim, dim_bits) = Canvas::new(width, height).ok_or_else(failed)?;
        let (back, _) = Canvas::new(width, height).ok_or_else(failed)?;
        // SAFETY: each canvas holds `count` pixels, alive as long as it
        // is, and GDI doesn't touch them until after this.
        unsafe {
            let bright = std::slice::from_raw_parts_mut(bright_bits, count);
            let dim = std::slice::from_raw_parts_mut(dim_bits, count);
            fill_preview(&frame.pixels, white, bright, dim);
        }
        // SAFETY: plain Win32 calls; the window and everything made for it
        // are destroyed before returning.
        unsafe {
            // In case the process isn't aware of each screen's scale, so
            // that the window covers the screen pixel for pixel.
            let dpi_before =
                SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
            let picked = run(frame, monitor, front, (bright, dim, back));
            if !dpi_before.is_invalid() {
                SetThreadDpiAwarenessContext(dpi_before);
            }
            picked.ok_or_else(failed)
        }
    }

    /// Makes the overlay window and runs it until the user chooses.
    unsafe fn run(
        frame: &Frame,
        monitor: HMONITOR,
        front: HWND,
        (bright, dim, mut back): (Canvas, Canvas, Canvas),
    ) -> Option<Pick> {
        let (width, height) = (frame.width as i32, frame.height as i32);
        // SAFETY: see `show`.
        unsafe {
            let instance = HINSTANCE(GetModuleHandleW(PCWSTR::null()).ok()?.0);
            let class = w!("hdrshot region");
            let class_info = WNDCLASSEXW {
                cbSize: size_of::<WNDCLASSEXW>() as u32,
                lpfnWndProc: Some(window_proc),
                hInstance: instance,
                hCursor: LoadCursorW(None, IDC_CROSS).unwrap_or_default(),
                lpszClassName: class,
                ..Default::default()
            };
            // Fails harmlessly when the class exists from an earlier time.
            RegisterClassExW(&class_info);
            let hwnd = CreateWindowExW(
                WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
                class,
                w!("hdrshot region"),
                WS_POPUP,
                frame.left,
                frame.top,
                width,
                height,
                None,
                None,
                Some(instance),
                None,
            )
            .ok()?;
            // Shown and gone at once, without fading, as a frozen screen.
            let off = BOOL::from(true);
            let _ = DwmSetWindowAttribute(
                hwnd,
                DWMWA_TRANSITIONS_FORCEDISABLED,
                (&raw const off).cast(),
                size_of::<BOOL>() as u32,
            );
            let dpi = match GetDpiForWindow(hwnd) {
                0 => 96,
                dpi => dpi as i32,
            };
            let scaled = |v: i32| v * dpi / 96;
            // 9 points.
            let font = CreateFontW(
                -scaled(12),
                0,
                0,
                0,
                FW_SEMIBOLD.0 as i32,
                0,
                0,
                0,
                DEFAULT_CHARSET,
                OUT_DEFAULT_PRECIS,
                CLIP_DEFAULT_PRECIS,
                CLEARTYPE_QUALITY,
                0,
                w!("Segoe UI"),
            );
            back.select_font(font.into());
            SetBkMode(back.dc, TRANSPARENT);
            SetTextColor(back.dc, COLORREF(0x00ff_ffff));
            let overlay = Rc::new(Overlay {
                width,
                height,
                bright,
                dim,
                back,
                _font: Object(font.into()),
                border: Object(CreateSolidBrush(COLORREF(0x00ff_ffff)).into()),
                label: Object(CreateSolidBrush(COLORREF(0x0020_2020)).into()),
                gap: scaled(6),
                pad: scaled(4),
                min_drag: scaled(super::MIN_DRAG),
                monitor,
                bounds: frame.bounds(),
                anchor: Cell::new(None),
                pointer: Cell::new((0, 0)),
                picked: Cell::new(None),
                active: Cell::new(false),
                watch_focus: Cell::new(false),
            });
            OVERLAY.with(|o| *o.borrow_mut() = Some(overlay.clone()));
            SetTimer(Some(hwnd), TIMER_ID, TIMEOUT_MS, None);
            let _ = ShowWindow(hwnd, SW_SHOW);
            // Painted at once, not a blank window first.
            let _ = UpdateWindow(hwnd);
            bring_to_front(hwnd);
            overlay.active.set(GetForegroundWindow() == hwnd);
            overlay.watch_focus.set(true);
            // Until the user chooses. Other messages for the thread, such
            // as the shortcut pressed again, are dropped.
            let mut quit = None;
            let mut msg = MSG::default();
            while overlay.picked.get().is_none() {
                match GetMessageW(&mut msg, None, 0, 0).0 {
                    0 => {
                        quit = Some(msg.wParam.0 as i32);
                        break;
                    }
                    -1 => break,
                    _ => {
                        DispatchMessageW(&msg);
                    }
                }
            }
            let _ = KillTimer(Some(hwnd), TIMER_ID);
            let _ = ReleaseCapture();
            // Not when the user switched to another window, which cancels.
            let had_focus = GetForegroundWindow() == hwnd;
            let _ = DestroyWindow(hwnd);
            if had_focus && !front.is_invalid() && IsWindow(Some(front)).as_bool() {
                let _ = SetForegroundWindow(front);
            }
            OVERLAY.with(|o| *o.borrow_mut() = None);
            // The thread is asked to end: the loop it runs ends too.
            if let Some(code) = quit {
                PostQuitMessage(code);
            }
            Some(overlay.picked.get().unwrap_or(Pick::Cancel))
        }
    }

    /// Makes the overlay the window in front with the keyboard focus, for
    /// Escape. Windows allows it after a hotkey or a choice in the tray
    /// menu, input the app got; if it refuses anyway, joining the input of
    /// the window in front usually works.
    unsafe fn bring_to_front(hwnd: HWND) {
        // SAFETY: plain Win32 calls; the input is detached again.
        unsafe {
            if SetForegroundWindow(hwnd).as_bool() && GetForegroundWindow() == hwnd {
                return;
            }
            let front = GetForegroundWindow();
            let front_thread = GetWindowThreadProcessId(front, None);
            let own = GetCurrentThreadId();
            let attached = front_thread != 0
                && front_thread != own
                && AttachThreadInput(own, front_thread, true).as_bool();
            let _ = BringWindowToTop(hwnd);
            let _ = SetForegroundWindow(hwnd);
            let _ = SetFocus(Some(hwnd));
            if attached {
                let _ = AttachThreadInput(own, front_thread, false);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
        Rect {
            left,
            top,
            right,
            bottom,
        }
    }

    #[test]
    fn boxes_from_drags() {
        // Either way round, both ends included.
        assert_eq!(
            drag_rect((10, 20), (30, 25), 100, 100),
            rect(10, 20, 31, 26)
        );
        assert_eq!(
            drag_rect((30, 25), (10, 20), 100, 100),
            rect(10, 20, 31, 26)
        );
        assert_eq!(
            drag_rect((30, 20), (10, 25), 100, 100),
            rect(10, 20, 31, 26)
        );
        // Off the screen, as while the mouse is captured: cut to it.
        assert_eq!(
            drag_rect((50, 50), (-20, 300), 100, 80),
            rect(0, 50, 51, 80)
        );
        assert_eq!(
            drag_rect((-5, -5), (500, 500), 100, 80),
            rect(0, 0, 100, 80)
        );
    }

    #[test]
    fn clicks_and_drags() {
        let min = MIN_DRAG;
        assert_eq!(pick((10, 10), (12, 13), 100, 100, min), Pick::Point(10, 10));
        // Both sides 8 pixels: a box.
        assert_eq!(
            pick((10, 10), (17, 17), 100, 100, min),
            Pick::Area(rect(10, 10, 18, 18))
        );
        assert_eq!(
            pick((40, 40), (10, 50), 100, 100, min),
            Pick::Area(rect(10, 40, 41, 51))
        );
        // Long but thin either way, or one pixel short: a click.
        assert_eq!(pick((10, 10), (90, 11), 100, 100, min), Pick::Point(10, 10));
        assert_eq!(pick((40, 10), (38, 90), 100, 100, min), Pick::Point(40, 10));
        assert_eq!(pick((10, 10), (16, 30), 100, 100, min), Pick::Point(10, 10));
        // Scaled for a screen at 200%.
        assert_eq!(pick((10, 10), (20, 20), 100, 100, 16), Pick::Point(10, 10));
        assert_eq!(
            pick((10, 10), (25, 25), 100, 100, 16),
            Pick::Area(rect(10, 10, 26, 26))
        );
    }

    #[test]
    fn windows_from_the_front() {
        let windows = [
            ("dialog", rect(100, 100, 200, 200)),
            ("game", rect(0, 0, 1920, 1080)),
            ("other", rect(-1920, 0, 0, 1080)),
        ];
        let name = |point| window_at(&windows, point).map(|(name, _)| name);
        assert_eq!(name((150, 150)), Some("dialog"));
        assert_eq!(
            window_at(&windows, (150, 150)),
            Some(("dialog", rect(100, 100, 200, 200)))
        );
        // Right and bottom edges are outside.
        assert_eq!(name((200, 150)), Some("game"));
        assert_eq!(name((0, 0)), Some("game"));
        assert_eq!(name((-1, 500)), Some("other"));
        assert_eq!(name((1920, 500)), None);
        assert_eq!(window_at::<&str>(&[], (0, 0)), None);
    }

    #[test]
    fn labels() {
        assert_eq!(size_label(rect(-10, 0, 1910, 1080)), "1920 x 1080");
        let (w, h) = (1920, 1080);
        let label = (100, 20);
        // Below the box.
        assert_eq!(
            label_place(rect(100, 100, 500, 400), label, w, h, 6),
            (100, 406)
        );
        // At the bottom: above it.
        assert_eq!(
            label_place(rect(100, 500, 500, 1070), label, w, h, 6),
            (100, 474)
        );
        // Kept on the screen at the right.
        assert_eq!(
            label_place(rect(1850, 100, 1900, 200), label, w, h, 6),
            (1820, 206)
        );
        // The whole screen: inside, at the top left.
        assert_eq!(label_place(rect(0, 0, w, h), label, w, h, 6), (6, 6));
    }

    /// Half floats for a few exact values.
    fn half(v: f32) -> u16 {
        half::f16::from_f32(v).to_bits()
    }

    fn preview(pixels: &[[f32; 3]], white: f32) -> (Vec<u32>, Vec<u32>) {
        let pixels: Vec<_> = pixels
            .iter()
            .map(|p| [half(p[0]), half(p[1]), half(p[2]), half(1.0)])
            .collect();
        let mut bright = vec![0; pixels.len()];
        let mut dim = vec![0; pixels.len()];
        fill_preview(&pixels, white, &mut bright, &mut dim);
        (bright, dim)
    }

    #[test]
    fn previews_in_sdr() {
        let (bright, dim) = preview(
            &[
                [0.0, 0.0, 0.0],
                // SDR white on an HDR screen.
                [2.5, 2.5, 2.5],
                // A highlight four times as bright, red.
                [10.0, 0.0, 0.0],
                [-1.0, f32::NAN, f32::INFINITY],
                // 18% gray.
                [0.45, 0.45, 0.45],
            ],
            2.5,
        );
        assert_eq!(bright[0], 0);
        // White is nearly white, a highlight brighter still and as red.
        let white = bright[1] & 0xff;
        assert!((240..255).contains(&white), "{white}");
        assert_eq!(bright[1], white * 0x010101);
        assert!(
            bright[2] >> 16 > white && bright[2] & 0xffff == 0,
            "{:x}",
            bright[2]
        );
        assert_eq!(bright[3], 0);
        // Midtones as they are: 18% is 118 in sRGB.
        assert_eq!(bright[4] & 0xff, 118);
        assert_eq!(dim[4] & 0xff, (118 * DIM) >> 8);
        assert_eq!(dim[1] >> 16, (white * DIM) >> 8);
    }

    #[test]
    fn rolls_off_highlights() {
        assert_eq!(roll_off(0.5), 0.5);
        assert_eq!(roll_off(KNEE), KNEE);
        assert_eq!(roll_off(-1.0), 0.0);
        let mut last = KNEE;
        for v in [1.0, 2.0, 4.0, 16.0, 1000.0] {
            let out = roll_off(v);
            assert!(out > last && out < 1.0, "{v} -> {out}");
            last = out;
        }
        // Smooth at the knee.
        assert!((roll_off(KNEE + 1e-3) - (KNEE + 1e-3)).abs() < 1e-5);
    }
}