hdrshot-gui 2.6.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
//! Adding files: the drop area of the empty window with its tip, the
//! toolbar above the list, and the overlay shown while files are dragged
//! over the window.

use super::*;

/// The input formats, named on the empty window's drop area.
const FORMATS: [&str; 8] = [
    "JPEG XR",
    "HDR JPEG",
    "HEIC",
    "HDR AVIF",
    "OpenEXR",
    "Radiance HDR",
    "JPEG XL",
    "HDR PNG",
];

/// Names of the tips under the empty drop area, kept in the settings once
/// hidden.
const WATCH_TIP: &str = "watch-folder";
const SCREENSHOT_TIP: &str = "screenshots";

/// A tip under the empty drop area. Only one shows at a time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tip {
    /// How to take screenshots. `offer_tray` adds a button that keeps
    /// hdrshot in the tray and starts it with Windows, so the shortcut is
    /// always ready.
    Screenshot { offer_tray: bool },
    /// Watching the folder Game Bar saves screenshots in.
    Watch,
}

/// The tip to show: the screenshot one first, since a new user can't find
/// the shortcut alone, then the watch folder one. `shortcut_on` is whether
/// the screenshot shortcut is registered, `always_running` whether hdrshot
/// already stays in the tray and starts with Windows, `can_run_in_background`
/// whether this platform has a tray, and `watch_applies` whether the watch
/// folder tip applies.
fn choose_tip(
    hidden: &[String],
    shortcut_on: bool,
    always_running: bool,
    can_run_in_background: bool,
    watch_applies: bool,
) -> Option<Tip> {
    let hidden = |name: &str| hidden.iter().any(|t| t == name);
    if shortcut_on && !hidden(SCREENSHOT_TIP) {
        Some(Tip::Screenshot {
            offer_tray: can_run_in_background && !always_running,
        })
    } else if watch_applies && !hidden(WATCH_TIP) {
        Some(Tip::Watch)
    } else {
        None
    }
}

/// Smallest height of the empty window's drop area, which fits its text.
const MIN_DROP_HEIGHT: f32 = 180.0;

impl App {
    pub(crate) fn add_paths(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
        let mut skipped = 0;
        for path in paths {
            // Added files show at once, even from the Screenshots view.
            self.settings.view = View::Files;
            if path.is_dir() {
                for file in hdrshot_core::find_inputs(&path, true) {
                    self.add_file(file);
                }
            } else if hdrshot_core::is_supported(&path) {
                self.add_file(path);
            } else {
                skipped += 1;
            }
        }
        self.notice = (skipped > 0).then(|| {
            format!(
                "Skipped {skipped} file{} that {} not a supported image.",
                if skipped == 1 { "" } else { "s" },
                if skipped == 1 { "is" } else { "are" }
            )
        });
    }

    pub(crate) fn add_file(&mut self, path: PathBuf) {
        if !self.files.iter().any(|e| e.path == path) {
            let size = hdrshot_core::input::dimensions(&path).ok();
            let bytes = std::fs::metadata(&path).ok().map(|m| m.len());
            self.previews.request(&path);
            self.files.push(Entry {
                info: input_info(&path, size, bytes),
                path,
                status: Status::Waiting,
                size,
                saved: String::new(),
                thumb: Thumb::Loading,
            });
        }
    }

    /// Asks for images with the system's file dialog and adds them.
    pub(crate) fn choose_files(&mut self) {
        if let Some(paths) = rfd::FileDialog::new()
            .set_title("Choose HDR images")
            .add_filter("HDR images", &INPUT_EXTENSIONS)
            .pick_files()
        {
            self.add_paths(paths);
        }
    }

    /// The empty window: a large drop area, with a tip under it until it
    /// is followed or hidden.
    pub(crate) fn empty_ui(&mut self, ui: &mut egui::Ui) {
        // The drop area takes what the tip leaves. The tip's text can wrap,
        // so its height is only known once laid out: it is remembered, and
        // when it changes, the pass is redone. In a window too short for
        // both, only the drop area shows.
        let tip_id = egui::Id::unique("empty window tip height");
        let tip_height = ui.data(|d| d.get_temp::<f32>(tip_id)).unwrap_or_default();
        let available = ui.available_height();
        let tip = self
            .current_tip()
            .filter(|_| available - tip_height >= MIN_DROP_HEIGHT);
        let reserved = if tip.is_some() { tip_height } else { 0.0 };
        self.drop_area(ui, (available - reserved).max(MIN_DROP_HEIGHT));
        let top = ui.cursor().top();
        match tip {
            Some(Tip::Screenshot { offer_tray }) => self.screenshot_tip(ui, offer_tray),
            Some(Tip::Watch) => self.watch_tip(ui),
            None => return,
        }
        let used = ui.cursor().top() - top;
        if (used - tip_height).abs() > 0.5 {
            ui.data_mut(|d| d.insert_temp(tip_id, used));
            ui.ctx().request_discard("the tip's height changed");
        }
    }

    /// The tip that applies and isn't hidden, if any.
    fn current_tip(&self) -> Option<Tip> {
        let s = &self.settings;
        choose_tip(
            &s.hidden_tips,
            self.shortcut_name().is_some(),
            s.tray && (s.start_with_windows || !startup::SUPPORTED),
            tray::SUPPORTED,
            self.watch_tip_applies(),
        )
    }

    /// Whether the watch folder tip applies: not once watching is on or
    /// another folder is chosen to watch.
    fn watch_tip_applies(&self) -> bool {
        let folders = watching::capture_folders();
        !self.settings.watch
            && !folders.is_empty()
            && self
                .settings
                .watch_dir
                .as_ref()
                .is_none_or(|dir| folders.iter().any(|f| &f.dir == dir))
    }

    /// The first-start card: how to take screenshots, and that the
    /// shortcut needs hdrshot running, with an offer to keep it running.
    fn screenshot_tip(&mut self, ui: &mut egui::Ui, offer_tray: bool) {
        let Some(keys) = self.shortcut_name() else {
            return;
        };
        let text = if offer_tray {
            format!(
                "Press {keys} in a game to save an HDR screenshot. The shortcut \
                 only works while hdrshot runs, so keep it in the tray to have it \
                 ready."
            )
        } else {
            format!(
                "Press {keys} in a game to save an HDR screenshot. The shortcut \
                 only works while hdrshot runs, open or in the tray."
            )
        };
        let buttons: &[&str] = if offer_tray {
            &["Keep in tray and start with Windows", "Not now"]
        } else {
            &["Got it"]
        };
        match stacked_tip(ui, icons::camera, "Take HDR screenshots", &text, buttons) {
            Some(0) if offer_tray => {
                let ctx = ui.ctx().clone();
                self.settings.tray = true;
                // The same as turning both on in Settings.
                let started = !startup::SUPPORTED || {
                    self.settings.start_with_windows = true;
                    self.apply_start_with_windows(&ctx)
                };
                if started {
                    self.show_toast(
                        "hdrshot now starts with Windows and stays in the tray".into(),
                        &ctx,
                    );
                }
                self.settings.hidden_tips.push(SCREENSHOT_TIP.into());
            }
            Some(_) => self.settings.hidden_tips.push(SCREENSHOT_TIP.into()),
            None => {}
        }
    }

    /// The tip offering to watch the folder Game Bar saves screenshots in.
    fn watch_tip(&mut self, ui: &mut egui::Ui) {
        let Some(folder) = watching::capture_folders().first() else {
            return;
        };
        match tip(
            ui,
            icons::eye,
            &format!("Watch the {} folder", folder.app),
            &format!(
                "Convert new {} screenshots as soon as you take them, while \
                 hdrshot is open.",
                folder.app
            ),
            "Turn on",
        ) {
            Some(true) => {
                let ctx = ui.ctx().clone();
                self.show_toast(format!("Watching {}", folder.dir.display()), &ctx);
                self.settings.watch_dir = Some(folder.dir.clone());
                self.settings.watch = true;
            }
            Some(false) => self.settings.hidden_tips.push(WATCH_TIP.into()),
            None => {}
        }
    }

    /// The large drop area of the empty window, which opens the file dialog
    /// when clicked.
    fn drop_area(&mut self, ui: &mut egui::Ui, height: f32) {
        let (rect, response) =
            ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::click());
        let visuals = ui.visuals();
        let accent = visuals.selection.bg_fill;
        let hovered = response.hovered();
        let painter = ui.painter();
        if hovered {
            painter.rect_filled(rect, 12.0, accent.gamma_multiply(0.08));
            painter.rect_stroke(rect, 12.0, Stroke::new(1.5, accent), StrokeKind::Inside);
        } else {
            painter.rect_filled(rect, 12.0, visuals.faint_bg_color);
            let stroke = Stroke::new(1.5, visuals.weak_text_color().gamma_multiply(0.45));
            dashed_outline(painter, rect.shrink(1.0), 12.0, stroke);
        }

        let center = rect.center() - Vec2::new(0.0, 16.0);
        let circle = center - Vec2::new(0.0, 46.0);
        painter.circle_filled(
            circle,
            30.0,
            accent.gamma_multiply(if hovered { 0.24 } else { 0.14 }),
        );
        icons::image(
            painter,
            egui::Rect::from_center_size(circle, Vec2::splat(28.0)),
            accent,
        );
        painter.text(
            center,
            egui::Align2::CENTER_CENTER,
            "Drop HDR images or folders here",
            theme::semibold(16.0),
            visuals.text_color(),
        );
        let paste = if cfg!(target_os = "macos") {
            "Cmd+V"
        } else {
            "Ctrl+V"
        };
        painter.text(
            center + Vec2::new(0.0, 24.0),
            egui::Align2::CENTER_CENTER,
            format!("or click to choose files. {paste} pastes copied files."),
            egui::FontId::proportional(13.0),
            visuals.weak_text_color(),
        );
        format_tags(
            painter,
            center + Vec2::new(0.0, 58.0),
            visuals,
            rect.width(),
        );

        if response
            .on_hover_cursor(egui::CursorIcon::PointingHand)
            .clicked()
        {
            self.choose_files();
        }
    }

    /// The line above the list: how many files it holds, Add files and
    /// Clear.
    pub(crate) fn toolbar(&mut self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            let total = self.files.len();
            let converted = self
                .files
                .iter()
                .filter(|e| matches!(e.status, Status::Done(_)))
                .count();
            let mut count = images(total);
            if converted > 0 {
                count = format!("{count}, {converted} converted");
            }
            ui.label(RichText::new(count).weak());
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if theme::icon_text_button(ui, icons::plus, "Add files")
                    .on_hover_text("Choose more images. You can also drop them on the window.")
                    .clicked()
                {
                    self.choose_files();
                }
                ui.add_enabled_ui(!self.running(), |ui| {
                    ui.menu_button("Clear", |ui| {
                        let ctx = ui.ctx().clone();
                        if ui.button("All files").clicked() {
                            self.clear_all(&ctx);
                        }
                        if ui
                            .add_enabled(converted > 0, egui::Button::new("Converted files"))
                            .on_hover_text("Keep the files still waiting or failed")
                            .clicked()
                        {
                            self.clear_finished(&ctx);
                        }
                    })
                    .response
                    .on_hover_text("Remove files from the list");
                });
            });
        });
    }
}

/// While files are dragged over the window, covers it with a large target
/// saying they will be added. Dropping anywhere adds them.
pub(crate) fn drop_overlay(ctx: &egui::Context) {
    // Not for the window's own files being dragged out over it.
    if ctx.input(|i| i.raw.hovered_files.is_empty()) || dragout::active() {
        return;
    }
    let layer = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("drop overlay"));
    let painter = ctx.layer_painter(layer);
    let style = ctx.global_style();
    let visuals = &style.visuals;
    let accent = visuals.selection.bg_fill;
    let screen = ctx.content_rect();
    painter.rect_filled(screen, 0.0, visuals.panel_fill);
    let target = screen.shrink(12.0);
    painter.rect_filled(target, 14.0, accent.gamma_multiply(0.10));
    dashed_outline(&painter, target, 14.0, Stroke::new(2.0, accent));
    let center = target.center();
    let circle = center - Vec2::new(0.0, 44.0);
    painter.circle_filled(circle, 34.0, accent.gamma_multiply(0.2));
    icons::drop(
        &painter,
        egui::Rect::from_center_size(circle, Vec2::splat(30.0)),
        accent,
    );
    painter.text(
        center + Vec2::new(0.0, 8.0),
        egui::Align2::CENTER_CENTER,
        "Release to add",
        theme::semibold(18.0),
        visuals.text_color(),
    );
    painter.text(
        center + Vec2::new(0.0, 34.0),
        egui::Align2::CENTER_CENTER,
        "Nothing is converted until you press Convert.",
        egui::FontId::proportional(13.0),
        visuals.weak_text_color(),
    );
}

/// The input formats as small tags in a row centered on `center`, as many
/// as fit in `width`.
fn format_tags(painter: &egui::Painter, center: egui::Pos2, visuals: &egui::Visuals, width: f32) {
    let font = egui::FontId::proportional(11.5);
    let color = visuals.weak_text_color();
    let gap = 6.0;
    let mut galleys: Vec<_> = FORMATS
        .iter()
        .map(|f| painter.layout_no_wrap((*f).to_owned(), font.clone(), color))
        .collect();
    let row_width = |galleys: &[std::sync::Arc<egui::Galley>]| {
        galleys.iter().map(|g| g.size().x + 16.0 + gap).sum::<f32>() - gap
    };
    while galleys.len() > 1 && row_width(&galleys) > width - 32.0 {
        galleys.pop();
    }
    let mut x = center.x - row_width(&galleys) / 2.0;
    for galley in galleys {
        let size = galley.size() + Vec2::new(16.0, 6.0);
        let rect = egui::Rect::from_min_size(egui::pos2(x, center.y - size.y / 2.0), size);
        painter.rect(
            rect,
            size.y / 2.0,
            visuals.widgets.inactive.bg_fill,
            Stroke::NONE,
            StrokeKind::Inside,
        );
        painter.galley(rect.center() - galley.size() / 2.0, galley, color);
        x = rect.right() + gap;
    }
}

/// A card with an icon, a title, a line of text and a button, plus a
/// cross to hide it. Returns `Some(true)` when the button is clicked and
/// `Some(false)` when the cross is.
fn tip(
    ui: &mut egui::Ui,
    icon: icons::Icon,
    title: &str,
    text: &str,
    button: &str,
) -> Option<bool> {
    let mut clicked = None;
    theme::card(ui, |ui| {
        ui.horizontal(|ui| {
            let accent = theme::accent(ui);
            let (rect, _) = ui.allocate_exact_size(Vec2::splat(32.0), Sense::hover());
            ui.painter()
                .circle_filled(rect.center(), 16.0, accent.gamma_multiply(0.14));
            icon(
                ui.painter(),
                egui::Rect::from_center_size(rect.center(), Vec2::splat(16.0)),
                accent,
            );
            ui.add_space(4.0);
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if theme::small_icon_button(ui, icons::cross)
                    .on_hover_text("Don't show this again")
                    .clicked()
                {
                    clicked = Some(false);
                }
                if ui.button(button).clicked() {
                    clicked = Some(true);
                }
                ui.add_space(4.0);
                ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
                    ui.spacing_mut().item_spacing.y = 2.0;
                    ui.label(RichText::new(title).font(theme::semibold(13.5)));
                    ui.label(RichText::new(text).size(12.5).weak());
                });
            });
        });
    });
    clicked
}

/// A card with an icon, a title and text beside it, and a row of buttons
/// under the text, which fits a narrow window better than [`tip`] when the
/// buttons are long. Returns the index of the button clicked.
fn stacked_tip(
    ui: &mut egui::Ui,
    icon: icons::Icon,
    title: &str,
    text: &str,
    buttons: &[&str],
) -> Option<usize> {
    let mut clicked = None;
    theme::card(ui, |ui| {
        ui.horizontal_top(|ui| {
            let accent = theme::accent(ui);
            let (rect, _) = ui.allocate_exact_size(Vec2::splat(32.0), Sense::hover());
            ui.painter()
                .circle_filled(rect.center(), 16.0, accent.gamma_multiply(0.14));
            icon(
                ui.painter(),
                egui::Rect::from_center_size(rect.center(), Vec2::splat(16.0)),
                accent,
            );
            ui.add_space(4.0);
            ui.vertical(|ui| {
                ui.spacing_mut().item_spacing.y = 2.0;
                ui.label(RichText::new(title).font(theme::semibold(13.5)));
                ui.label(RichText::new(text).size(12.5).weak());
                ui.add_space(6.0);
                ui.horizontal_wrapped(|ui| {
                    for (i, label) in buttons.iter().enumerate() {
                        let button = if i == 0 {
                            theme::primary(
                                ui,
                                egui::Button::new(
                                    RichText::new(*label).color(egui::Color32::WHITE),
                                ),
                            )
                        } else {
                            egui::Button::new(*label)
                        };
                        if ui.add(button).clicked() {
                            clicked = Some(i);
                        }
                    }
                });
            });
        });
    });
    clicked
}

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

    fn hidden(names: &[&str]) -> Vec<String> {
        names.iter().map(|n| (*n).to_owned()).collect()
    }

    #[test]
    fn screenshot_tip_comes_before_watch_tip() {
        assert_eq!(
            choose_tip(&[], true, false, true, true),
            Some(Tip::Screenshot { offer_tray: true })
        );
    }

    #[test]
    fn screenshot_tip_offers_tray_only_when_useful() {
        // Already in the tray and starting with Windows.
        assert_eq!(
            choose_tip(&[], true, true, true, false),
            Some(Tip::Screenshot { offer_tray: false })
        );
        // No tray on this platform.
        assert_eq!(
            choose_tip(&[], true, false, false, false),
            Some(Tip::Screenshot { offer_tray: false })
        );
    }

    #[test]
    fn hidden_or_unusable_screenshot_tip_leaves_watch_tip() {
        let watch = Some(Tip::Watch);
        assert_eq!(
            choose_tip(&hidden(&[SCREENSHOT_TIP]), true, false, true, true),
            watch
        );
        // No shortcut registered, e.g. turned off or taken by another app.
        assert_eq!(choose_tip(&[], false, false, true, true), watch);
    }

    #[test]
    fn no_tip_once_all_are_hidden_or_moot() {
        let both = hidden(&[SCREENSHOT_TIP, WATCH_TIP]);
        assert_eq!(choose_tip(&both, true, false, true, true), None);
        assert_eq!(
            choose_tip(&hidden(&[WATCH_TIP]), false, false, true, true),
            None
        );
        assert_eq!(choose_tip(&[], false, false, true, false), None);
    }
}