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
//! The settings: chips under the file list that sum them up, each with a
//! menu for its choices, and the Settings page holding all of them.

use super::*;

/// How many folders saved into before the save menu offers.
const RECENT_DIRS: usize = 3;

/// Height limits offered for the output, `None` keeping the source size.
const HEIGHTS: [Option<u32>; 5] = [None, Some(2160), Some(1440), Some(1080), Some(720)];

impl App {
    /// The row of chips under the file list.
    pub(crate) fn summary_chips(&mut self, ui: &mut egui::Ui) {
        ui.horizontal_wrapped(|ui| {
            ui.spacing_mut().item_spacing = Vec2::new(5.0, 6.0);
            let output = self.settings.output_summary();
            chip_menu(ui, "output", &output, false, "What to create", |ui| {
                settings_grid(ui, "output menu", |ui| self.output_rows(ui));
            });
            let save = self.settings.save_summary();
            let no_folder = self.settings.save_to_folder && self.settings.output_dir.is_none();
            chip_menu(ui, "save", &save, no_folder, "Where to save", |ui| {
                if self.save_menu(ui) {
                    ui.close();
                }
            });
            let size = size_summary(self.max_height);
            chip_menu(ui, "size", &size, false, "Largest output size", |ui| {
                ui.set_max_width(260.0);
                let labels: Vec<_> = HEIGHTS
                    .iter()
                    .map(|&h| (h, self.resolution_label(h)))
                    .collect();
                for (h, label) in labels {
                    if ui
                        .selectable_value(&mut self.max_height, h, label)
                        .clicked()
                    {
                        ui.close();
                    }
                }
                ui.label(
                    RichText::new("Keeps the aspect ratio. Smaller images are never scaled up.")
                        .weak()
                        .size(12.0),
                );
            });
            let after = self.settings.after_summary();
            chip_menu(
                ui,
                "after",
                &after,
                false,
                "What happens after converting",
                |ui| {
                    settings_grid(ui, "after menu", |ui| self.after_rows(ui));
                },
            );
            if !self.tuning.is_default()
                && theme::chip(ui, "Custom tuning", false, true)
                    .on_hover_text(
                        "Fine-tuning is changed for this session. Click to see it in \
                         Settings.",
                    )
                    .clicked()
            {
                self.settings_open = true;
            }
        });
    }

    /// The Settings page, in place of the file list.
    pub(crate) fn settings_page(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            if theme::icon_button(ui, icons::back)
                .on_hover_text("Back to the files (Esc)")
                .clicked()
            {
                self.settings_open = false;
            }
            ui.add_space(2.0);
            ui.label(RichText::new("Settings").font(theme::semibold(18.0)));
        });
        ui.add_space(4.0);
        egui::ScrollArea::vertical()
            .auto_shrink([false, false])
            .show(ui, |ui| {
                if self.running() {
                    ui.weak("Settings can be changed once the images are converted.");
                }
                theme::section(ui, "General");
                theme::card(ui, |ui| {
                    settings_grid(ui, "general", |ui| self.general_rows(ui));
                });
                ui.add_enabled_ui(!self.running(), |ui| {
                    theme::section(ui, "Output");
                    theme::card(ui, |ui| {
                        settings_grid(ui, "output", |ui| {
                            self.output_rows(ui);
                            self.resolution_row(ui);
                        });
                    });
                    theme::section(ui, "Saving");
                    theme::card(ui, |ui| self.saving_ui(ui));
                    theme::section(ui, "After converting");
                    theme::card(ui, |ui| {
                        settings_grid(ui, "after", |ui| self.after_rows(ui))
                    });
                    if screenshot::SUPPORTED {
                        theme::section(ui, "Screenshots");
                        theme::card(ui, |ui| self.screenshot_ui(ui));
                    }
                    theme::section(ui, "Watch folder");
                    theme::card(ui, |ui| self.watch_ui(ui));
                    if tray::SUPPORTED {
                        theme::section(ui, "Background");
                        theme::card(ui, |ui| {
                            settings_grid(ui, "background", |ui| self.background_rows(ui))
                        });
                    }
                    theme::section(ui, "Fine-tuning");
                    theme::card(ui, |ui| self.tuning_ui(ui));
                });
            });
    }

    /// The theme, the weekly update check and the default app: rows of a
    /// two-column grid.
    fn general_rows(&mut self, ui: &mut egui::Ui) {
        theme::row_label(ui, "Theme");
        if theme::segmented(
            ui,
            &mut self.settings.theme,
            &[
                (
                    ThemeChoice::System,
                    "System",
                    "Light or dark, as the system is set",
                ),
                (ThemeChoice::Light, "Light", "Always light"),
                (ThemeChoice::Dark, "Dark", "Always dark"),
            ],
        ) {
            self.settings.theme.apply(ui.ctx());
        }
        ui.end_row();

        theme::row_label(ui, "Updates");
        ui.checkbox(
            &mut self.settings.update_check,
            "Check for updates once a week",
        )
        .on_hover_text(
            "When hdrshot starts, ask GitHub for its latest release at most once \
             a week. If there is a newer one, the link at the bottom of the window \
             offers it; nothing is downloaded until you choose Update.",
        );
        ui.end_row();

        if assoc::SUPPORTED {
            theme::row_label(ui, "Files");
            self.default_app_ui(ui);
            ui.end_row();
        }

        theme::row_label(ui, "Feedback");
        ui.horizontal(|ui| {
            ui.hyperlink_to("Report a problem", report_url())
                .on_hover_text("Opens a bug report on GitHub, with this version filled in");
            ui.add_space(12.0);
            ui.hyperlink_to("Ask a question", DISCUSSIONS_URL)
                .on_hover_text("Opens hdrshot's Discussions on GitHub");
        });
        ui.end_row();
    }

    /// What to create, in which formats: rows of a two-column grid.
    pub(crate) fn output_rows(&mut self, ui: &mut egui::Ui) {
        theme::row_label(ui, "Create");
        theme::segmented(
            ui,
            &mut self.settings.mode,
            &[
                (
                    Mode::Both,
                    "HDR + SDR",
                    "An HDR image and a tone-mapped SDR image for each image",
                ),
                (
                    Mode::Hdr,
                    "HDR only",
                    "Only the HDR image, in the format chosen below",
                ),
                (
                    Mode::Sdr,
                    "SDR only",
                    "Tone-mapped 8-bit image that looks right everywhere",
                ),
            ],
        );
        ui.end_row();

        theme::row_label(ui, "HDR format");
        ui.add_enabled_ui(self.settings.mode != Mode::Sdr, |ui| {
            hdr_format_choice(ui, &mut self.settings.hdr_format);
        });
        ui.end_row();

        ui.label("");
        let png = self.settings.mode != Mode::Sdr && self.settings.hdr_format == Format::Png;
        ui.horizontal(|ui| {
            ui.add_enabled(
                png,
                egui::Checkbox::new(&mut self.settings.discord_png, "Discord-compatible PNG"),
            );
            // Explains the option even while it doesn't apply.
            theme::info_icon(
                ui,
                "Saves HDR PNGs without their cICP and mDCV chunks. Discord turns \
                 PNGs with cICP yellow; without it, Discord shows them in HDR with \
                 the right colors.\n\n\
                 Windows Photos and most other HDR viewers need cICP to show HDR, \
                 so they show these PNGs in SDR only. Leave this off unless you \
                 upload the saved files to Discord yourself: Copy for Discord \
                 already copies a Discord-compatible version.",
            );
        });
        ui.end_row();

        theme::row_label(ui, "SDR format");
        ui.add_enabled_ui(self.settings.mode != Mode::Hdr, |ui| {
            sdr_format_choice(ui, &mut self.settings.sdr_format);
        });
        ui.end_row();
    }

    /// The Resolution row of the Settings page's grid.
    pub(crate) fn resolution_row(&mut self, ui: &mut egui::Ui) {
        theme::row_label(ui, "Resolution");
        let selected = self.resolution_label(self.max_height);
        let labels: Vec<_> = HEIGHTS
            .iter()
            .map(|&h| (h, self.resolution_label(h)))
            .collect();
        egui::ComboBox::from_id_salt("resolution")
            .selected_text(selected)
            .show_ui(ui, |ui| {
                for (h, label) in labels {
                    ui.selectable_value(&mut self.max_height, h, label);
                }
            })
            .response
            .on_hover_text(RESOLUTION_HINT);
        ui.end_row();
    }

    /// A height limit's name, with the size the listed files come out at.
    pub(crate) fn resolution_label(&self, max_height: Option<u32>) -> String {
        let name = max_height.map_or_else(|| "Source".to_owned(), |h| format!("{h}p"));
        match output_size(&self.files, max_height) {
            OutputSize::Unknown => name,
            OutputSize::Same(w, h) => format!("{name} ({w}×{h})"),
            OutputSize::Varies => format!("{name} (sizes vary)"),
        }
    }

    /// The choices of where to save: next to each original, one of the
    /// folders chosen lately, or a new one. Returns whether one was made.
    pub(crate) fn save_menu(&mut self, ui: &mut egui::Ui) -> bool {
        let mut chosen = false;
        let folders = self.settings.save_folders();
        let s = &mut self.settings;
        if ui
            .selectable_label(!s.save_to_folder, "Next to each original")
            .on_hover_text("Save the new files in the folder of the image they come from")
            .clicked()
        {
            s.save_to_folder = false;
            chosen = true;
        }
        for dir in folders {
            let selected = s.save_to_folder && s.output_dir.as_ref() == Some(&dir);
            if ui
                .selectable_label(selected, folder_name(&dir))
                .on_hover_text(dir.display().to_string())
                .clicked()
            {
                s.use_output_dir(dir);
                chosen = true;
            }
        }
        ui.separator();
        if ui.button("Choose a folder…").clicked() {
            let mut dialog = rfd::FileDialog::new().set_title("Save images to");
            if let Some(dir) = &s.output_dir {
                dialog = dialog.set_directory(dir);
            }
            if let Some(dir) = dialog.pick_folder() {
                s.use_output_dir(dir);
            }
            chosen = true;
        }
        chosen
    }

    /// Where the images go and how they are named.
    pub(crate) fn saving_ui(&mut self, ui: &mut egui::Ui) {
        settings_grid(ui, "saving", |ui| {
            theme::row_label(ui, "Save to");
            let selected = match (&self.settings.output_dir, self.settings.save_to_folder) {
                (_, false) => "Next to each original".to_owned(),
                (Some(dir), true) => dir.display().to_string(),
                (None, true) => "Choose a folder…".to_owned(),
            };
            egui::ComboBox::from_id_salt("save to")
                .selected_text(selected)
                .width(ui.available_width().min(300.0))
                .truncate()
                .show_ui(ui, |ui| self.save_menu(ui));
            ui.end_row();
        });
        ui.add_space(4.0);
        ui.checkbox(&mut self.settings.keep_date, "Keep the capture date")
            .on_hover_text(
                "Give each PNG the date of its screenshot, so folders sorted \
                 by date stay in capture order",
            );
        let s = &mut self.settings;
        ui.checkbox(&mut s.subfolders, "Save HDR and SDR images in subfolders")
            .on_hover_text("Put them in folders named hdr and sdr");
        let needed = s.suffix_needed();
        let mut suffix = s.type_suffix || needed;
        ui.add_enabled_ui(!needed, |ui| {
            if ui
                .checkbox(&mut suffix, "End file names in _hdr and _sdr")
                .on_hover_text("Off: shot.jxr becomes shot.png")
                .on_disabled_hover_text(
                    "Needed to tell the two PNGs apart when both are saved in the \
                     same folder",
                )
                .changed()
            {
                s.type_suffix = suffix;
            }
        });
        self.name_preview_ui(ui);
    }

    /// The names of the files an image gets with the current settings,
    /// using the first listed image or a sample name.
    fn name_preview_ui(&self, ui: &mut egui::Ui) {
        let input = self
            .files
            .first()
            .map_or_else(|| PathBuf::from(SAMPLE_INPUT), |entry| entry.path.clone());
        let names = name_preview(&input, &self.convert_options(Existing::Skip));
        ui.add_space(6.0);
        // The page's color, set into the card.
        egui::Frame::new()
            .fill(ui.visuals().panel_fill)
            .corner_radius(6.0)
            .inner_margin(egui::Margin::symmetric(10, 8))
            .show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.spacing_mut().item_spacing.y = 3.0;
                let source = input.file_name().unwrap_or_default().to_string_lossy();
                ui.label(RichText::new(format!("{source} becomes")).size(12.0).weak());
                for name in names {
                    ui.add(egui::Label::new(RichText::new(name).size(13.0)).truncate());
                }
            });
    }

    /// The clipboard copy and the Recycle Bin: rows of a two-column grid.
    pub(crate) fn after_rows(&mut self, ui: &mut egui::Ui) {
        theme::row_label(ui, "Clipboard");
        ui.checkbox(
            &mut self.settings.copy_to_clipboard,
            "Copy the last converted image",
        )
        .on_hover_text(if screenshot::SUPPORTED {
            "After converting, copy the last image to the clipboard as a file \
                 (the HDR one if made), ready to paste into Discord, a browser or a \
                 folder. Screenshots follow Afterwards under Screenshots instead."
        } else {
            "After converting, copy the last image to the clipboard as a file \
                 (the HDR one if made), ready to paste into Discord, a browser or a folder"
        });
        ui.end_row();

        theme::row_label(ui, "Originals");
        ui.checkbox(
            &mut self.settings.trash_originals,
            format!("Replace the original (it goes to the {RECYCLE_BIN})"),
        )
        .on_hover_text(format!(
            "Once all of an image's files are saved, move the original to the \
             {RECYCLE_BIN}, so only the converted files are left. It can \
             be restored from there. Images that fail, or whose files already \
             existed, are kept, and so is everything when you stop the batch."
        ));
        ui.end_row();
    }

    pub(crate) fn tuning_ui(&mut self, ui: &mut egui::Ui) {
        ui.label(
            RichText::new(
                "Not needed normally: by default the results match the original \
                 image. Use these only to fine-tune the result. They reset when \
                 hdrshot closes.",
            )
            .weak(),
        );
        let t = &mut self.tuning;
        let mode = self.settings.mode;
        fn nits(value: &mut f32, min: f32) -> egui::DragValue<'_> {
            egui::DragValue::new(value)
                .range(min..=10_000.0)
                .speed(5.0)
                .suffix(" nits")
        }
        egui::Grid::new("tuning")
            .num_columns(2)
            .spacing([12.0, 8.0])
            .show(ui, |ui| {
                ui.add_enabled_ui(mode != Mode::Sdr, |ui| {
                    ui.checkbox(&mut t.limit_hdr_peak, "Limit HDR peak")
                        .on_hover_text(
                            "Roll off highlights brighter than this in the HDR image. \
                             Off keeps the original brightness.",
                        );
                });
                ui.add_enabled(
                    mode != Mode::Sdr && t.limit_hdr_peak,
                    nits(&mut t.hdr_peak, 100.0),
                );
                ui.end_row();

                ui.label("SDR white").on_hover_text(
                    "HDR brightness that becomes white in the SDR image. \
                     Lower makes the SDR picture brighter. At the default, 80, \
                     phone photos keep their own SDR white.",
                );
                ui.horizontal(|ui| {
                    ui.add(nits(&mut t.sdr_white, 10.0));
                    let default = SdrOptions::default().white_nits;
                    if t.sdr_white != default && ui.small_button("Reset").clicked() {
                        t.sdr_white = default;
                    }
                });
                ui.end_row();

                ui.checkbox(&mut t.fixed_sdr_peak, "Fixed SDR peak")
                    .on_hover_text(
                        "HDR brightness that maps to full SDR white. \
                     Off uses the brightest 0.1% of each image.",
                    );
                ui.add_enabled(t.fixed_sdr_peak, nits(&mut t.sdr_peak, 10.0));
                ui.end_row();

                ui.checkbox(&mut t.fixed_input_white, "Render white")
                    .on_hover_text(
                        "For OpenEXR, Radiance and float JPEG XL files: the \
                     brightness of a value of 1.0. Off uses the file's own value, or 80 nits. \
                     For phone photos: the brightness of SDR white. Off uses 203 nits.",
                    );
                ui.add_enabled(t.fixed_input_white, nits(&mut t.input_white, 1.0));
                ui.end_row();
            });
        if !t.is_default() && ui.button("Back to automatic").clicked() {
            *t = Tuning::default();
        }
    }
}

/// The HDR format choice of the output rows.
pub(crate) fn hdr_format_choice(ui: &mut egui::Ui, format: &mut Format) {
    theme::segmented(
        ui,
        format,
        &[
            (
                Format::Png,
                "PNG",
                "16-bit lossless PNG, shown in HDR by Windows Photos, Chrome \
                 and Edge. The largest files.",
            ),
            (
                Format::Avif,
                "AVIF",
                "10-bit AVIF, about a twentieth of the PNG's size, shown in HDR \
                 by Chrome, Edge and Firefox. Takes a few seconds per image.",
            ),
            (
                Format::UltraHdr,
                "Ultra HDR JPEG",
                "A JPEG that every app shows in SDR and that Chrome, Edge \
                 and Android show in HDR.",
            ),
        ],
    );
}

/// The SDR format choice of the output rows.
pub(crate) fn sdr_format_choice(ui: &mut egui::Ui, kind: &mut SdrKind) {
    theme::segmented(
        ui,
        kind,
        &[
            (
                SdrKind::Png,
                "PNG",
                "8-bit lossless PNG, the exact tone-mapped picture",
            ),
            (
                SdrKind::Jpeg,
                "JPEG",
                "JPEG at quality 90, a fraction of the PNG's size, for chats \
                 and forums that don't show HDR. Transparency is lost.",
            ),
        ],
    );
}

const RESOLUTION_HINT: &str = "Scale images taller than this down to this height, keeping the \
     aspect ratio, so ultrawide images stay ultrawide. Smaller images are never scaled up. \
     The size in brackets is what the listed files come out at.";

/// The image whose names the Settings page shows while the list is empty.
const SAMPLE_INPUT: &str = "Screenshot 2026-10-14 212314.jxr";

/// The files `input` becomes with `options`, as paths from the folder they
/// are saved in, e.g. `hdr/shot_hdr.png` with subfolders.
pub(crate) fn name_preview(input: &Path, options: &ConvertOptions) -> Vec<String> {
    let outputs = hdrshot_core::output_paths(input, options);
    let dir = options
        .output_dir
        .clone()
        .or_else(|| input.parent().map(Path::to_path_buf))
        .unwrap_or_default();
    [outputs.hdr, outputs.sdr]
        .into_iter()
        .flatten()
        .map(|path| {
            let path = path.strip_prefix(&dir).unwrap_or(&path);
            path.components()
                .map(|c| c.as_os_str().to_string_lossy())
                .collect::<Vec<_>>()
                .join("/")
        })
        .collect()
}

/// A two-column grid of labelled settings.
const DISCUSSIONS_URL: &str = "https://github.com/snaketech-tu/hdrshot/discussions";

/// A new bug report on GitHub, with the version, the desktop app and, where
/// it is clear, the operating system already filled in.
pub(crate) fn report_url() -> String {
    let os = match std::env::consts::OS {
        "macos" => "&os=macOS",
        "linux" => "&os=Linux",
        _ => "",
    };
    format!(
        "https://github.com/snaketech-tu/hdrshot/issues/new?template=bug.yml&version={}&surface=Desktop%20app{os}",
        env!("CARGO_PKG_VERSION")
    )
}

pub(crate) fn settings_grid(ui: &mut egui::Ui, id: &str, add_rows: impl FnOnce(&mut egui::Ui)) {
    egui::Grid::new(id)
        .num_columns(2)
        .spacing([16.0, 10.0])
        .show(ui, add_rows);
}

/// A chip that opens `menu` above itself when clicked. `hint` shows while
/// the menu is closed.
fn chip_menu(
    ui: &mut egui::Ui,
    id_salt: &str,
    label: &str,
    accented: bool,
    hint: &str,
    menu: impl FnOnce(&mut egui::Ui),
) {
    let popup_id = ui.scope_id().with(id_salt);
    let open = egui::Popup::is_id_open(ui.ctx(), popup_id);
    let mut response = theme::chip(ui, label, open, accented);
    if !open {
        response = response.on_hover_text(hint);
    }
    egui::Popup::from_toggle_button_response(&response)
        .id(popup_id)
        .align(egui::RectAlign::TOP_START)
        .gap(6.0)
        .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
        .show(|ui| {
            ui.set_min_width(220.0);
            menu(ui);
        });
}

/// What the size chip says.
pub(crate) fn size_summary(max_height: Option<u32>) -> String {
    max_height.map_or_else(|| "Source size".to_owned(), |h| format!("Up to {h}p"))
}

/// Reads a saved shortcut for an optional one.
fn some_shortcut<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<screenshot::Shortcut>, D::Error> {
    screenshot::Shortcut::deserialize(deserializer).map(Some)
}

/// Saves an optional shortcut as a plain one; only called with one.
fn plain_shortcut<S: serde::Serializer>(
    shortcut: &Option<screenshot::Shortcut>,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    shortcut
        .unwrap_or(screenshot::Shortcut::CtrlAltPrintScreen)
        .serialize(serializer)
}

/// What the user picked last time. Tuning options are deliberately not
/// remembered: every session starts out matching the original screenshots.
#[derive(Serialize, Deserialize)]
#[serde(default)]
pub(crate) struct Settings {
    pub(crate) mode: Mode,
    pub(crate) hdr_format: Format,
    pub(crate) sdr_format: SdrKind,
    pub(crate) save_to_folder: bool,
    pub(crate) output_dir: Option<PathBuf>,
    pub(crate) copy_to_clipboard: bool,
    pub(crate) keep_date: bool,
    /// Put HDR and SDR PNGs into `hdr` and `sdr` subfolders.
    pub(crate) subfolders: bool,
    /// End file names in `_hdr` or `_sdr`. Always on when both types share
    /// a folder.
    pub(crate) type_suffix: bool,
    /// Write HDR PNGs without `cICP`, so Discord shows them correctly.
    pub(crate) discord_png: bool,
    /// Move each original to the Recycle Bin once its outputs are written.
    pub(crate) trash_originals: bool,
    /// Convert new images saved to `watch_dir`.
    pub(crate) watch: bool,
    pub(crate) watch_dir: Option<PathBuf>,
    /// Folders saved into before, newest first, offered in the save menu.
    pub(crate) recent_dirs: Vec<PathBuf>,
    /// Tips of the empty window the user hid.
    pub(crate) hidden_tips: Vec<String>,
    pub(crate) theme: ThemeChoice,
    /// Look for a newer version once a week when hdrshot starts.
    pub(crate) update_check: bool,
    /// When a check for updates last succeeded, in seconds since 1970.
    pub(crate) last_update_check: u64,
    /// Where the window was when hdrshot last closed.
    pub(crate) window: Option<window::Place>,
    /// Keep running in the tray when the window is closed (Windows).
    pub(crate) tray: bool,
    /// Start in the tray when the user signs in.
    pub(crate) start_with_windows: bool,
    /// Say with a notification when images were converted while the
    /// window was hidden or in the background.
    pub(crate) notify: bool,
    /// Whether the note that hdrshot keeps running in the tray showed.
    pub(crate) tray_note_shown: bool,
    /// The shortcut that takes an HDR screenshot (Windows).
    pub(crate) screenshot_shortcut: screenshot::Shortcut,
    /// The shortcut that takes a region screenshot (Windows); see
    /// [`Settings::region_shortcut`]. `None` in settings from before it
    /// existed. Saved as a plain shortcut.
    #[serde(
        deserialize_with = "some_shortcut",
        serialize_with = "plain_shortcut",
        skip_serializing_if = "Option::is_none"
    )]
    pub(crate) region_shortcut: Option<screenshot::Shortcut>,
    /// Where screenshots are saved; `None` is `hdrshot` in Pictures.
    pub(crate) screenshot_dir: Option<PathBuf>,
    /// Whether screenshots show the window in front or the whole screen.
    pub(crate) screenshot_area: screenshot::Area,
    /// Save screenshots in a subfolder per game.
    pub(crate) screenshot_game_folders: bool,
    /// The view shown last: the file list or the Screenshots view.
    pub(crate) view: View,
    /// What screenshots are converted to; `None` is the same as other
    /// images. The formats apply only with a mode.
    pub(crate) screenshot_mode: Option<Mode>,
    pub(crate) screenshot_hdr_format: Format,
    pub(crate) screenshot_sdr_format: SdrKind,
    /// What happens once a screenshot is converted; see
    /// [`Settings::after_screenshot`]. `None` in settings from before the
    /// choice existed.
    pub(crate) after_screenshot: Option<AfterShot>,
    /// Play a click when a screenshot is taken.
    pub(crate) shutter_sound: bool,
}

impl Settings {
    /// Whether the names need `_hdr`/`_sdr` to tell the two PNGs apart.
    pub(crate) fn suffix_needed(&self) -> bool {
        self.suffix_needed_for(self.mode)
    }

    fn suffix_needed_for(&self, mode: Mode) -> bool {
        mode == Mode::Both && !self.subfolders
    }

    pub(crate) fn naming(&self) -> Naming {
        self.naming_for(self.mode)
    }

    /// The naming for images converted with `mode`.
    fn naming_for(&self, mode: Mode) -> Naming {
        Naming {
            pattern: if self.type_suffix || self.suffix_needed_for(mode) {
                Naming::DEFAULT_PATTERN.into()
            } else {
                "{name}".into()
            },
            subfolders: self.subfolders,
        }
    }

    /// `options`, the ones for converting, changed for screenshots hdrshot
    /// took: their own mode and formats, if chosen. Where and how files
    /// are saved, the tuning and the size stay the same.
    pub(crate) fn screenshot_options(&self, mut options: ConvertOptions) -> ConvertOptions {
        let Some(mode) = self.screenshot_mode else {
            return options;
        };
        options.mode = mode.into();
        options.hdr.format = self.screenshot_hdr_format.into();
        options.sdr_format = self.screenshot_sdr_format.into();
        options.naming = self.naming_for(mode);
        options
    }

    /// Whether converted images go to a folder that isn't chosen yet, so
    /// nothing can be converted.
    pub(crate) fn save_folder_missing(&self) -> bool {
        self.save_to_folder && self.output_dir.is_none()
    }

    /// What happens once a screenshot is converted. Until chosen, it
    /// follows **Copy the last converted image**, which screenshots used
    /// in 2.4.0, so turning that off then still leaves the clipboard alone.
    pub(crate) fn after_screenshot(&self) -> AfterShot {
        self.after_screenshot.unwrap_or(if self.copy_to_clipboard {
            AfterShot::Copy
        } else {
            AfterShot::Nothing
        })
    }

    /// The region shortcut. Until chosen, Ctrl+Alt+PrtScn, or the first
    /// other choice when the screenshot shortcut has that, as 2.4.0 let
    /// it, so that both work.
    pub(crate) fn region_shortcut(&self) -> screenshot::Shortcut {
        use screenshot::Shortcut;
        self.region_shortcut.unwrap_or_else(|| {
            let main = self.screenshot_shortcut;
            if main != Shortcut::CtrlAltPrintScreen {
                return Shortcut::CtrlAltPrintScreen;
            }
            Shortcut::ALL
                .into_iter()
                .find(|&s| s != main && s != Shortcut::Off)
                .unwrap_or(Shortcut::Off)
        })
    }

    /// Fixes the choices that follow others until made, once loaded, so
    /// they stay as they are when those others change later.
    pub(crate) fn settle(&mut self) {
        self.after_screenshot = Some(self.after_screenshot());
        self.region_shortcut = Some(self.region_shortcut());
    }

    /// What the output chip says, e.g. "HDR PNG + SDR JPEG".
    pub(crate) fn output_summary(&self) -> String {
        let hdr = match self.hdr_format {
            Format::Png if self.discord_png => "HDR PNG for Discord",
            Format::Png => "HDR PNG",
            Format::Avif => "HDR AVIF",
            Format::UltraHdr => "Ultra HDR JPEG",
        };
        let sdr = match self.sdr_format {
            SdrKind::Png => "SDR PNG",
            SdrKind::Jpeg => "SDR JPEG",
        };
        match self.mode {
            Mode::Both => format!("{hdr} + {sdr}"),
            Mode::Hdr => hdr.to_owned(),
            Mode::Sdr => sdr.to_owned(),
        }
    }

    /// What the save chip says: the folder's name, not its whole path.
    pub(crate) fn save_summary(&self) -> String {
        if !self.save_to_folder {
            return "Next to originals".to_owned();
        }
        match &self.output_dir {
            Some(dir) => format!("In {}", folder_name(dir)),
            None => "Choose a folder".to_owned(),
        }
    }

    /// Saves into `dir` from now on and puts it first in the save menu.
    pub(crate) fn use_output_dir(&mut self, dir: PathBuf) {
        self.recent_dirs.retain(|d| d != &dir);
        self.recent_dirs.insert(0, dir.clone());
        self.recent_dirs.truncate(RECENT_DIRS);
        self.output_dir = Some(dir);
        self.save_to_folder = true;
    }

    /// The folders the save menu offers: the chosen one and the recent
    /// ones that still exist.
    pub(crate) fn save_folders(&self) -> Vec<PathBuf> {
        let mut folders: Vec<PathBuf> = Vec::new();
        for dir in self.output_dir.iter().chain(&self.recent_dirs) {
            if !folders.contains(dir) && dir.is_dir() {
                folders.push(dir.clone());
            }
        }
        folders.truncate(RECENT_DIRS);
        folders
    }

    /// What the chip for the steps after converting says: what happens to
    /// the originals, and the clipboard copy only when it is off, so the
    /// chips fit one row in the default window.
    pub(crate) fn after_summary(&self) -> String {
        match (self.trash_originals, self.copy_to_clipboard) {
            (false, true) => "Keep originals",
            (true, true) => "Replace originals",
            (false, false) => "Keep originals, no clipboard",
            (true, false) => "Replace originals, no clipboard",
        }
        .to_owned()
    }
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            mode: Mode::Both,
            hdr_format: Format::Png,
            sdr_format: SdrKind::Png,
            save_to_folder: false,
            output_dir: None,
            copy_to_clipboard: true,
            keep_date: true,
            subfolders: false,
            type_suffix: true,
            discord_png: false,
            trash_originals: false,
            watch: false,
            watch_dir: watching::default_watch_dir(),
            recent_dirs: Vec::new(),
            hidden_tips: Vec::new(),
            theme: ThemeChoice::System,
            update_check: true,
            last_update_check: 0,
            window: None,
            tray: false,
            start_with_windows: false,
            notify: true,
            tray_note_shown: false,
            screenshot_shortcut: screenshot::Shortcut::CtrlShiftPrintScreen,
            region_shortcut: None,
            screenshot_dir: None,
            screenshot_area: screenshot::Area::Window,
            screenshot_game_folders: true,
            view: View::Files,
            screenshot_mode: None,
            screenshot_hdr_format: Format::Png,
            screenshot_sdr_format: SdrKind::Png,
            after_screenshot: None,
            shutter_sound: false,
        }
    }
}

/// What happens once a screenshot is converted.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum AfterShot {
    /// Copy it to the clipboard as Copy for Discord does.
    Copy,
    /// Show it in its folder.
    Reveal,
    Nothing,
}

impl AfterShot {
    pub(crate) const ALL: [Self; 3] = [Self::Copy, Self::Reveal, Self::Nothing];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Copy => "Copy for Discord",
            Self::Reveal => "Open the folder",
            Self::Nothing => "Nothing",
        }
    }
}

/// Light or dark, or as the system is set.
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum ThemeChoice {
    System,
    Light,
    Dark,
}

impl ThemeChoice {
    /// Uses this theme for the window's contents and its title bar.
    pub(crate) fn apply(self, ctx: &egui::Context) {
        let (preference, title_bar) = match self {
            Self::System => (
                egui::ThemePreference::System,
                egui::SystemTheme::SystemDefault,
            ),
            Self::Light => (egui::ThemePreference::Light, egui::SystemTheme::Light),
            Self::Dark => (egui::ThemePreference::Dark, egui::SystemTheme::Dark),
        };
        ctx.set_theme(preference);
        ctx.send_viewport_cmd(egui::ViewportCommand::SetTheme(title_bar));
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Mode {
    Hdr,
    Sdr,
    Both,
}

impl From<Mode> for OutputMode {
    fn from(mode: Mode) -> Self {
        match mode {
            Mode::Hdr => Self::Hdr,
            Mode::Sdr => Self::Sdr,
            Mode::Both => Self::Both,
        }
    }
}

/// File format of the HDR output.
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Format {
    Png,
    Avif,
    UltraHdr,
}

impl From<Format> for HdrFormat {
    fn from(format: Format) -> Self {
        match format {
            Format::Png => Self::Png,
            Format::Avif => Self::Avif,
            Format::UltraHdr => Self::UltraHdr,
        }
    }
}

/// File format of the SDR output.
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum SdrKind {
    Png,
    Jpeg,
}

impl From<SdrKind> for SdrFormat {
    fn from(kind: SdrKind) -> Self {
        match kind {
            SdrKind::Png => Self::Png,
            SdrKind::Jpeg => Self::Jpeg {
                quality: Self::DEFAULT_JPEG_QUALITY,
            },
        }
    }
}

/// Optional tuning, off by default.
pub(crate) struct Tuning {
    pub(crate) limit_hdr_peak: bool,
    pub(crate) hdr_peak: f32,
    pub(crate) sdr_white: f32,
    pub(crate) fixed_sdr_peak: bool,
    pub(crate) sdr_peak: f32,
    pub(crate) fixed_input_white: bool,
    pub(crate) input_white: f32,
}

impl Default for Tuning {
    fn default() -> Self {
        Self {
            limit_hdr_peak: false,
            hdr_peak: 1000.0,
            sdr_white: SdrOptions::default().white_nits,
            fixed_sdr_peak: false,
            sdr_peak: 1000.0,
            fixed_input_white: false,
            input_white: 80.0,
        }
    }
}

impl Tuning {
    pub(crate) fn is_default(&self) -> bool {
        !self.limit_hdr_peak
            && !self.fixed_sdr_peak
            && !self.fixed_input_white
            && self.sdr_white == SdrOptions::default().white_nits
    }
}

/// What size the listed files come out at with a given height limit.
#[derive(Debug, PartialEq)]
pub(crate) enum OutputSize {
    /// No file in the list, or none whose size could be read.
    Unknown,
    Same(u32, u32),
    Varies,
}

pub(crate) fn output_size(files: &[Entry], max_height: Option<u32>) -> OutputSize {
    let mut sizes = files
        .iter()
        .filter_map(|e| e.size)
        .map(|(w, h)| max_height.map_or((w, h), |max| hdrshot_core::resize::fit_height(w, h, max)));
    let Some(first) = sizes.next() else {
        return OutputSize::Unknown;
    };
    if sizes.all(|s| s == first) {
        OutputSize::Same(first.0, first.1)
    } else {
        OutputSize::Varies
    }
}

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

    fn entry(size: Option<(u32, u32)>) -> Entry {
        Entry {
            path: PathBuf::new(),
            status: Status::Waiting,
            size,
            info: String::new(),
            saved: String::new(),
            thumb: Thumb::Failed,
        }
    }

    #[test]
    fn output_size_keeps_ultrawide_aspect() {
        let files = [entry(Some((3440, 1440))), entry(Some((3440, 1440)))];
        assert_eq!(output_size(&files, None), OutputSize::Same(3440, 1440));
        assert_eq!(
            output_size(&files, Some(1080)),
            OutputSize::Same(2580, 1080)
        );
        assert_eq!(
            output_size(&files, Some(2160)),
            OutputSize::Same(3440, 1440)
        );
    }

    #[test]
    fn output_size_varies_or_unknown() {
        let mixed = [entry(Some((3440, 1440))), entry(Some((3840, 2160)))];
        assert_eq!(output_size(&mixed, Some(1080)), OutputSize::Varies);
        // Both are 1440 or less tall, but their widths differ.
        assert_eq!(output_size(&mixed, Some(1440)), OutputSize::Varies);
        assert_eq!(output_size(&[], Some(1080)), OutputSize::Unknown);
        assert_eq!(output_size(&[entry(None)], None), OutputSize::Unknown);
    }

    #[test]
    fn recent_folders_come_newest_first() {
        let mut s = Settings::default();
        let base = std::env::temp_dir();
        for name in ["a", "b", "c", "d", "b"] {
            s.use_output_dir(base.join(name));
        }
        assert_eq!(
            s.recent_dirs,
            [base.join("b"), base.join("d"), base.join("c")]
        );
        assert_eq!(s.output_dir, Some(base.join("b")));
        // Only folders that exist are offered.
        s.recent_dirs.push(base.clone());
        s.output_dir = Some(base.clone());
        assert_eq!(s.save_folders(), [base]);
    }

    #[test]
    fn name_preview_lists_the_files() {
        let input = Path::new("shots").join("Screenshot 1.jxr");
        let mut s = Settings::default();
        let names = |s: &Settings| {
            let options = ConvertOptions {
                mode: s.mode.into(),
                output_dir: s.save_to_folder.then(|| s.output_dir.clone()).flatten(),
                naming: s.naming(),
                hdr: HdrOptions {
                    format: s.hdr_format.into(),
                    ..Default::default()
                },
                sdr_format: s.sdr_format.into(),
                ..Default::default()
            };
            name_preview(&input, &options)
        };
        assert_eq!(names(&s), ["Screenshot 1_hdr.png", "Screenshot 1_sdr.png"]);
        s.subfolders = true;
        s.type_suffix = false;
        s.hdr_format = Format::Avif;
        s.sdr_format = SdrKind::Jpeg;
        assert_eq!(names(&s), ["hdr/Screenshot 1.avif", "sdr/Screenshot 1.jpg"]);
        s.mode = Mode::Hdr;
        s.save_to_folder = true;
        s.output_dir = Some(std::env::temp_dir().join("out"));
        assert_eq!(names(&s), ["hdr/Screenshot 1.avif"]);
    }

    #[test]
    fn screenshots_get_their_own_output() {
        let mut s = Settings {
            mode: Mode::Hdr,
            hdr_format: Format::Png,
            type_suffix: false,
            keep_date: false,
            save_to_folder: true,
            output_dir: Some(PathBuf::from("out")),
            ..Default::default()
        };
        let batch = ConvertOptions {
            mode: s.mode.into(),
            output_dir: s.output_dir.clone(),
            naming: s.naming(),
            keep_date: s.keep_date,
            max_height: Some(1440),
            ..Default::default()
        };
        // Same as converting.
        let same = s.screenshot_options(batch.clone());
        assert_eq!(same.mode, OutputMode::Hdr);
        assert_eq!(same.naming, batch.naming);
        assert_eq!(same.hdr.format, HdrFormat::Png);

        s.screenshot_mode = Some(Mode::Both);
        s.screenshot_hdr_format = Format::Avif;
        s.screenshot_sdr_format = SdrKind::Jpeg;
        let own = s.screenshot_options(batch.clone());
        assert_eq!(own.mode, OutputMode::Both);
        assert_eq!(own.hdr.format, HdrFormat::Avif);
        assert!(matches!(own.sdr_format, SdrFormat::Jpeg { .. }));
        // Both in one folder need the suffixes, whatever the batch's names.
        assert_eq!(own.naming.pattern, Naming::DEFAULT_PATTERN);
        // Where and how they are saved stays.
        assert_eq!(own.output_dir, batch.output_dir);
        assert_eq!(own.max_height, Some(1440));
        assert!(!own.keep_date);
        let input = Path::new("shots").join("Game 2026-11-28 20-15-00.jxr");
        assert_eq!(
            name_preview(&input, &own),
            [
                "Game 2026-11-28 20-15-00_hdr.avif",
                "Game 2026-11-28 20-15-00_sdr.jpg"
            ]
        );

        s.screenshot_mode = Some(Mode::Sdr);
        let sdr = s.screenshot_options(batch);
        assert_eq!(sdr.mode, OutputMode::Sdr);
        assert_eq!(name_preview(&input, &sdr), ["Game 2026-11-28 20-15-00.jpg"]);
    }

    #[test]
    fn after_screenshot_follows_the_clipboard_setting_from_2_4_0() {
        let copying: Settings = serde_json::from_str(r#"{"copy_to_clipboard": true}"#).unwrap();
        assert_eq!(copying.after_screenshot(), AfterShot::Copy);
        let mut off: Settings = serde_json::from_str(r#"{"copy_to_clipboard": false}"#).unwrap();
        assert_eq!(off.after_screenshot(), AfterShot::Nothing);
        // Once settled, turning copying back on doesn't change it.
        off.settle();
        off.copy_to_clipboard = true;
        assert_eq!(off.after_screenshot(), AfterShot::Nothing);
        // A choice made is kept, whatever copying is.
        let chosen: Settings =
            serde_json::from_str(r#"{"copy_to_clipboard": false, "after_screenshot": "Reveal"}"#)
                .unwrap();
        assert_eq!(chosen.after_screenshot(), AfterShot::Reveal);
        assert_eq!(Settings::default().after_screenshot(), AfterShot::Copy);
    }

    #[test]
    fn region_shortcut_moves_off_the_screenshot_shortcut_from_2_4_0() {
        use screenshot::Shortcut;
        // 2.4.0 with Ctrl+Alt+PrtScn for screenshots: the region shortcut
        // takes the first other choice.
        let mut s: Settings =
            serde_json::from_str(r#"{"screenshot_shortcut": "CtrlAltPrintScreen"}"#).unwrap();
        assert_eq!(s.region_shortcut(), Shortcut::CtrlShiftPrintScreen);
        s.settle();
        assert_eq!(s.region_shortcut, Some(Shortcut::CtrlShiftPrintScreen));
        // Otherwise the default.
        let mut s: Settings =
            serde_json::from_str(r#"{"screenshot_shortcut": "ShiftPrintScreen"}"#).unwrap();
        s.settle();
        assert_eq!(s.region_shortcut(), Shortcut::CtrlAltPrintScreen);
        assert_eq!(
            Settings::default().region_shortcut(),
            Shortcut::CtrlAltPrintScreen
        );
        // A choice saved is kept, even the same one, which then says to
        // choose another.
        let mut s: Settings = serde_json::from_str(
            r#"{"screenshot_shortcut": "CtrlAltPrintScreen", "region_shortcut": "CtrlAltPrintScreen"}"#,
        )
        .unwrap();
        s.settle();
        assert_eq!(s.region_shortcut(), Shortcut::CtrlAltPrintScreen);
        // Saved as a plain shortcut, as before, and read back the same.
        s.region_shortcut = Some(Shortcut::ShiftPrintScreen);
        let saved = ron::to_string(&s).unwrap();
        assert!(
            saved.contains("region_shortcut:ShiftPrintScreen"),
            "{saved}"
        );
        let back: Settings = ron::from_str(&saved).unwrap();
        assert_eq!(back.region_shortcut, Some(Shortcut::ShiftPrintScreen));
    }

    #[test]
    fn report_url_fills_in_the_version() {
        let url = report_url();
        assert!(
            url.starts_with("https://github.com/snaketech-tu/hdrshot/issues/new?template=bug.yml&")
        );
        assert!(url.contains(&format!("version={}", env!("CARGO_PKG_VERSION"))));
        assert!(!url.contains(' '));
    }

    #[test]
    fn chips_sum_up_the_settings() {
        let mut s = Settings::default();
        assert_eq!(s.output_summary(), "HDR PNG + SDR PNG");
        assert_eq!(s.save_summary(), "Next to originals");
        assert_eq!(s.after_summary(), "Keep originals");
        assert_eq!(size_summary(None), "Source size");
        assert_eq!(size_summary(Some(1440)), "Up to 1440p");

        s.mode = Mode::Hdr;
        s.hdr_format = Format::Avif;
        assert_eq!(s.output_summary(), "HDR AVIF");
        s.mode = Mode::Sdr;
        s.sdr_format = SdrKind::Jpeg;
        assert_eq!(s.output_summary(), "SDR JPEG");

        s.save_to_folder = true;
        s.output_dir = None;
        assert_eq!(s.save_summary(), "Choose a folder");
        s.output_dir = Some(PathBuf::from("shots").join("HDR"));
        assert_eq!(s.save_summary(), "In HDR");

        s.trash_originals = true;
        assert_eq!(s.after_summary(), "Replace originals");
        s.copy_to_clipboard = false;
        assert_eq!(s.after_summary(), "Replace originals, no clipboard");
        s.trash_originals = false;
        assert_eq!(s.after_summary(), "Keep originals, no clipboard");
    }
}