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
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
//! HDR screenshots on Windows. A shortcut that works in games, or the
//! tray menu or the window's camera button, saves what a screen shows as
//! a JPEG XR file, like Game Bar does, which the app then converts with the
//! current settings. By default only the window in front is kept, and each
//! game's screenshots go in a folder named after it. A second shortcut
//! takes a part of the screen (see `region`).
//!
//! The picture comes from DXGI desktop duplication in 16-bit float
//! (scRGB), the format Windows composes an HDR desktop in, so nothing is
//! lost: it is the same data as in a Game Bar screenshot. The mouse pointer
//! isn't part of it.

use std::path::PathBuf;
#[cfg(windows)]
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde::{Deserialize, Serialize};

/// Whether this platform can take HDR screenshots.
pub(crate) const SUPPORTED: bool = cfg!(windows);

/// The keyboard shortcut that takes a screenshot, from any app.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Shortcut {
    Off,
    CtrlShiftPrintScreen,
    CtrlPrintScreen,
    ShiftPrintScreen,
    CtrlAltPrintScreen,
}

impl Shortcut {
    /// The choices, in the order the Settings page offers them, for both
    /// shortcuts. Ctrl+Alt+PrtScn, the region shortcut's default, stays a
    /// choice for the screenshot shortcut, which 2.4.0 offered it for; the
    /// region shortcut then says to choose another.
    pub(crate) const ALL: [Self; 5] = [
        Self::CtrlShiftPrintScreen,
        Self::CtrlPrintScreen,
        Self::ShiftPrintScreen,
        Self::CtrlAltPrintScreen,
        Self::Off,
    ];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Off => "Off",
            Self::CtrlShiftPrintScreen => "Ctrl+Shift+PrtScn",
            Self::CtrlPrintScreen => "Ctrl+PrtScn",
            Self::ShiftPrintScreen => "Shift+PrtScn",
            Self::CtrlAltPrintScreen => "Ctrl+Alt+PrtScn",
        }
    }
}

/// Which screen to capture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Target {
    /// The one showing the window in front, e.g. the game.
    Foreground,
    /// The one with the mouse pointer, as after choosing the tray menu.
    /// Always the whole screen: the window in front is then whatever was
    /// behind the menu, not one the user picked.
    Pointer,
}

/// How much of the screen a screenshot shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Area {
    /// Only the window in front, e.g. the game, like Game Bar. A game in
    /// full screen fills the screen anyway.
    #[default]
    Window,
    /// The whole screen the window in front is on.
    Screen,
    /// A part of the screen the user dragged a box around (see `region`).
    /// Not a setting: only region screenshots are this.
    Region,
}

impl Area {
    /// The choices, in the order the Settings page offers them.
    pub(crate) const ALL: [Self; 2] = [Self::Window, Self::Screen];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Window => "Game window",
            Self::Screen => "Whole screen",
            Self::Region => "Region",
        }
    }
}

/// Where and how screenshots are saved, from the settings. The shortcut's
/// thread shares them with the app.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Options {
    pub(crate) folder: PathBuf,
    pub(crate) area: Area,
    /// Save each game's screenshots in a subfolder named after it.
    pub(crate) game_folders: bool,
}

/// Refuses to take a screenshot without a folder for it, as the
/// shortcut's thread has before the app has passed it one, rather than
/// saving it wherever hdrshot was started.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn check_folder(options: &Options) -> Result<(), String> {
    if options.folder.as_os_str().is_empty() {
        Err("Choose a folder for screenshots in Settings".to_owned())
    } else {
        Ok(())
    }
}

/// A screenshot saved.
#[cfg_attr(not(windows), allow(dead_code))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Shot {
    pub(crate) path: PathBuf,
    /// The game's name, or "Desktop", as in the file name.
    pub(crate) game: String,
    /// Whether the screen showed HDR. When Windows has HDR off, the
    /// screenshot only holds SDR. `true` when Windows doesn't say.
    pub(crate) hdr: bool,
    /// How much of the screen it shows: [`Area::Screen`] whenever the
    /// whole screen was kept, as for a game in full screen or with no app
    /// window in front, whatever the setting.
    pub(crate) area: Area,
}

/// The screenshot saved, or why not.
pub(crate) type Taken = Result<Shot, String>;

/// Where screenshots go unless the user picked a folder: `hdrshot` in the
/// Pictures folder.
pub(crate) fn default_folder() -> Option<PathBuf> {
    #[cfg(windows)]
    return imp::pictures().map(|p| p.join("hdrshot"));
    #[cfg(not(windows))]
    None
}

/// The shortcut, registered with the system while this exists. Each press
/// saves a screenshot with the options it shares with the app and sends
/// the outcome.
pub(crate) struct Hotkey {
    #[cfg(windows)]
    thread: imp::HotkeyThread,
}

impl Hotkey {
    /// Registers `shortcut`; fails when another app has it already.
    #[cfg(windows)]
    pub(crate) fn register(
        shortcut: Shortcut,
        options: Arc<Mutex<Options>>,
        taken: std::sync::mpsc::Sender<Taken>,
        ctx: egui::Context,
    ) -> Result<Self, String> {
        imp::HotkeyThread::start(shortcut, options, taken, ctx).map(|thread| Self { thread })
    }

    /// Registers `shortcut` for region screenshots: each press freezes the
    /// screen for the user to drag a box on (see `region`).
    #[cfg(windows)]
    pub(crate) fn register_region(
        shortcut: Shortcut,
        options: Arc<Mutex<Options>>,
        taken: std::sync::mpsc::Sender<Taken>,
        ctx: egui::Context,
    ) -> Result<Self, String> {
        imp::HotkeyThread::start_with(shortcut, imp::REGION_HOTKEY_ID, move || {
            let options = options.lock().map(|o| o.clone()).unwrap_or_default();
            // Nothing to send when the user cancelled.
            if let Some(outcome) = crate::region::imp::take(&options)
                && taken.send(outcome).is_ok()
            {
                ctx.request_repaint();
            }
        })
        .map(|thread| Self { thread })
    }
}

#[cfg(windows)]
impl Drop for Hotkey {
    fn drop(&mut self) {
        self.thread.stop();
    }
}

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

/// A rectangle on the desktop in physical pixels, as Windows gives the
/// places of screens and windows. `right` and `bottom` are just outside.
#[cfg_attr(not(windows), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Rect {
    pub(crate) left: i32,
    pub(crate) top: i32,
    pub(crate) right: i32,
    pub(crate) bottom: i32,
}

#[cfg_attr(not(windows), allow(dead_code))]
impl Rect {
    pub(crate) fn width(self) -> i32 {
        (self.right - self.left).max(0)
    }

    pub(crate) fn height(self) -> i32 {
        (self.bottom - self.top).max(0)
    }

    /// The part inside both, if any.
    pub(crate) fn intersect(self, other: Self) -> Option<Self> {
        let part = Self {
            left: self.left.max(other.left),
            top: self.top.max(other.top),
            right: self.right.min(other.right),
            bottom: self.bottom.min(other.bottom),
        };
        (part.width() > 0 && part.height() > 0).then_some(part)
    }
}

/// A screen's picture, or part of one: half floats, red, green, blue and
/// alpha, turned the way the screen shows them.
#[cfg_attr(not(windows), allow(dead_code))]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Frame {
    pub(crate) width: usize,
    pub(crate) height: usize,
    pub(crate) pixels: Vec<[u16; 4]>,
    /// Where the top left pixel is on the desktop, so that windows and
    /// regions can be cut out by their desktop coordinates.
    pub(crate) left: i32,
    pub(crate) top: i32,
    /// Whether the screen showed HDR (see [`Shot::hdr`]).
    pub(crate) hdr: bool,
}

#[cfg_attr(not(windows), allow(dead_code))]
impl Frame {
    /// Where the picture is on the desktop.
    pub(crate) fn bounds(&self) -> Rect {
        Rect {
            left: self.left,
            top: self.top,
            right: self.left + self.width as i32,
            bottom: self.top + self.height as i32,
        }
    }

    /// The part of the picture inside `rect`, in desktop coordinates, or
    /// `None` when nothing of it is.
    pub(crate) fn crop(&self, rect: Rect) -> Option<Self> {
        let part = rect.intersect(self.bounds())?;
        let x = (part.left - self.left) as usize;
        let y = (part.top - self.top) as usize;
        let (width, height) = (part.width() as usize, part.height() as usize);
        let pixels = (y..y + height)
            .flat_map(|row| {
                let start = row * self.width + x;
                self.pixels[start..start + width].iter().copied()
            })
            .collect();
        Some(Self {
            width,
            height,
            pixels,
            left: part.left,
            top: part.top,
            hdr: self.hdr,
        })
    }
}

/// Windows smaller than this either way, such as a tool tip that has the
/// focus, are taken with the whole screen instead.
const MIN_WINDOW: i32 = 64;

/// How far a window may fall short of the screen's edges and still count
/// as filling it, as games in full screen can by a few pixels.
const FULL_SCREEN_SLACK: i32 = 8;

/// The part of `screen` to keep for a screenshot of the window at
/// `window`, or `None` to keep the whole screen: when the window is tiny,
/// off the screen, or (nearly) fills it anyway.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn window_area(window: Rect, screen: Rect) -> Option<Rect> {
    let part = window.intersect(screen)?;
    let tiny = part.width() < MIN_WINDOW || part.height() < MIN_WINDOW;
    let fills = part.width() >= screen.width() - FULL_SCREEN_SLACK
        && part.height() >= screen.height() - FULL_SCREEN_SLACK;
    (!tiny && !fills).then_some(part)
}

/// Whether a window of class `class` is part of the Windows shell, such as
/// the desktop, the taskbar or the Start menu, rather than an app's.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn is_shell_class(class: &str) -> bool {
    matches!(
        class,
        "Progman"
            | "WorkerW"
            | "Shell_TrayWnd"
            | "Shell_SecondaryTrayWnd"
            | "Windows.UI.Core.CoreWindow"
            | "XamlExplorerHostIslandWindow"
            | "MultitaskingViewFrame"
            | "TaskListThumbnailWnd"
            | "NotifyIconOverflowWindow"
            | "TopLevelWindowForOverflowXamlIsland"
    )
}

/// The name a screenshot is filed under: the game's own name from its
/// program file (`description`, else `product`), unless that is missing or
/// says nothing, such as a game engine's name; else the window's `title`;
/// else "Desktop", as for a screenshot of the desktop. Made fit for file
/// names.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn game_name(description: &str, product: &str, title: &str) -> String {
    [description, product]
        .into_iter()
        .map(|name| clean_name(name, MAX_NAME))
        .find(|name| !is_generic(name))
        .or_else(|| Some(clean_name(title, MAX_NAME)).filter(|t| !t.is_empty()))
        .unwrap_or_else(|| "Desktop".to_owned())
}

/// Whether a program's name says nothing about which game it is.
#[cfg_attr(not(windows), allow(dead_code))]
fn is_generic(name: &str) -> bool {
    const GENERIC: [&str; 18] = [
        "",
        "game",
        "application",
        "app",
        "launcher",
        "client",
        "main",
        "player",
        "unity",
        "unity player",
        "unrealgame",
        "ue4game",
        "unreal engine",
        "bootstrappackagedgame",
        "java(tm) platform se binary",
        "openjdk platform binary",
        "microsoft windows operating system",
        // The frame around Windows Store apps.
        "application frame host",
    ];
    let name = name.to_lowercase();
    GENERIC.contains(&name.as_str()) || name.ends_with(".exe") || name.contains("-shipping")
}

/// The longest name a game gets in file and folder names, in characters.
const MAX_NAME: usize = 60;

/// `text` made fit for a Windows file or folder name: without the
/// characters Windows doesn't allow or trademark signs, on one line, at
/// most `max` characters, and not ending in a dot or a space, which
/// Windows doesn't allow either. May be empty.
fn clean_name(text: &str, max: usize) -> String {
    let name = text
        .chars()
        .filter(|c| !matches!(c, '\u{ae}' | '\u{2122}' | '\u{a9}'))
        .map(|c| match c {
            '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' => ' ',
            c if c.is_control() => ' ',
            c => c,
        })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let name: String = name.chars().take(max).collect();
    name.trim_end_matches(['.', ' ']).to_owned()
}

/// The folder a screenshot of `game` goes in: a subfolder named after the
/// game, when the options say so.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn shot_folder(options: &Options, game: &str) -> PathBuf {
    if !options.game_folders {
        return options.folder.clone();
    }
    let mut name = clean_name(game, MAX_NAME);
    if name.is_empty() {
        name = "Desktop".to_owned();
    }
    // Names Windows keeps for devices, even with an extension.
    let stem = name.split('.').next().unwrap_or_default().to_uppercase();
    let numbered = stem.len() == 4
        && (stem.starts_with("COM") || stem.starts_with("LPT"))
        && stem.ends_with(|c: char| c.is_ascii_digit());
    if numbered || matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") {
        name.push('_');
    }
    options.folder.join(name)
}

/// A file name for a screenshot of `game` (a game's name, usually) taken
/// at `time` (year, month, day, hour, minute, second), like Game Bar's:
/// "Game 2026-11-28 13-45-02".
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn file_stem(game: &str, time: [u16; 6]) -> String {
    let name = clean_name(game, MAX_NAME);
    let name = if name.is_empty() { "Screenshot" } else { &name };
    let [y, mo, d, h, mi, s] = time;
    format!("{name} {y:04}-{mo:02}-{d:02} {h:02}-{mi:02}-{s:02}")
}

/// How the desktop image is turned relative to the screen, as DXGI
/// reports for a monitor in portrait or upside down.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) enum Rotation {
    None,
    /// The screen shows the image turned 90 degrees clockwise.
    Cw90,
    Cw180,
    Cw270,
}

/// Turns `pixels`, `width` by `height`, the way the screen shows them.
/// Returns the new width and height.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn rotate<T: Copy>(
    pixels: &mut Vec<T>,
    width: usize,
    height: usize,
    rotation: Rotation,
) -> (usize, usize) {
    let (w, h) = match rotation {
        Rotation::None => return (width, height),
        Rotation::Cw180 => (width, height),
        Rotation::Cw90 | Rotation::Cw270 => (height, width),
    };
    // Where the pixel shown at `x`, `y` is in `pixels`.
    let source = |x: usize, y: usize| {
        let (sx, sy) = match rotation {
            Rotation::Cw90 => (y, height - 1 - x),
            Rotation::Cw180 => (width - 1 - x, height - 1 - y),
            _ => (width - 1 - y, x),
        };
        sy * width + sx
    };
    let turned = (0..h)
        .flat_map(|y| (0..w).map(move |x| (x, y)))
        .map(|(x, y)| pixels[source(x, y)])
        .collect();
    *pixels = turned;
    (w, h)
}

/// The Windows side: capturing, cutting out and saving. Region capture
/// builds on `capture`, `Frame::crop` and `save` too.
#[cfg(windows)]
pub(crate) mod imp {
    use std::path::{Path, PathBuf};
    use std::sync::mpsc::{Sender, sync_channel};
    use std::sync::{Arc, Mutex};
    use std::thread::JoinHandle;

    use windows::Win32::Foundation::{
        CloseHandle, E_ACCESSDENIED, GENERIC_WRITE, HMODULE, HWND, LPARAM, POINT, RECT, WPARAM,
    };
    use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_UNKNOWN;
    use windows::Win32::Graphics::Direct3D11::{
        D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
        D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,
        D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
    };
    use windows::Win32::Graphics::Dwm::{
        DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute,
    };
    use windows::Win32::Graphics::Dxgi::Common::{
        DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_FORMAT_R16G16B16A16_FLOAT,
        DXGI_MODE_ROTATION_ROTATE90, DXGI_MODE_ROTATION_ROTATE180, DXGI_MODE_ROTATION_ROTATE270,
    };
    use windows::Win32::Graphics::Dxgi::{
        CreateDXGIFactory1, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE,
        DXGI_ERROR_SESSION_DISCONNECTED, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT,
        DXGI_OUTDUPL_FRAME_INFO, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput, IDXGIOutput5,
        IDXGIOutput6, IDXGIOutputDuplication, IDXGIResource,
    };
    use windows::Win32::Graphics::Gdi::{
        HMONITOR, MONITOR_DEFAULTTOPRIMARY, MonitorFromPoint, MonitorFromWindow,
    };
    use windows::Win32::Graphics::Imaging::{
        CLSID_WICImagingFactory, GUID_ContainerFormatWmp, GUID_WICPixelFormat64bppRGBAHalf,
        IWICBitmapFrameEncode, IWICImagingFactory, WICBitmapEncoderNoCache,
    };
    use windows::Win32::Storage::FileSystem::{
        GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW,
    };
    use windows::Win32::System::Com::StructuredStorage::{IPropertyBag2, PROPBAG2};
    use windows::Win32::System::Com::{
        CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree,
    };
    use windows::Win32::System::SystemInformation::GetLocalTime;
    use windows::Win32::System::Threading::{
        GetCurrentProcessId, GetCurrentThreadId, OpenProcess, PROCESS_NAME_WIN32,
        PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
    };
    use windows::Win32::System::Variant::VARIANT;
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        HOT_KEY_MODIFIERS, MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, RegisterHotKey,
        UnregisterHotKey, VK_SNAPSHOT,
    };
    use windows::Win32::UI::Shell::{FOLDERID_Pictures, KF_FLAG_DEFAULT, SHGetKnownFolderPath};
    use windows::Win32::UI::WindowsAndMessaging::{
        GA_ROOT, GetAncestor, GetClassNameW, GetCursorPos, GetForegroundWindow, GetMessageW,
        GetWindowTextW, GetWindowThreadProcessId, IsIconic, IsWindowVisible, MSG, PM_NOREMOVE,
        PeekMessageW, PostThreadMessageW, WM_HOTKEY, WM_QUIT, WM_USER,
    };
    use windows::core::{GUID, HSTRING, Interface, PCWSTR, PWSTR, w};

    use super::{
        Area, Frame, Options, Rect, Rotation, Shortcut, Shot, Taken, Target, check_folder,
        file_stem, game_name, is_shell_class, rotate, shot_folder, window_area,
    };

    /// The hotkeys' ids, one for each shortcut, as each has a thread.
    const HOTKEY_ID: i32 = 1;
    pub const REGION_HOTKEY_ID: i32 = 2;

    /// A thread that owns the registered hotkey and waits for presses.
    pub struct HotkeyThread {
        id: u32,
        handle: Option<JoinHandle<()>>,
    }

    impl HotkeyThread {
        /// Takes a screenshot on each press.
        pub fn start(
            shortcut: Shortcut,
            options: Arc<Mutex<Options>>,
            taken: Sender<Taken>,
            ctx: egui::Context,
        ) -> Result<Self, String> {
            Self::start_with(shortcut, HOTKEY_ID, move || {
                // It would capture the overlay, dimmed.
                if crate::region::showing() {
                    return;
                }
                let options = options.lock().map(|o| o.clone()).unwrap_or_default();
                if taken.send(take(Target::Foreground, &options)).is_ok() {
                    ctx.request_repaint();
                }
            })
        }

        /// Calls `press` on the thread on each press. Windows lets the
        /// thread that gets a hotkey bring its windows to the front, as the
        /// region overlay needs.
        pub fn start_with(
            shortcut: Shortcut,
            hotkey_id: i32,
            mut press: impl FnMut() + Send + 'static,
        ) -> Result<Self, String> {
            let modifiers = match shortcut {
                Shortcut::Off => return Err("No shortcut".to_owned()),
                Shortcut::CtrlShiftPrintScreen => MOD_CONTROL | MOD_SHIFT,
                Shortcut::CtrlPrintScreen => MOD_CONTROL,
                Shortcut::ShiftPrintScreen => MOD_SHIFT,
                Shortcut::CtrlAltPrintScreen => MOD_CONTROL | MOD_ALT,
            };
            let (ready, registered) = sync_channel(1);
            let handle = std::thread::spawn(move || {
                // SAFETY: plain Win32 calls on this thread's own queue and
                // hotkey.
                unsafe {
                    // Makes the thread's message queue, so a quit message
                    // can't arrive before there is one.
                    let mut msg = MSG::default();
                    let _ = PeekMessageW(&mut msg, None, WM_USER, WM_USER, PM_NOREMOVE);
                    let modifiers = HOT_KEY_MODIFIERS(modifiers.0 | MOD_NOREPEAT.0);
                    let result =
                        RegisterHotKey(None, hotkey_id, modifiers, u32::from(VK_SNAPSHOT.0));
                    let ok = result.is_ok();
                    let _ = ready.send(result.map(|()| GetCurrentThreadId()));
                    if !ok {
                        return;
                    }
                    while GetMessageW(&mut msg, None, 0, 0).as_bool() {
                        if msg.message == WM_HOTKEY {
                            press();
                        }
                    }
                    let _ = UnregisterHotKey(None, hotkey_id);
                }
            });
            match registered.recv() {
                Ok(Ok(id)) => Ok(Self {
                    id,
                    handle: Some(handle),
                }),
                _ => {
                    let _ = handle.join();
                    Err(format!(
                        "{} is taken by another app. Choose another shortcut.",
                        shortcut.label()
                    ))
                }
            }
        }

        pub fn stop(&mut self) {
            // SAFETY: posts to the thread started above, which then ends.
            unsafe {
                let _ = PostThreadMessageW(self.id, WM_QUIT, WPARAM(0), LPARAM(0));
            }
            if let Some(handle) = self.handle.take() {
                let _ = handle.join();
            }
        }
    }

    /// The user's Pictures folder, wherever it was moved, e.g. to OneDrive.
    pub fn pictures() -> Option<PathBuf> {
        // SAFETY: the returned string is copied, then freed as documented.
        unsafe {
            let path = SHGetKnownFolderPath(&FOLDERID_Pictures, KF_FLAG_DEFAULT, None).ok()?;
            let text = path.to_string().ok();
            CoTaskMemFree(Some(path.0 as *const _));
            text.map(PathBuf::from)
        }
    }

    /// Takes a screenshot of `target` as the options say and saves it as
    /// JPEG XR.
    pub fn take(target: Target, options: &Options) -> Taken {
        check_folder(options)?;
        // SAFETY: initializes COM for this thread, as WIC needs; the window
        // calls only read.
        let (monitor, window) = unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
            match target {
                Target::Foreground => {
                    let front = GetForegroundWindow();
                    (
                        MonitorFromWindow(front, MONITOR_DEFAULTTOPRIMARY),
                        app_window(front),
                    )
                }
                Target::Pointer => {
                    let mut point = POINT::default();
                    let _ = GetCursorPos(&mut point);
                    (MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY), None)
                }
            }
        };
        let screen = capture(monitor)?;
        let cut = window
            .filter(|_| options.area == Area::Window)
            .and_then(window_rect)
            .and_then(|rect| window_area(rect, screen.bounds()))
            .and_then(|rect| screen.crop(rect));
        let (frame, area) = match cut {
            Some(frame) => (frame, Area::Window),
            None => (screen, Area::Screen),
        };
        let game = game_of(window);
        let path = save(&frame, &shot_folder(options, &game), &game)?;
        Ok(Shot {
            path,
            game,
            hdr: frame.hdr,
            area,
        })
    }

    /// Saves `frame` into `folder`, which is made if need be, as a JPEG XR
    /// file named after `game` and the time. Returns the file's path.
    /// The shutter sounds once the folder is there, before the file is
    /// encoded, so it comes right away but not for a capture that can't
    /// be kept.
    pub fn save(frame: &Frame, folder: &Path, game: &str) -> Result<PathBuf, String> {
        std::fs::create_dir_all(folder)
            .map_err(|e| format!("Can't make {}: {e}", folder.display()))?;
        crate::sound::shutter();
        // SAFETY: fills a plain struct.
        let now = unsafe { GetLocalTime() };
        let stem = file_stem(
            game,
            [
                now.wYear,
                now.wMonth,
                now.wDay,
                now.wHour,
                now.wMinute,
                now.wSecond,
            ],
        );
        let mut path = folder.join(format!("{stem}.jxr"));
        let mut n = 2;
        while path.exists() {
            path = folder.join(format!("{stem} ({n}).jxr"));
            n += 1;
        }
        // Written under another name first, so a watch folder or the app
        // never sees half a file.
        let partial = path.with_extension("jxr.partial");
        // SAFETY: COM was initialized on this thread by `take` or the
        // caller; a second call is harmless.
        let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
        let written = save_jxr(frame, &partial);
        if let Err(e) = written {
            let _ = std::fs::remove_file(&partial);
            return Err(format!("Couldn't save the screenshot: {}", e.message()));
        }
        std::fs::rename(&partial, &path).map_err(|e| {
            let _ = std::fs::remove_file(&partial);
            format!("Couldn't save the screenshot: {e}")
        })?;
        Ok(path)
    }

    /// `window`'s top-level window, if it is an app's window a screenshot
    /// can show: not the desktop, the taskbar or another part of the
    /// shell, not hdrshot's own, and not minimized or hidden.
    pub fn app_window(window: HWND) -> Option<HWND> {
        if window.is_invalid() {
            return None;
        }
        // SAFETY: Win32 calls that only read about the window; the buffers'
        // lengths are passed with them.
        unsafe {
            let root = GetAncestor(window, GA_ROOT);
            let window = if root.is_invalid() { window } else { root };
            if !IsWindowVisible(window).as_bool() || IsIconic(window).as_bool() {
                return None;
            }
            // E.g. on another virtual desktop, or a suspended store app.
            let mut cloaked = 0u32;
            let is_cloaked = DwmGetWindowAttribute(
                window,
                DWMWA_CLOAKED,
                (&raw mut cloaked).cast(),
                size_of::<u32>() as u32,
            )
            .is_ok()
                && cloaked != 0;
            let mut process = 0;
            GetWindowThreadProcessId(window, Some(&mut process));
            let mut class = [0u16; 256];
            let len = GetClassNameW(window, &mut class);
            let class = String::from_utf16_lossy(&class[..len.max(0) as usize]);
            let own = process == GetCurrentProcessId();
            (!is_cloaked && !own && !is_shell_class(&class)).then_some(window)
        }
    }

    /// Where `window` shows on the desktop, in physical pixels, without the
    /// invisible borders Windows adds for resizing.
    pub fn window_rect(window: HWND) -> Option<Rect> {
        let mut rect = RECT::default();
        // SAFETY: the struct's size is passed with it. hdrshot is aware of
        // each screen's scale (winit sets it up), and the frame bounds are
        // in physical pixels regardless, as the screens' places are.
        unsafe {
            DwmGetWindowAttribute(
                window,
                DWMWA_EXTENDED_FRAME_BOUNDS,
                (&raw mut rect).cast(),
                size_of::<RECT>() as u32,
            )
            .ok()?;
        }
        Some(Rect {
            left: rect.left,
            top: rect.top,
            right: rect.right,
            bottom: rect.bottom,
        })
    }

    /// The name to file a screenshot of `window` under (see `game_name`);
    /// "Desktop" without one.
    pub fn game_of(window: Option<HWND>) -> String {
        let Some(window) = window else {
            return game_name("", "", "");
        };
        let (description, product) = program_names(window).unwrap_or_default();
        game_name(&description, &product, &window_title(window))
    }

    fn window_title(window: HWND) -> String {
        let mut text = [0u16; 256];
        // SAFETY: the buffer's length is passed with it.
        let len = unsafe { GetWindowTextW(window, &mut text) };
        let title = String::from_utf16_lossy(&text[..len.max(0) as usize]);
        // The desktop itself.
        if title == "Program Manager" {
            String::new()
        } else {
            title
        }
    }

    /// The description and product name in the version information of the
    /// program that shows `window`, e.g. the game's name. `None` when it
    /// can't be read, as for a game that runs as administrator.
    fn program_names(window: HWND) -> Option<(String, String)> {
        // SAFETY: the process handle is closed after use; the version data
        // outlives the pointers into it, which VerQueryValueW returns with
        // their lengths.
        unsafe {
            let mut process = 0;
            GetWindowThreadProcessId(window, Some(&mut process));
            if process == 0 {
                return None;
            }
            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process).ok()?;
            let mut path = [0u16; 1024];
            let mut len = path.len() as u32;
            let named = QueryFullProcessImageNameW(
                handle,
                PROCESS_NAME_WIN32,
                PWSTR(path.as_mut_ptr()),
                &mut len,
            );
            let _ = CloseHandle(handle);
            named.ok()?;
            let file = PCWSTR(path.as_ptr());
            let size = GetFileVersionInfoSizeW(file, None);
            if size == 0 {
                return None;
            }
            // In u32s, so the values inside are aligned for reading.
            let mut data = vec![0u32; (size as usize).div_ceil(4)];
            GetFileVersionInfoW(file, None, size, data.as_mut_ptr().cast()).ok()?;
            let block = data.as_ptr().cast::<std::ffi::c_void>();
            let mut languages = Vec::new();
            let mut value = std::ptr::null_mut();
            let mut len = 0u32;
            if VerQueryValueW(
                block,
                w!("\\VarFileInfo\\Translation"),
                &mut value,
                &mut len,
            )
            .as_bool()
                && !value.is_null()
            {
                let pairs = std::slice::from_raw_parts(value as *const [u16; 2], len as usize / 4);
                languages.extend(pairs.iter().map(|[l, c]| format!("{l:04x}{c:04x}")));
            }
            // US English, as most programs have, in Unicode and Windows'
            // Western code page.
            languages.extend(["040904b0".to_owned(), "040904e4".to_owned()]);
            let text = |key: &str| {
                languages.iter().find_map(|language| {
                    let name = HSTRING::from(format!("\\StringFileInfo\\{language}\\{key}"));
                    let mut value = std::ptr::null_mut();
                    let mut len = 0u32;
                    if !VerQueryValueW(block, &name, &mut value, &mut len).as_bool()
                        || value.is_null()
                        || len == 0
                    {
                        return None;
                    }
                    let chars = std::slice::from_raw_parts(value as *const u16, len as usize);
                    let end = chars.iter().position(|&c| c == 0).unwrap_or(chars.len());
                    Some(String::from_utf16_lossy(&chars[..end]))
                })
            };
            Some((
                text("FileDescription").unwrap_or_default(),
                text("ProductName").unwrap_or_default(),
            ))
        }
    }

    /// Says what went wrong in words.
    fn describe(e: &windows::core::Error) -> String {
        let code = e.code();
        if code == E_ACCESSDENIED {
            "Windows doesn't allow screenshots right now, e.g. while a UAC prompt or \
             the lock screen shows"
                .to_owned()
        } else if code == DXGI_ERROR_UNSUPPORTED {
            "Windows can't capture this screen with this graphics driver".to_owned()
        } else if code == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE {
            "Too many apps are capturing the screen right now".to_owned()
        } else if code == DXGI_ERROR_SESSION_DISCONNECTED || code == DXGI_ERROR_ACCESS_LOST {
            "The screen changed while taking the screenshot. Try again.".to_owned()
        } else {
            format!("Couldn't capture the screen: {}", e.message())
        }
    }

    /// One in half float.
    const HALF_ONE: u16 = 0x3c00;

    /// How long to wait for the screen to show a new frame. A game shows
    /// one every few milliseconds; a still desktop may show none.
    const FRAME_WAIT_MS: u32 = 250;

    /// The picture `monitor` shows, the whole screen, turned the way it
    /// shows it and placed where the screen is on the desktop.
    pub fn capture(monitor: HMONITOR) -> Result<Frame, String> {
        capture_screen(monitor).map_err(|e| describe(&e))
    }

    fn capture_screen(monitor: HMONITOR) -> windows::core::Result<Frame> {
        // SAFETY: COM calls on objects made here; the mapped memory is
        // read within its row pitch and unmapped before it's released.
        unsafe {
            let (adapter, output) = find_output(monitor)?;
            // Where the screen is on the desktop, as shown, so turned
            // like the picture once `rotate` has turned it.
            let place = output.GetDesc()?.DesktopCoordinates;
            // HDR shows in the PQ (ST 2084) color space. When Windows can't
            // say, as before Windows 10 version 1803, no warning is better
            // than a wrong one.
            let hdr = output
                .cast::<IDXGIOutput6>()
                .and_then(|o| o.GetDesc1())
                .map_or(true, |d| {
                    d.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020
                });
            let output: IDXGIOutput5 = output.cast().map_err(|_| {
                windows::core::Error::new(
                    DXGI_ERROR_UNSUPPORTED,
                    "HDR screenshots need Windows 10 version 1703 or later",
                )
            })?;
            let mut device: Option<ID3D11Device> = None;
            let mut context: Option<ID3D11DeviceContext> = None;
            D3D11CreateDevice(
                &adapter,
                D3D_DRIVER_TYPE_UNKNOWN,
                HMODULE::default(),
                D3D11_CREATE_DEVICE_BGRA_SUPPORT,
                None,
                D3D11_SDK_VERSION,
                Some(&mut device),
                None,
                Some(&mut context),
            )?;
            let device = device.expect("D3D11CreateDevice made a device");
            let context = context.expect("D3D11CreateDevice made a context");
            // Float even when HDR is off: Windows converts the desktop.
            let duplication =
                output.DuplicateOutput1(&device, 0, &[DXGI_FORMAT_R16G16B16A16_FLOAT])?;
            let rotation = match duplication.GetDesc().Rotation {
                DXGI_MODE_ROTATION_ROTATE90 => Rotation::Cw90,
                DXGI_MODE_ROTATION_ROTATE180 => Rotation::Cw180,
                DXGI_MODE_ROTATION_ROTATE270 => Rotation::Cw270,
                _ => Rotation::None,
            };
            let staging = newest_frame(&duplication, &device, &context)?;
            let mut desc = D3D11_TEXTURE2D_DESC::default();
            staging.GetDesc(&mut desc);
            if desc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT {
                return Err(windows::core::Error::new(
                    DXGI_ERROR_UNSUPPORTED,
                    "Windows gave the screen in a format other than 16-bit float",
                ));
            }
            let (width, height) = (desc.Width as usize, desc.Height as usize);
            let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
            context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;
            let mut pixels = Vec::with_capacity(width * height);
            for y in 0..height {
                let row = (mapped.pData as *const u8).add(y * mapped.RowPitch as usize);
                let row = std::slice::from_raw_parts(row as *const [u16; 4], width);
                // The alpha channel means nothing on a screen.
                pixels.extend(row.iter().map(|&[r, g, b, _]| [r, g, b, HALF_ONE]));
            }
            context.Unmap(&staging, 0);
            let (width, height) = rotate(&mut pixels, width, height, rotation);
            Ok(Frame {
                width,
                height,
                pixels,
                left: place.left,
                top: place.top,
                hdr,
            })
        }
    }

    /// The graphics adapter and output that show `monitor`.
    unsafe fn find_output(
        monitor: HMONITOR,
    ) -> windows::core::Result<(IDXGIAdapter1, IDXGIOutput)> {
        // SAFETY: plain DXGI enumeration.
        unsafe {
            let factory: IDXGIFactory1 = CreateDXGIFactory1()?;
            let mut first = None;
            let mut a = 0;
            while let Ok(adapter) = factory.EnumAdapters1(a) {
                let mut o = 0;
                while let Ok(output) = adapter.EnumOutputs(o) {
                    if output.GetDesc()?.Monitor == monitor {
                        return Ok((adapter, output));
                    }
                    if first.is_none() {
                        first = Some((adapter.clone(), output));
                    }
                    o += 1;
                }
                a += 1;
            }
            first
                .ok_or_else(|| windows::core::Error::new(DXGI_ERROR_UNSUPPORTED, "No screen found"))
        }
    }

    /// Copies the screen's picture into a texture the CPU can read. The
    /// first frame may be from before the latest one shown, so this waits
    /// briefly for one the screen actually presented.
    unsafe fn newest_frame(
        duplication: &IDXGIOutputDuplication,
        device: &ID3D11Device,
        context: &ID3D11DeviceContext,
    ) -> windows::core::Result<ID3D11Texture2D> {
        // SAFETY: each acquired frame is released before the next.
        unsafe {
            let mut staging: Option<ID3D11Texture2D> = None;
            for _ in 0..4 {
                let mut info = DXGI_OUTDUPL_FRAME_INFO::default();
                let mut resource: Option<IDXGIResource> = None;
                match duplication.AcquireNextFrame(FRAME_WAIT_MS, &mut info, &mut resource) {
                    Ok(()) => {}
                    Err(e) if e.code() == DXGI_ERROR_WAIT_TIMEOUT => {
                        if staging.is_some() {
                            break;
                        }
                        continue;
                    }
                    Err(e) => return Err(e),
                }
                let presented = info.LastPresentTime != 0;
                if let Some(resource) = resource
                    && (presented || staging.is_none())
                {
                    let texture: ID3D11Texture2D = resource.cast()?;
                    if staging.is_none() {
                        let mut desc = D3D11_TEXTURE2D_DESC::default();
                        texture.GetDesc(&mut desc);
                        desc.Usage = D3D11_USAGE_STAGING;
                        desc.BindFlags = 0;
                        desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;
                        desc.MiscFlags = 0;
                        desc.MipLevels = 1;
                        desc.ArraySize = 1;
                        device.CreateTexture2D(&desc, None, Some(&mut staging))?;
                    }
                    context.CopyResource(staging.as_ref().expect("made above"), &texture);
                }
                duplication.ReleaseFrame()?;
                if presented && staging.is_some() {
                    break;
                }
            }
            staging.ok_or_else(|| {
                windows::core::Error::new(
                    DXGI_ERROR_WAIT_TIMEOUT,
                    "The screen didn't show a picture in time",
                )
            })
        }
    }

    /// Saves `frame` as a lossless JPEG XR file with Windows' own encoder,
    /// the format Game Bar saves HDR screenshots in.
    fn save_jxr(frame: &Frame, path: &Path) -> windows::core::Result<()> {
        // SAFETY: COM calls on objects made here; the pixels outlive them.
        unsafe {
            let factory: IWICImagingFactory =
                CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
            let stream = factory.CreateStream()?;
            let name = HSTRING::from(path.as_os_str());
            stream.InitializeFromFilename(PCWSTR(name.as_ptr()), GENERIC_WRITE.0)?;
            let encoder = factory.CreateEncoder(&GUID_ContainerFormatWmp, std::ptr::null())?;
            encoder.Initialize(&stream, WICBitmapEncoderNoCache)?;
            let mut encode: Option<IWICBitmapFrameEncode> = None;
            let mut options: Option<IPropertyBag2> = None;
            encoder.CreateNewFrame(&mut encode, &mut options)?;
            let encode = encode.expect("CreateNewFrame made a frame");
            if let Some(options) = &options {
                // 1.0 is lossless.
                let name = PROPBAG2 {
                    pstrName: windows::core::PWSTR(w!("ImageQuality").as_ptr() as *mut u16),
                    ..Default::default()
                };
                options.Write(1, &name, &VARIANT::from(1.0f32))?;
            }
            encode.Initialize(options.as_ref())?;
            encode.SetSize(frame.width as u32, frame.height as u32)?;
            let wanted: GUID = GUID_WICPixelFormat64bppRGBAHalf;
            let mut format = wanted;
            encode.SetPixelFormat(&mut format)?;
            if format != wanted {
                return Err(windows::core::Error::new(
                    DXGI_ERROR_UNSUPPORTED,
                    "Windows' JPEG XR encoder doesn't take 16-bit float pixels",
                ));
            }
            let bytes = std::slice::from_raw_parts(
                frame.pixels.as_ptr() as *const u8,
                frame.pixels.len() * 8,
            );
            let stride = frame.width as u32 * 8;
            // In bands, as WIC limits the size of one call.
            let band = (16 * 1024 * 1024 / stride as usize).max(1);
            for rows in bytes.chunks(band * stride as usize) {
                encode.WritePixels(rows.len() as u32 / stride, stride, rows)?;
            }
            encode.Commit()?;
            encoder.Commit()?;
            Ok(())
        }
    }

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

        /// Windows' encoder writes a file that hdrshot reads back as the
        /// same HDR picture.
        #[test]
        fn jxr_round_trip() {
            // SAFETY: initializes COM for this test thread.
            let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
            let half = |v: f32| {
                // Exact for these values: 0.5, 1, 4.
                match v {
                    0.5 => 0x3800,
                    1.0 => 0x3c00,
                    _ => 0x4400,
                }
            };
            let (width, height) = (16, 8);
            let pixels = (0..width * height)
                .map(|i| {
                    let v = [0.5, 1.0, 4.0][i % 3];
                    [half(v), half(1.0), half(0.5), HALF_ONE]
                })
                .collect();
            let frame = Frame {
                width,
                height,
                pixels,
                left: 0,
                top: 0,
                hdr: true,
            };
            let path =
                std::env::temp_dir().join(format!("hdrshot-shot-{}.jxr", std::process::id()));
            save_jxr(&frame, &path).unwrap();
            let bytes = std::fs::read(&path).unwrap();
            let image = hdrshot_core::decode::decode(&bytes).unwrap();
            let _ = std::fs::remove_file(&path);
            assert_eq!((image.width, image.height), (16, 8));
            for (i, p) in image.pixels.iter().enumerate() {
                let v = [0.5, 1.0, 4.0][i % 3];
                assert!((p[0] - v).abs() < 1e-3, "{p:?} at {i}");
                assert!((p[1] - 1.0).abs() < 1e-3 && (p[2] - 0.5).abs() < 1e-3);
            }
        }
    }
}

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

    #[test]
    fn names_like_game_bar() {
        let time = [2026, 11, 28, 9, 5, 2];
        assert_eq!(
            file_stem("Some Game", time),
            "Some Game 2026-11-28 09-05-02"
        );
        assert_eq!(
            file_stem("  A: B / C?  ", time),
            "A B C 2026-11-28 09-05-02"
        );
        assert_eq!(file_stem("", time), "Screenshot 2026-11-28 09-05-02");
        assert_eq!(file_stem("...", time), "Screenshot 2026-11-28 09-05-02");
        let long = "x".repeat(100);
        assert_eq!(file_stem(&long, time).len(), 60 + 20);
    }

    #[test]
    fn rotations() {
        // 3 by 2:
        // a b c
        // d e f
        let image = vec!['a', 'b', 'c', 'd', 'e', 'f'];
        let turned = |rotation| {
            let mut pixels = image.clone();
            let size = rotate(&mut pixels, 3, 2, rotation);
            (size, pixels.into_iter().collect::<String>())
        };
        assert_eq!(turned(Rotation::None), ((3, 2), "abcdef".into()));
        // Turned clockwise: d a / e b / f c.
        assert_eq!(turned(Rotation::Cw90), ((2, 3), "daebfc".into()));
        assert_eq!(turned(Rotation::Cw180), ((3, 2), "fedcba".into()));
        // Counterclockwise: c f / b e / a d.
        assert_eq!(turned(Rotation::Cw270), ((2, 3), "cfbead".into()));
    }

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

    /// A 4 by 3 frame on a screen to the left of the main one, each pixel
    /// holding its own position.
    fn frame() -> Frame {
        Frame {
            width: 4,
            height: 3,
            pixels: (0..3)
                .flat_map(|y| (0..4).map(move |x| [x, y, 0, 0x3c00]))
                .collect(),
            left: -4,
            top: 10,
            hdr: false,
        }
    }

    #[test]
    fn crops_in_desktop_coordinates() {
        let frame = frame();
        assert_eq!(frame.bounds(), rect(-4, 10, 0, 13));
        let part = frame.crop(rect(-3, 11, -1, 13)).unwrap();
        assert_eq!((part.width, part.height), (2, 2));
        assert_eq!((part.left, part.top, part.hdr), (-3, 11, false));
        let positions: Vec<_> = part.pixels.iter().map(|p| (p[0], p[1])).collect();
        assert_eq!(positions, [(1, 1), (2, 1), (1, 2), (2, 2)]);
        // Partly off the frame: cut to it.
        let part = frame.crop(rect(-2, 0, 50, 11)).unwrap();
        assert_eq!(
            (part.width, part.height, part.left, part.top),
            (2, 1, -2, 10)
        );
        assert_eq!(part.pixels[0][..2], [2, 0]);
        // All of it.
        assert_eq!(frame.crop(rect(-100, -100, 100, 100)), Some(frame.clone()));
        // Off it, or empty.
        assert_eq!(frame.crop(rect(0, 10, 5, 13)), None);
        assert_eq!(frame.crop(rect(-3, 11, -3, 12)), None);
    }

    #[test]
    fn window_or_whole_screen() {
        let screen = rect(1920, 0, 3840, 1080);
        // A window on the screen, partly off it.
        assert_eq!(
            window_area(rect(1800, 100, 2600, 700), screen),
            Some(rect(1920, 100, 2600, 700))
        );
        // Maximized, above the taskbar: the window.
        assert_eq!(
            window_area(rect(1920, 0, 3840, 1032), screen),
            Some(rect(1920, 0, 3840, 1032))
        );
        // Full screen, give or take a few pixels: the whole screen.
        assert_eq!(window_area(screen, screen), None);
        assert_eq!(window_area(rect(1912, -8, 3848, 1088), screen), None);
        assert_eq!(window_area(rect(1922, 2, 3838, 1078), screen), None);
        // Tiny, or on another screen.
        assert_eq!(window_area(rect(2000, 100, 2050, 600), screen), None);
        assert_eq!(window_area(rect(0, 0, 800, 600), screen), None);
    }

    #[test]
    fn shell_windows() {
        assert!(is_shell_class("Progman"));
        assert!(is_shell_class("WorkerW"));
        assert!(is_shell_class("Shell_TrayWnd"));
        assert!(!is_shell_class("UnrealWindow"));
        assert!(!is_shell_class("CabinetWClass"));
    }

    #[test]
    fn names_games() {
        assert_eq!(
            game_name("Cyberpunk 2077", "Cyberpunk", "x"),
            "Cyberpunk 2077"
        );
        assert_eq!(game_name("ELDEN RING\u{2122}", "", "x"), "ELDEN RING");
        // Engine names say nothing: the product or the title instead.
        assert_eq!(
            game_name("Unity Player", "Hollow Knight", "x"),
            "Hollow Knight"
        );
        assert_eq!(game_name("", "UnrealGame", "Some Game  "), "Some Game");
        assert_eq!(
            game_name("Game-Win64-Shipping", "", "Some: Game"),
            "Some Game"
        );
        assert_eq!(game_name("game.exe", "", "Title"), "Title");
        assert_eq!(game_name("  ", "", ""), "Desktop");
        assert_eq!(game_name("", "", "???"), "Desktop");
    }

    #[test]
    fn no_screenshot_without_a_folder() {
        let mut options = Options::default();
        assert_eq!(
            check_folder(&options),
            Err("Choose a folder for screenshots in Settings".to_owned())
        );
        options.folder = PathBuf::from("shots");
        assert_eq!(check_folder(&options), Ok(()));
    }

    #[test]
    fn folder_per_game() {
        let mut options = Options {
            folder: PathBuf::from("shots"),
            area: Area::Window,
            game_folders: true,
        };
        let folder = |options: &Options, game: &str| shot_folder(options, game);
        assert_eq!(folder(&options, "Some Game"), Path::new("shots/Some Game"));
        assert_eq!(folder(&options, "A/B: C."), Path::new("shots/A B C"));
        assert_eq!(folder(&options, "..."), Path::new("shots/Desktop"));
        assert_eq!(folder(&options, "con"), Path::new("shots/con_"));
        assert_eq!(folder(&options, "COM1"), Path::new("shots/COM1_"));
        assert_eq!(folder(&options, "Company"), Path::new("shots/Company"));
        assert_eq!(
            folder(&options, &"y".repeat(100)),
            Path::new("shots").join("y".repeat(60))
        );
        options.game_folders = false;
        assert_eq!(folder(&options, "Some Game"), Path::new("shots"));
    }

    #[test]
    fn names_without_trailing_dots_or_spaces() {
        let time = [2026, 11, 28, 9, 5, 2];
        assert_eq!(file_stem("Game\u{ae} .", time), "Game 2026-11-28 09-05-02");
        let long = format!("{} tail", "x".repeat(59));
        assert_eq!(
            file_stem(&long, time),
            format!("{} 2026-11-28 09-05-02", "x".repeat(59))
        );
    }
}