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
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
//! The Screenshots view: the `.jxr` screenshots hdrshot took, as a grid
//! of thumbnails, newest first and grouped by day, with a filter by game.
//!
//! It has to stay smooth with thousands of screenshots, so the folder is
//! scanned on a background thread (when the view opens, after each new
//! screenshot and after one is deleted), only the tiles in sight are laid
//! out and drawn, and only their thumbnails are decoded, on threads of
//! their own. Thumbnails are freed when the view closes.

use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Condvar, Mutex};
use std::time::SystemTime;

use super::*;
use viewer::Source;

/// The two views under the header.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum View {
    /// The file list, to convert images.
    #[default]
    Files,
    Screenshots,
}

/// Narrowest a tile gets before the grid drops a column.
const MIN_TILE_WIDTH: f32 = 150.0;
/// Room between tiles.
const GAP: f32 = 8.0;
/// Height of the line under a thumbnail with the game and time.
const CAPTION_HEIGHT: f32 = 26.0;
/// Height of a day's heading.
const HEADING_HEIGHT: f32 = 30.0;
const RADIUS: u8 = 9;
/// Thumbnails are decoded to fit a square this size, in pixels: sharp on
/// the widest tiles at 125 % scale, small enough to keep many.
const THUMB_BOX: u32 = 384;
/// Thumbnails kept, at least: beyond that those seen longest ago go.
const CACHE: usize = 160;
/// Threads decoding thumbnails. Each holds a whole decoded screenshot
/// (about 100 MB for 4K) while it works.
const DECODERS: usize = 2;
/// How deep into subfolders the scan looks. Screenshots are in the folder
/// itself or a folder per game; deeper ones are someone else's files.
const MAX_DEPTH: usize = 3;

/// The month names for the day headings.
const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];
const WEEKDAYS: [&str; 7] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];

/// When a screenshot was taken, as its name says, in local time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Stamp {
    pub(crate) year: u16,
    pub(crate) month: u8,
    pub(crate) day: u8,
    pub(crate) hour: u8,
    pub(crate) minute: u8,
    pub(crate) second: u8,
}

impl Stamp {
    fn date(self) -> (u16, u8, u8) {
        (self.year, self.month, self.day)
    }
}

/// What a screenshot's file name says: "Game 2026-11-28 13-45-02", with
/// " (2)" and so on after it for a second one in the same second.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Name<'a> {
    /// The game, empty for a screenshot of no window in particular.
    pub(crate) game: &'a str,
    pub(crate) taken: Option<Stamp>,
    /// The number in brackets, 1 without one.
    pub(crate) number: u32,
}

/// Reads a screenshot's file stem as `screenshot::file_stem` writes it.
/// A stem without the time is all game.
pub(crate) fn parse_stem(stem: &str) -> Name<'_> {
    let (base, number) = stem
        .strip_suffix(')')
        .and_then(|s| s.rsplit_once(" ("))
        .filter(|(_, n)| n.bytes().all(|b| b.is_ascii_digit()))
        .and_then(|(base, n)| Some((base, n.parse().ok()?)))
        .unwrap_or((stem, 1));
    // "YYYY-MM-DD HH-MM-SS"
    let len = 19;
    if let Some(at) = base.len().checked_sub(len)
        && base.is_char_boundary(at)
        && let Some(taken) = parse_stamp(&base[at..])
    {
        let rest = &base[..at];
        if rest.is_empty() || rest.ends_with(' ') {
            return Name {
                game: rest.trim(),
                taken: Some(taken),
                number,
            };
        }
    }
    Name {
        game: stem,
        taken: None,
        number: 1,
    }
}

/// "2026-11-28 13-45-02", as screenshot names end.
fn parse_stamp(text: &str) -> Option<Stamp> {
    let bytes = text.as_bytes();
    let shape = bytes.len() == 19
        && bytes.iter().enumerate().all(|(i, &b)| match i {
            4 | 7 | 13 | 16 => b == b'-',
            10 => b == b' ',
            _ => b.is_ascii_digit(),
        });
    if !shape {
        return None;
    }
    let number = |from: usize, to: usize| text[from..to].parse::<u16>().ok();
    let stamp = Stamp {
        year: number(0, 4)?,
        month: number(5, 7)? as u8,
        day: number(8, 10)? as u8,
        hour: number(11, 13)? as u8,
        minute: number(14, 16)? as u8,
        second: number(17, 19)? as u8,
    };
    // Year 0 isn't a real one, and the weekday needs the year before.
    let valid = stamp.year > 0
        && (1..=12).contains(&stamp.month)
        && (1..=31).contains(&stamp.day)
        && stamp.hour < 24
        && stamp.minute < 60
        && stamp.second < 60;
    valid.then_some(stamp)
}

/// The game of the screenshot at `relative`, its path inside the
/// screenshot folder: the folder it is in, if it is in one (one folder per
/// game), else its name without the time. Also returns that time and the
/// number after it.
pub(crate) fn describe(relative: &Path) -> (String, Option<Stamp>, u32) {
    let stem = relative.file_stem().unwrap_or_default().to_string_lossy();
    let name = parse_stem(&stem);
    let mut parts = relative.components();
    let folder = match (parts.next(), parts.next()) {
        (Some(first), Some(_)) => Some(first.as_os_str().to_string_lossy().into_owned()),
        _ => None,
    };
    let game = match (folder, name.taken) {
        (Some(folder), _) => folder,
        (None, Some(_)) if !name.game.is_empty() => name.game.to_owned(),
        (None, Some(_)) => "Screenshot".to_owned(),
        (None, None) => "Other".to_owned(),
    };
    (game, name.taken, name.number)
}

/// The heading of a day: "Saturday, 28 November 2026".
pub(crate) fn day_heading((year, month, day): (u16, u8, u8)) -> String {
    let weekday = WEEKDAYS[weekday(year, month, day)];
    let month = MONTHS[usize::from(month.clamp(1, 12)) - 1];
    format!("{weekday}, {day} {month} {year}")
}

/// The day of the week, 0 for Sunday (Sakamoto's method).
fn weekday(year: u16, month: u8, day: u8) -> usize {
    const OFFSETS: [usize; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
    let month = usize::from(month.clamp(1, 12));
    let year = usize::from(year).saturating_sub(usize::from(month < 3));
    (year + year / 4 - year / 100 + year / 400 + OFFSETS[month - 1] + usize::from(day)) % 7
}

/// One screenshot in the folder.
pub(crate) struct Shot {
    pub(crate) path: PathBuf,
    pub(crate) game: String,
    /// When it was taken, from its name; `None` for files named otherwise.
    pub(crate) taken: Option<Stamp>,
    /// The number after the time, for two taken in the same second.
    number: u32,
    /// For ordering files whose name has no time.
    modified: Option<SystemTime>,
}

/// Newest first: by the time in the name, then those without one by when
/// they were last changed.
fn newest_first(a: &Shot, b: &Shot) -> Ordering {
    match (a.taken, b.taken) {
        (Some(x), Some(y)) => (y, b.number).cmp(&(x, a.number)),
        (Some(_), None) => Ordering::Less,
        (None, Some(_)) => Ordering::Greater,
        (None, None) => b.modified.cmp(&a.modified),
    }
    .then_with(|| b.path.cmp(&a.path))
}

/// The screenshots in `dir` and its subfolders, newest first.
fn scan(dir: &Path) -> Vec<Shot> {
    fn walk(root: &Path, dir: &Path, depth: usize, out: &mut Vec<Shot>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            // Links aren't followed, so a link up the tree can't loop.
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            let path = entry.path();
            if kind.is_dir() {
                if depth > 0 {
                    walk(root, &path, depth - 1, out);
                }
            } else if kind.is_file()
                && path
                    .extension()
                    .is_some_and(|e| e.eq_ignore_ascii_case("jxr"))
            {
                let relative = path.strip_prefix(root).unwrap_or(&path);
                let (game, taken, number) = describe(relative);
                let modified = match taken {
                    Some(_) => None,
                    None => entry.metadata().ok().and_then(|m| m.modified().ok()),
                };
                out.push(Shot {
                    path,
                    game,
                    taken,
                    number,
                    modified,
                });
            }
        }
    }
    let mut shots = Vec::new();
    walk(dir, dir, MAX_DEPTH, &mut shots);
    shots.sort_by(newest_first);
    shots
}

/// The paths `options` give the outputs of `input`, for those that exist.
fn converted(input: &Path, options: &ConvertOptions) -> Outputs {
    let outputs = hdrshot_core::output_paths(input, options);
    Outputs {
        hdr: outputs.hdr.filter(|p| p.is_file()),
        sdr: outputs.sdr.filter(|p| p.is_file()),
        ..Outputs::default()
    }
}

/// A thumbnail and the frame it was last in sight.
struct Thumbnail {
    /// `None` if the screenshot couldn't be read.
    texture: Option<egui::TextureHandle>,
    seen: u64,
}

/// What the decoding threads share: the screenshots to decode next, in
/// order, and those being decoded.
#[derive(Default)]
struct Queue {
    wanted: Vec<PathBuf>,
    busy: HashSet<PathBuf>,
    closed: bool,
}

type Decoded = (PathBuf, Option<egui::ColorImage>);

/// Decodes thumbnails on [`DECODERS`] threads. The list of those wanted is
/// replaced every frame with the tiles in sight, so scrolling past
/// thousands doesn't queue them all. The threads end when this is dropped.
struct Loader {
    queue: Arc<(Mutex<Queue>, Condvar)>,
    done: Receiver<Decoded>,
}

impl Loader {
    fn new(ctx: &egui::Context) -> Self {
        let queue = Arc::new((Mutex::new(Queue::default()), Condvar::new()));
        let (sender, done) = channel();
        for _ in 0..DECODERS {
            let (queue, sender, ctx) = (queue.clone(), sender.clone(), ctx.clone());
            std::thread::spawn(move || {
                let (lock, wake) = &*queue;
                loop {
                    let path = {
                        let mut q = lock.lock().unwrap_or_else(|e| e.into_inner());
                        while q.wanted.is_empty() && !q.closed {
                            q = wake.wait(q).unwrap_or_else(|e| e.into_inner());
                        }
                        if q.closed {
                            return;
                        }
                        let path = q.wanted.remove(0);
                        q.busy.insert(path.clone());
                        path
                    };
                    let image =
                        hdrshot_core::preview(&path, &Default::default(), THUMB_BOX, THUMB_BOX)
                            .ok()
                            .map(|preview| previews::sdr_image(&preview, &SdrOptions::default()));
                    // Still busy until the app has it (see `take_done`).
                    if sender.send((path, image)).is_err() {
                        return;
                    }
                    ctx.request_repaint();
                }
            });
        }
        Self { queue, done }
    }

    /// The thumbnails decoded since last asked. Only now are they no
    /// longer busy: until the app has them, a frame asking for those not
    /// shown yet would otherwise have them decoded again.
    fn take_done(&self) -> Vec<Decoded> {
        let done: Vec<Decoded> = self.done.try_iter().collect();
        if !done.is_empty() {
            let mut q = self.queue.0.lock().unwrap_or_else(|e| e.into_inner());
            for (path, _) in &done {
                q.busy.remove(path);
            }
        }
        done
    }

    /// Decodes `paths` next, in order, in place of those asked for before.
    fn want(&self, paths: Vec<PathBuf>) {
        let (lock, wake) = &*self.queue;
        let mut q = lock.lock().unwrap_or_else(|e| e.into_inner());
        let busy = &q.busy;
        let wanted: Vec<PathBuf> = paths.into_iter().filter(|p| !busy.contains(p)).collect();
        if wanted != q.wanted {
            q.wanted = wanted;
            wake.notify_all();
        }
    }
}

impl Drop for Loader {
    fn drop(&mut self) {
        let (lock, wake) = &*self.queue;
        let mut q = lock.lock().unwrap_or_else(|e| e.into_inner());
        q.closed = true;
        q.wanted.clear();
        wake.notify_all();
    }
}

/// The Screenshots view's state.
pub(crate) struct Gallery {
    /// Whether the view shows, so its thumbnails are kept.
    open: bool,
    /// The folder scanned.
    dir: Option<PathBuf>,
    shots: Vec<Shot>,
    /// Whether `shots` is what a scan of `dir` found.
    scanned: bool,
    scan: Option<Receiver<Vec<Shot>>>,
    /// Another scan wanted once the running one ends.
    rescan: bool,
    /// The game shown, or `None` for all.
    filter: Option<String>,
    /// Indices into `shots` of those the filter lets through.
    shown: Vec<usize>,
    /// Each game with its number of screenshots, by name.
    games: Vec<(String, usize)>,
    thumbs: HashMap<PathBuf, Thumbnail>,
    loader: Option<Loader>,
    /// Counts the frames the view showed in, for dropping old thumbnails.
    frame: u64,
    /// Whether Settings showed over the view last frame.
    under_settings: bool,
    /// Screenshots moved to the Recycle Bin, or why they couldn't be.
    trashed: (Sender<Trashed>, Receiver<Trashed>),
}

/// A screenshot moved to the Recycle Bin, or why it couldn't be.
type Trashed = (PathBuf, Result<(), String>);

impl Default for Gallery {
    fn default() -> Self {
        Self {
            open: false,
            dir: None,
            shots: Vec::new(),
            scanned: false,
            scan: None,
            rescan: false,
            filter: None,
            shown: Vec::new(),
            games: Vec::new(),
            thumbs: HashMap::new(),
            loader: None,
            frame: 0,
            under_settings: false,
            trashed: channel(),
        }
    }
}

impl Gallery {
    /// Frees the thumbnails and stops decoding them; the list stays, to
    /// show right away the next time.
    pub(crate) fn close(&mut self) {
        self.open = false;
        self.loader = None;
        self.thumbs.clear();
    }

    /// How many screenshots the filter lets through.
    pub(crate) fn len(&self) -> usize {
        self.shown.len()
    }

    /// Where `path` is among those the filter lets through.
    pub(crate) fn position(&self, path: &Path) -> Option<usize> {
        self.shown.iter().position(|&i| self.shots[i].path == path)
    }

    fn shot(&self, index: usize) -> Option<&Shot> {
        self.shown.get(index).map(|&i| &self.shots[i])
    }

    /// Counts the games and applies the filter, after `shots` changed.
    fn refilter(&mut self) {
        let mut counts: HashMap<&str, usize> = HashMap::new();
        for shot in &self.shots {
            *counts.entry(&shot.game).or_default() += 1;
        }
        let mut games: Vec<(String, usize)> = counts
            .into_iter()
            .map(|(game, n)| (game.to_owned(), n))
            .collect();
        games.sort_by_cached_key(|(game, _)| game.to_lowercase());
        self.games = games;
        if self
            .filter
            .as_ref()
            .is_some_and(|f| !self.games.iter().any(|(g, _)| g == f))
        {
            self.filter = None;
        }
        self.shown = (0..self.shots.len())
            .filter(|&i| {
                self.filter
                    .as_ref()
                    .is_none_or(|f| &self.shots[i].game == f)
            })
            .collect();
    }
}

/// Something done to a screenshot in the grid.
enum ShotAction {
    /// Show the large preview of the one at this place in the grid.
    View(usize),
    Copy(PathBuf),
    Open(PathBuf),
    ShowInFolder(PathBuf),
    Convert(PathBuf),
    Trash(PathBuf),
}

/// A line of the grid: a day's heading or a row of tiles, as a range of
/// places in the grid.
enum Line {
    Heading(Option<(u16, u8, u8)>),
    Tiles(std::ops::Range<usize>),
}

impl App {
    /// Whether the Screenshots view is chosen, where it's supported.
    pub(crate) fn showing_gallery(&self) -> bool {
        screenshot::SUPPORTED && self.settings.view == View::Screenshots
    }

    /// The options the outputs of a screenshot were made with.
    fn shot_options(&self) -> ConvertOptions {
        self.batch_options(Existing::Skip, true)
    }

    /// Opens or closes the view as it shows or not, and takes in what the
    /// background threads found.
    pub(crate) fn sync_gallery(&mut self, ctx: &egui::Context) {
        // Settings over the view keeps its thumbnails, so closing it
        // shows them right away; only no more are decoded meanwhile.
        let active = self.showing_gallery() && !self.hidden;
        let settings_closed =
            std::mem::replace(&mut self.gallery.under_settings, self.settings_open)
                && !self.settings_open;
        if active && !self.gallery.open {
            self.gallery.open = true;
            self.gallery.loader = Some(Loader::new(ctx));
            self.gallery_folder();
            self.rescan_gallery(ctx);
        } else if !active && self.gallery.open {
            self.gallery.close();
        } else if active && settings_closed {
            // The folder may have been changed there.
            self.gallery_folder();
            self.rescan_gallery(ctx);
        }
        if self.settings_open
            && let Some(loader) = &self.gallery.loader
        {
            loader.want(Vec::new());
        }
        if let Some(scan) = &self.gallery.scan {
            match scan.try_recv() {
                Ok(shots) => {
                    self.gallery.scan = None;
                    self.gallery.shots = shots;
                    self.gallery.scanned = true;
                    self.gallery.refilter();
                    let paths: HashSet<&Path> = self
                        .gallery
                        .shots
                        .iter()
                        .map(|s| s.path.as_path())
                        .collect();
                    self.gallery
                        .thumbs
                        .retain(|p, _| paths.contains(p.as_path()));
                    if std::mem::take(&mut self.gallery.rescan) {
                        self.rescan_gallery(ctx);
                    }
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => {}
                Err(std::sync::mpsc::TryRecvError::Disconnected) => self.gallery.scan = None,
            }
        }
        let trashed: Vec<_> = self.gallery.trashed.1.try_iter().collect();
        for (path, result) in trashed {
            let name = path.file_name().unwrap_or_default().to_string_lossy();
            let text = match result {
                Ok(()) => format!("Moved {name} to the {RECYCLE_BIN}"),
                Err(e) => format!("Couldn't move {name} to the {RECYCLE_BIN}: {e}"),
            };
            self.show_toast(text, ctx);
            self.rescan_gallery(ctx);
        }
        if let Some(loader) = &self.gallery.loader {
            for (path, image) in loader.take_done() {
                let texture = image.map(|image| {
                    ctx.load_texture("gallery thumb", image, egui::TextureOptions::LINEAR)
                });
                let seen = self.gallery.frame;
                self.gallery
                    .thumbs
                    .insert(path, Thumbnail { texture, seen });
            }
        }
    }

    /// Points the view at the screenshot folder, emptying it if that is
    /// another one than before.
    fn gallery_folder(&mut self) {
        let dir = self.screenshot_dir();
        if dir != self.gallery.dir {
            self.gallery.dir = dir;
            self.gallery.shots.clear();
            self.gallery.thumbs.clear();
            self.gallery.filter = None;
            self.gallery.refilter();
            self.gallery.scanned = false;
            // What a scan of the folder before finds is out of date.
            self.gallery.scan = None;
            self.gallery.rescan = false;
        }
    }

    /// Looks through the screenshot folder again, in the background, if
    /// the view shows.
    pub(crate) fn rescan_gallery(&mut self, ctx: &egui::Context) {
        let gallery = &mut self.gallery;
        if !gallery.open {
            return;
        }
        if gallery.scan.is_some() {
            gallery.rescan = true;
            return;
        }
        let Some(dir) = gallery.dir.clone() else {
            return;
        };
        let (sender, receiver) = channel();
        gallery.scan = Some(receiver);
        let ctx = ctx.clone();
        std::thread::spawn(move || {
            if sender.send(scan(&dir)).is_ok() {
                ctx.request_repaint();
            }
        });
    }

    /// The switch between the file list and the Screenshots view.
    pub(crate) fn view_toggle(&mut self, ui: &mut egui::Ui) {
        let mut view = self.settings.view;
        let options = [
            (
                View::Files,
                "Convert",
                "Convert images and see what was made",
            ),
            (
                View::Screenshots,
                "Screenshots",
                "The HDR screenshots hdrshot took",
            ),
        ];
        if theme::segmented(ui, &mut view, &options) {
            self.settings.view = view;
            self.viewer = None;
        }
    }

    pub(crate) fn view_toggle_width(&self, ui: &egui::Ui) -> f32 {
        theme::segmented_width(ui, ["Convert", "Screenshots"])
    }

    /// Shows the large preview of the screenshot at `index` in the grid.
    pub(crate) fn open_gallery_viewer(&mut self, index: usize, ctx: &egui::Context) {
        let Some(shot) = self.gallery.shot(index) else {
            return;
        };
        let path = shot.path.clone();
        let placeholder = self
            .gallery
            .thumbs
            .get(&path)
            .and_then(|t| t.texture.clone());
        self.show_viewer(Source::Gallery, path, placeholder, ctx);
    }

    /// The Screenshots view under the header.
    pub(crate) fn gallery_ui(&mut self, ui: &mut egui::Ui) {
        self.gallery.frame += 1;
        let Some(dir) = self.gallery.dir.clone() else {
            self.no_folder_ui(ui);
            return;
        };
        if self.gallery.shots.is_empty() {
            if self.gallery.scanned {
                self.no_screenshots_ui(ui);
            } else {
                ui.add_space(24.0);
                ui.vertical_centered(|ui| {
                    ui.spinner();
                    ui.weak("Looking for screenshots…");
                });
            }
            return;
        }
        self.gallery_toolbar(ui, &dir);
        ui.add_space(6.0);
        self.grid(ui);
    }

    /// The game filter, and a button that opens the folder.
    fn gallery_toolbar(&mut self, ui: &mut egui::Ui, dir: &Path) {
        ui.horizontal(|ui| {
            let gallery = &mut self.gallery;
            let total = gallery.shots.len();
            if gallery.games.len() > 1 {
                let all = format!("All games ({total})");
                let selected = match &gallery.filter {
                    Some(game) => {
                        let n = gallery
                            .games
                            .iter()
                            .find(|(g, _)| g == game)
                            .map_or(0, |(_, n)| *n);
                        format!("{game} ({n})")
                    }
                    None => all.clone(),
                };
                let before = gallery.filter.clone();
                let width = (ui.available_width() - 40.0).clamp(120.0, 260.0);
                egui::ComboBox::from_id_salt("gallery game")
                    .selected_text(selected)
                    .width(width)
                    .truncate()
                    .show_ui(ui, |ui| {
                        ui.selectable_value(&mut gallery.filter, None, all);
                        for (game, n) in &gallery.games {
                            ui.selectable_value(
                                &mut gallery.filter,
                                Some(game.clone()),
                                format!("{game} ({n})"),
                            );
                        }
                    });
                if gallery.filter != before {
                    gallery.refilter();
                }
            } else {
                let count = if total == 1 {
                    "1 screenshot".to_owned()
                } else {
                    format!("{total} screenshots")
                };
                ui.label(RichText::new(count).weak());
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if theme::small_icon_button(ui, icons::folder)
                    .on_hover_text(format!("Open {}", dir.display()))
                    .clicked()
                {
                    reveal(dir);
                }
                if self.gallery.scan.is_some() {
                    ui.add(egui::Spinner::new().size(14.0));
                }
            });
        });
    }

    /// The tiles, by day, laid out and drawn only where in sight.
    fn grid(&mut self, ui: &mut egui::Ui) {
        let options = self.shot_options();
        let ctx = ui.ctx().clone();
        let mut action = None;
        let mut seen = Vec::new();
        let mut wanted = Vec::new();
        let mut later = Vec::new();
        let gallery = &self.gallery;
        egui::ScrollArea::vertical()
            .id_salt("gallery")
            .auto_shrink([false, false])
            .show_viewport(ui, |ui, viewport| {
                let width = ui.available_width();
                let columns = (((width + GAP) / (MIN_TILE_WIDTH + GAP)).floor() as usize).max(1);
                let tile_width = ((width - GAP * (columns - 1) as f32) / columns as f32).floor();
                let thumb_height = (tile_width * 9.0 / 16.0).round();
                let tile_height = thumb_height + CAPTION_HEIGHT;
                let lines = lines(gallery, columns);
                let height = |line: &Line| match line {
                    Line::Heading(_) => HEADING_HEIGHT,
                    Line::Tiles(_) => tile_height + GAP,
                };
                let total: f32 = lines.iter().map(height).sum();
                ui.set_height(total);
                let origin = ui.max_rect().min;
                // Thumbnails just below are decoded too, after those in sight.
                let ahead = viewport.expand2(Vec2::new(0.0, viewport.height() * 0.75));
                let mut y = 0.0;
                for line in &lines {
                    let top = y;
                    y += height(line);
                    if y < ahead.top() || top > ahead.bottom() {
                        continue;
                    }
                    let in_sight = y >= viewport.top() && top <= viewport.bottom();
                    match line {
                        Line::Heading(day) if in_sight => {
                            let text = day.map_or_else(|| "Other".to_owned(), day_heading);
                            ui.painter().text(
                                origin + Vec2::new(2.0, top + HEADING_HEIGHT - 9.0),
                                egui::Align2::LEFT_BOTTOM,
                                text,
                                theme::semibold(13.5),
                                ui.visuals().text_color(),
                            );
                        }
                        Line::Heading(_) => {}
                        Line::Tiles(places) => {
                            for (column, place) in places.clone().enumerate() {
                                let Some(shot) = gallery.shot(place) else {
                                    continue;
                                };
                                let thumb = gallery.thumbs.get(&shot.path);
                                if thumb.is_none() {
                                    if in_sight { &mut wanted } else { &mut later }
                                        .push(shot.path.clone());
                                }
                                if !in_sight {
                                    continue;
                                }
                                seen.push(shot.path.clone());
                                let x = column as f32 * (tile_width + GAP);
                                let rect = egui::Rect::from_min_size(
                                    origin + Vec2::new(x, top),
                                    Vec2::new(tile_width, tile_height),
                                );
                                let texture = thumb.map(|t| t.texture.as_ref());
                                if let Some(done) =
                                    tile(ui, rect, thumb_height, shot, place, texture, &options)
                                {
                                    action = Some(done);
                                }
                            }
                        }
                    }
                }
            });
        let frame = self.gallery.frame;
        for path in &seen {
            if let Some(thumb) = self.gallery.thumbs.get_mut(path) {
                thumb.seen = frame;
            }
        }
        let keep = CACHE.max(2 * (seen.len() + later.len()));
        if self.gallery.thumbs.len() > keep {
            let mut ages: Vec<(u64, PathBuf)> = self
                .gallery
                .thumbs
                .iter()
                .map(|(p, t)| (t.seen, p.clone()))
                .collect();
            ages.sort_unstable();
            for (_, path) in ages.into_iter().take(self.gallery.thumbs.len() - keep) {
                self.gallery.thumbs.remove(&path);
            }
        }
        wanted.extend(later);
        if let Some(loader) = &self.gallery.loader {
            loader.want(wanted);
        }
        match action {
            None => {}
            Some(ShotAction::View(place)) => self.open_gallery_viewer(place, &ctx),
            Some(ShotAction::Copy(path)) => self.copy_shot(path, &ctx),
            Some(ShotAction::Open(path)) => open(&path),
            Some(ShotAction::ShowInFolder(path)) => show_in_folder(&path),
            Some(ShotAction::Convert(path)) => self.convert_shot(path, &ctx),
            Some(ShotAction::Trash(path)) => self.trash_shot(path, &ctx),
        }
    }

    /// Copies a screenshot for Discord, in the background: its converted
    /// image if there is one, else a PNG made from it now.
    fn copy_shot(&mut self, path: PathBuf, ctx: &egui::Context) {
        let options = self.shot_options();
        let outputs = converted(&path, &options);
        let clipboard = self.clipboard.clone();
        let made = outputs.hdr.is_some() || outputs.sdr.is_some();
        if !made || convert::copy_makes_png(&outputs) {
            self.show_toast("Making the PNG for Discord…".into(), ctx);
        }
        convert::in_background(self.copied.0.clone(), ctx.clone(), move || {
            if made {
                convert::copy(&clipboard, &path, &outputs, &options)
            } else {
                convert::copy_original(&clipboard, &path, &options)
            }
        });
    }

    /// Adds a screenshot to the file list, shows the list and converts it,
    /// unless a batch is running, when it waits in the list.
    fn convert_shot(&mut self, path: PathBuf, ctx: &egui::Context) {
        self.add_paths([path.clone()]);
        self.settings.view = View::Files;
        if let Some(row) = self.files.iter().position(|e| e.path == path) {
            self.selection.set(row);
            if self.can_convert() {
                self.start_some(vec![row], ctx);
            }
        }
    }

    /// Moves a screenshot to the Recycle Bin, in the background, as that
    /// can take a moment. It leaves the grid at once.
    fn trash_shot(&mut self, path: PathBuf, ctx: &egui::Context) {
        let gallery = &mut self.gallery;
        gallery.shots.retain(|s| s.path != path);
        gallery.thumbs.remove(&path);
        gallery.refilter();
        let sender = gallery.trashed.0.clone();
        let ctx = ctx.clone();
        std::thread::spawn(move || {
            let result = ::trash::delete(&path).map_err(|e| e.to_string());
            let _ = sender.send((path, result));
            ctx.request_repaint();
        });
    }

    /// Without a folder for screenshots (there's no Pictures folder).
    fn no_folder_ui(&mut self, ui: &mut egui::Ui) {
        empty_message(
            ui,
            "No folder for screenshots",
            "Choose where to save them in Settings.",
        );
        ui.vertical_centered(|ui| {
            if ui.button("Open Settings").clicked() {
                self.settings_open = true;
            }
        });
    }

    /// Before the first screenshot: how to take one.
    fn no_screenshots_ui(&mut self, ui: &mut egui::Ui) {
        let how = match self.shortcut_name() {
            Some(keys) => format!("Press {keys} in a game to take an HDR screenshot."),
            None => "Set a shortcut in Settings to take HDR screenshots in games.".to_owned(),
        };
        empty_message(ui, "No screenshots yet", &how);
        ui.vertical_centered(|ui| {
            if theme::icon_text_button(ui, icons::camera, "Take one now")
                .on_hover_text("Take an HDR screenshot of what's behind this window")
                .clicked()
            {
                let ctx = ui.ctx().clone();
                self.screenshot_from_window(&ctx);
            }
        });
    }
}

/// The lines of the grid: a heading for each day, then its screenshots in
/// rows of `columns`.
fn lines(gallery: &Gallery, columns: usize) -> Vec<Line> {
    let mut lines = Vec::new();
    let day = |place: usize| gallery.shot(place).and_then(|s| s.taken).map(Stamp::date);
    let mut start = 0;
    while start < gallery.len() {
        let today = day(start);
        let mut end = start + 1;
        while end < gallery.len() && day(end) == today {
            end += 1;
        }
        lines.push(Line::Heading(today));
        let mut row = start;
        while row < end {
            let next = (row + columns).min(end);
            lines.push(Line::Tiles(row..next));
            row = next;
        }
        start = end;
    }
    lines
}

/// A large icon with a title and a line under it, centered, for an empty
/// view.
fn empty_message(ui: &mut egui::Ui, title: &str, text: &str) {
    ui.vertical_centered(|ui| {
        ui.add_space((ui.available_height() * 0.22).clamp(12.0, 120.0));
        let (rect, _) = ui.allocate_exact_size(Vec2::splat(44.0), Sense::hover());
        icons::camera(ui.painter(), rect, ui.visuals().weak_text_color());
        ui.add_space(10.0);
        ui.label(RichText::new(title).font(theme::semibold(16.0)));
        ui.add_space(2.0);
        ui.label(RichText::new(text).weak());
        ui.add_space(12.0);
    });
}

/// One screenshot's tile: its thumbnail (`None` while loading, `Some(None)`
/// if it couldn't be read), the game and the time, with buttons over the
/// thumbnail while pointed at and a right-click menu.
fn tile(
    ui: &mut egui::Ui,
    rect: egui::Rect,
    thumb_height: f32,
    shot: &Shot,
    place: usize,
    texture: Option<Option<&egui::TextureHandle>>,
    options: &ConvertOptions,
) -> Option<ShotAction> {
    let mut action = None;
    let response = ui
        .interact(
            rect,
            ui.scope_id().with(("shot", &shot.path)),
            Sense::click(),
        )
        .on_hover_cursor(egui::CursorIcon::PointingHand);
    let pointed = ui.rect_contains_pointer(rect);
    let visuals = ui.visuals().clone();
    let fill = if pointed || response.context_menu_opened() {
        visuals.widgets.inactive.weak_bg_fill
    } else {
        visuals.faint_bg_color
    };
    let painter = ui.painter();
    painter.rect_filled(rect, RADIUS, fill);
    let thumb_rect = egui::Rect::from_min_size(rect.min, Vec2::new(rect.width(), thumb_height));
    let top = egui::CornerRadius {
        nw: RADIUS,
        ne: RADIUS,
        sw: 0,
        se: 0,
    };
    match texture {
        Some(Some(texture)) => {
            let [w, h] = texture.size();
            let uv = cover_uv(w as f32 / h.max(1) as f32, rect.width() / thumb_height);
            egui::Image::new((texture.id(), thumb_rect.size()))
                .uv(uv)
                .corner_radius(top)
                .paint_at(ui, thumb_rect);
        }
        Some(None) => {
            painter.rect_filled(thumb_rect, top, visuals.widgets.inactive.bg_fill);
            let icon = egui::Rect::from_center_size(thumb_rect.center(), Vec2::splat(22.0));
            icons::image(painter, icon, visuals.weak_text_color());
        }
        None => {
            painter.rect_filled(thumb_rect, top, visuals.widgets.inactive.bg_fill);
        }
    }

    // The game on the left, the time on the right.
    let caption = egui::Rect::from_min_max(
        egui::pos2(rect.left() + 8.0, thumb_rect.bottom()),
        egui::pos2(rect.right() - 8.0, rect.bottom()),
    );
    let time = shot
        .taken
        .map(|t| format!("{:02}:{:02}", t.hour, t.minute))
        .unwrap_or_default();
    let painter = ui.painter();
    let time = painter.layout_no_wrap(
        time,
        egui::FontId::proportional(12.0),
        visuals.weak_text_color(),
    );
    let mut job = egui::text::LayoutJob::simple_singleline(
        shot.game.clone(),
        egui::FontId::proportional(13.0),
        visuals.text_color(),
    );
    job.wrap = egui::text::TextWrapping::truncate_at_width(
        (caption.width() - time.size().x - 8.0).max(10.0),
    );
    let game = painter.layout_job(job);
    painter.galley(
        egui::pos2(caption.left(), caption.center().y - game.size().y / 2.0),
        game,
        visuals.text_color(),
    );
    painter.galley(
        egui::pos2(
            caption.right() - time.size().x,
            caption.center().y - time.size().y / 2.0,
        ),
        time,
        visuals.weak_text_color(),
    );

    if response.clicked() {
        action = Some(ShotAction::View(place));
    }
    if pointed {
        let outputs = converted(&shot.path, options);
        let size = 26.0;
        let mut right = thumb_rect.right() - 6.0;
        let mut button = |icon: icons::Icon, hint: String| {
            let at = egui::Rect::from_min_size(
                egui::pos2(right - size, thumb_rect.top() + 6.0),
                Vec2::splat(size),
            );
            right -= size + 4.0;
            tile_button(ui, at, icon, &hint).clicked()
        };
        if button(icons::trash, format!("Move to the {RECYCLE_BIN}")) {
            action = Some(ShotAction::Trash(shot.path.clone()));
        }
        if button(icons::folder, "Show in folder".to_owned()) {
            action = Some(ShotAction::ShowInFolder(shot.path.clone()));
        }
        if let Some(made) = outputs.hdr.as_ref().or(outputs.sdr.as_ref())
            && button(
                icons::open,
                format!(
                    "Open {}",
                    made.file_name().unwrap_or_default().to_string_lossy()
                ),
            )
        {
            action = Some(ShotAction::Open(made.clone()));
        }
        let at = egui::pos2(thumb_rect.left() + 6.0, thumb_rect.bottom() - 6.0);
        if copy_pill(ui, at).clicked() {
            action = Some(ShotAction::Copy(shot.path.clone()));
        }
    }
    response.context_menu(|ui| {
        if let Some(menu) = shot_menu(ui, shot, place, options) {
            action = Some(menu);
            ui.close();
        }
    });
    action
}

/// The right-click menu of a screenshot's tile.
fn shot_menu(
    ui: &mut egui::Ui,
    shot: &Shot,
    place: usize,
    options: &ConvertOptions,
) -> Option<ShotAction> {
    let mut action = None;
    let outputs = converted(&shot.path, options);
    if ui
        .button("Copy for Discord")
        .on_hover_text(COPY_HINT)
        .clicked()
    {
        action = Some(ShotAction::Copy(shot.path.clone()));
    }
    if ui
        .add_enabled(outputs.hdr.is_some(), egui::Button::new("Open HDR image"))
        .clicked()
    {
        action = outputs.hdr.clone().map(ShotAction::Open);
    }
    if ui
        .add_enabled(outputs.sdr.is_some(), egui::Button::new("Open SDR image"))
        .clicked()
    {
        action = outputs.sdr.clone().map(ShotAction::Open);
    }
    if ui.button("Preview").clicked() {
        action = Some(ShotAction::View(place));
    }
    ui.separator();
    if ui.button("Show in folder").clicked() {
        action = Some(ShotAction::ShowInFolder(shot.path.clone()));
    }
    if ui
        .button("Convert")
        .on_hover_text("Add it to the file list and convert it")
        .clicked()
    {
        action = Some(ShotAction::Convert(shot.path.clone()));
    }
    if ui
        .button(format!("Move to the {RECYCLE_BIN}"))
        .on_hover_text("Only the screenshot, not the images made from it")
        .clicked()
    {
        action = Some(ShotAction::Trash(shot.path.clone()));
    }
    action
}

/// Tooltip for a screenshot's Copy for Discord.
const COPY_HINT: &str = "Copy the image (the HDR one if made) as a PNG that Discord shows \
     correctly. If the screenshot isn't converted yet, the PNG is made from it. Your saved \
     files are unchanged.";

/// A round dark button over a thumbnail, readable on any picture.
fn tile_button(
    ui: &mut egui::Ui,
    rect: egui::Rect,
    icon: icons::Icon,
    hint: &str,
) -> egui::Response {
    let response = ui
        .interact(
            rect,
            ui.scope_id()
                .with(("tile button", rect.min.x as i32, rect.min.y as i32)),
            Sense::click(),
        )
        .on_hover_text(hint)
        .on_hover_cursor(egui::CursorIcon::PointingHand);
    let alpha = if response.hovered() { 215 } else { 150 };
    let painter = ui.painter();
    painter.circle_filled(
        rect.center(),
        rect.width() / 2.0,
        Color32::from_black_alpha(alpha),
    );
    icon(painter, rect.shrink(rect.width() * 0.28), Color32::WHITE);
    response
}

/// "Copy for Discord" as a dark pill over a thumbnail, its bottom left
/// corner at `at`.
fn copy_pill(ui: &mut egui::Ui, at: egui::Pos2) -> egui::Response {
    let galley = ui.painter().layout_no_wrap(
        "Copy for Discord".to_owned(),
        egui::FontId::proportional(12.0),
        Color32::WHITE,
    );
    let size = galley.size() + Vec2::new(18.0, 9.0);
    let rect = egui::Rect::from_min_size(at - Vec2::new(0.0, size.y), size);
    let response = ui
        .interact(
            rect,
            ui.scope_id()
                .with(("copy pill", rect.min.x as i32, rect.min.y as i32)),
            Sense::click(),
        )
        .on_hover_text(COPY_HINT)
        .on_hover_cursor(egui::CursorIcon::PointingHand);
    let alpha = if response.hovered() { 215 } else { 150 };
    let painter = ui.painter();
    painter.rect_filled(rect, size.y / 2.0, Color32::from_black_alpha(alpha));
    painter.galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE);
    response
}

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

    fn stamp(time: [u16; 6]) -> Stamp {
        let [year, month, day, hour, minute, second] = time;
        Stamp {
            year,
            month: month as u8,
            day: day as u8,
            hour: hour as u8,
            minute: minute as u8,
            second: second as u8,
        }
    }

    #[test]
    fn reads_screenshot_names() {
        let time = [2026, 11, 28, 9, 5, 2];
        let stem = screenshot::file_stem("Some Game", time);
        assert_eq!(
            parse_stem(&stem),
            Name {
                game: "Some Game",
                taken: Some(stamp(time)),
                number: 1
            }
        );
        assert_eq!(
            parse_stem("Some Game 2026-11-28 09-05-02 (3)"),
            Name {
                game: "Some Game",
                taken: Some(stamp(time)),
                number: 3
            }
        );
        // A game whose name ends in brackets.
        assert_eq!(parse_stem("Game (2) 2026-11-28 09-05-02").game, "Game (2)");
        assert_eq!(parse_stem("2026-11-28 09-05-02").game, "");
        for other in [
            "holiday",
            "Game 2026-13-28 09-05-02",
            "Game 2026-11-28 09:05:02",
            "Game2026-11-28 09-05-02",
            "Game 2026-11-28 09-05-02 (x)",
            // No year 0, which has no weekday to head its day with.
            "Game 0000-01-15 09-05-02",
            "",
        ] {
            assert_eq!(
                parse_stem(other),
                Name {
                    game: other,
                    taken: None,
                    number: 1
                }
            );
        }
        // Not cut inside a character.
        assert_eq!(parse_stem("ééééééééééééé").taken, None);
    }

    #[test]
    fn games_come_from_folders_or_names() {
        let time = Some(stamp([2026, 11, 28, 9, 5, 2]));
        let flat = Path::new("Some Game 2026-11-28 09-05-02.jxr");
        assert_eq!(describe(flat), ("Some Game".into(), time, 1));
        let nested = Path::new("Some Game").join("Some Game 2026-11-28 09-05-02 (2).jxr");
        assert_eq!(describe(&nested), ("Some Game".into(), time, 2));
        // The folder wins, even over another name.
        let moved = Path::new("Other Game").join("Some Game 2026-11-28 09-05-02.jxr");
        assert_eq!(describe(&moved).0, "Other Game");
        let renamed = Path::new("Elden Ring").join("boss.jxr");
        assert_eq!(describe(&renamed), ("Elden Ring".into(), None, 1));
        assert_eq!(describe(Path::new("boss.jxr")).0, "Other");
        assert_eq!(
            describe(Path::new("2026-11-28 09-05-02.jxr")).0,
            "Screenshot"
        );
    }

    #[test]
    fn days_have_headings() {
        assert_eq!(day_heading((2026, 11, 28)), "Saturday, 28 November 2026");
        assert_eq!(day_heading((2024, 2, 29)), "Thursday, 29 February 2024");
        assert_eq!(day_heading((2000, 1, 1)), "Saturday, 1 January 2000");
        // Never underflows, even for a year 0 that names don't give.
        let _ = day_heading((0, 1, 1));
    }

    #[test]
    fn newest_screenshots_come_first() {
        let shot = |name: &str, modified: u64| {
            let path = PathBuf::from(name);
            let (game, taken, number) = describe(&path);
            Shot {
                path,
                game,
                taken,
                number,
                modified: Some(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(modified)),
            }
        };
        let mut shots = [
            shot("old.jxr", 1),
            shot("B 2026-11-27 23-59-59.jxr", 0),
            shot("A 2026-11-28 09-05-02.jxr", 0),
            shot("A 2026-11-28 09-05-02 (2).jxr", 0),
            shot("new.jxr", 2),
            shot("A 2026-11-28 09-05-02 (10).jxr", 0),
        ];
        shots.sort_by(newest_first);
        let names: Vec<_> = shots.iter().map(|s| s.path.to_str().unwrap()).collect();
        assert_eq!(
            names,
            [
                "A 2026-11-28 09-05-02 (10).jxr",
                "A 2026-11-28 09-05-02 (2).jxr",
                "A 2026-11-28 09-05-02.jxr",
                "B 2026-11-27 23-59-59.jxr",
                "new.jxr",
                "old.jxr",
            ]
        );
    }

    #[test]
    fn scans_folders_and_groups_by_day() {
        let dir = std::env::temp_dir().join(format!("hdrshot-gallery-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let game = dir.join("Some Game");
        std::fs::create_dir_all(game.join("hdr")).unwrap();
        for path in [
            dir.join("Old Game 2026-11-27 10-00-00.jxr"),
            game.join("Some Game 2026-11-28 09-05-02.jxr"),
            game.join("Some Game 2026-11-28 09-06-00.JXR"),
            // Converted images and unfinished screenshots are left out.
            game.join("Some Game 2026-11-28 09-05-02_sdr.png"),
            game.join("Some Game 2026-11-28 09-07-00.jxr.partial"),
            game.join("hdr")
                .join("Some Game 2026-11-28 09-05-02_hdr.png"),
        ] {
            std::fs::write(path, b"").unwrap();
        }
        let mut gallery = Gallery {
            shots: scan(&dir),
            ..Default::default()
        };
        gallery.refilter();
        let names: Vec<_> = gallery
            .shots
            .iter()
            .map(|s| s.path.file_name().unwrap().to_str().unwrap())
            .collect();
        assert_eq!(
            names,
            [
                "Some Game 2026-11-28 09-06-00.JXR",
                "Some Game 2026-11-28 09-05-02.jxr",
                "Old Game 2026-11-27 10-00-00.jxr",
            ]
        );
        assert_eq!(
            gallery.games,
            [("Old Game".to_owned(), 1), ("Some Game".to_owned(), 2)]
        );
        let lines = lines(&gallery, 1);
        assert!(matches!(lines[0], Line::Heading(Some((2026, 11, 28)))));
        assert!(matches!(&lines[1], Line::Tiles(r) if *r == (0..1)));
        assert!(matches!(&lines[2], Line::Tiles(r) if *r == (1..2)));
        assert!(matches!(lines[3], Line::Heading(Some((2026, 11, 27)))));
        assert_eq!(lines.len(), 5);

        gallery.filter = Some("Some Game".into());
        gallery.refilter();
        assert_eq!(gallery.len(), 2);
        assert_eq!(
            gallery.position(&dir.join("Old Game 2026-11-27 10-00-00.jxr")),
            None
        );
        // A filter for a game no longer there is dropped.
        gallery.shots.clear();
        gallery.refilter();
        assert_eq!(gallery.filter, None);
        let _ = std::fs::remove_dir_all(&dir);
    }
}