hdrshot-gui 2.4.0

HDR image tool: desktop app for converting HDR screenshots and images
//! The app's side of HDR screenshots: the shortcut, the tray menu item and
//! the camera button take them (see `screenshot`), and each one saved is
//! converted right away like a new file in the watch folder. Ctrl+V
//! without copied files adds the screenshot just taken instead.

use std::time::Duration;

use screenshot::{Shortcut, Taken, Target};

use super::*;

/// How recent a screenshot Ctrl+V adds when no files were copied.
const RECENT_CAPTURE: Duration = Duration::from_secs(5 * 60);

/// How long a toast explaining what Ctrl+V did stays up.
const PASTE_TOAST_SECONDS: f64 = 7.0;

/// The screenshot state the app keeps.
pub(crate) struct Shots {
    #[cfg_attr(not(windows), allow(dead_code))]
    hotkey: Option<screenshot::Hotkey>,
    /// The shortcut last registered or tried, `None` before the first try.
    #[cfg_attr(not(windows), allow(dead_code))]
    registered: Option<Shortcut>,
    /// Why the shortcut couldn't be registered.
    pub(crate) error: Option<String>,
    /// Where the shortcut saves, shared with its thread.
    #[cfg_attr(not(windows), allow(dead_code))]
    folder: std::sync::Arc<std::sync::Mutex<PathBuf>>,
    pub(crate) taken: (Sender<Taken>, Receiver<Taken>),
    /// Whether the window was minimized for a screenshot and comes back
    /// once it's taken.
    restore: bool,
}

impl Default for Shots {
    fn default() -> Self {
        Self {
            hotkey: None,
            registered: None,
            error: None,
            folder: Default::default(),
            taken: channel(),
            restore: false,
        }
    }
}

impl App {
    /// Where screenshots are saved.
    pub(crate) fn screenshot_dir(&self) -> Option<PathBuf> {
        self.settings
            .screenshot_dir
            .clone()
            .or_else(screenshot::default_folder)
    }

    /// Registers the shortcut to match the settings and converts the
    /// screenshots taken.
    pub(crate) fn sync_screenshots(&mut self, ctx: &egui::Context) {
        if !screenshot::SUPPORTED {
            return;
        }
        #[cfg(windows)]
        {
            if let (Ok(mut folder), Some(dir)) = (self.shots.folder.lock(), self.screenshot_dir())
                && *folder != dir
            {
                *folder = dir;
            }
            let wanted = self.settings.screenshot_shortcut;
            if self.shots.registered != Some(wanted) {
                self.shots.hotkey = None;
                self.shots.error = None;
                self.shots.registered = Some(wanted);
                if wanted != Shortcut::Off {
                    match screenshot::Hotkey::register(
                        wanted,
                        self.shots.folder.clone(),
                        self.shots.taken.0.clone(),
                        ctx.clone(),
                    ) {
                        Ok(hotkey) => self.shots.hotkey = Some(hotkey),
                        Err(e) => self.shots.error = Some(e),
                    }
                }
            }
        }
        let taken: Vec<_> = self.shots.taken.1.try_iter().collect();
        for outcome in taken {
            if std::mem::take(&mut self.shots.restore) {
                self.show_window(ctx);
            }
            match outcome {
                // A watch folder that holds it reports it already.
                Ok(path)
                    if self
                        .watching
                        .as_ref()
                        .is_some_and(|w| path.starts_with(&w.dir)) => {}
                Ok(path) => {
                    let _ = self.watched.0.send(path);
                }
                Err(e) => self.screenshot_failed(e, ctx),
            }
        }
    }

    fn screenshot_failed(&mut self, error: String, ctx: &egui::Context) {
        let background = self.hidden || !ctx.input(|i| i.focused);
        match &self.tray {
            Some(tray) if background => tray.notify("Screenshot not taken", &error),
            _ => self.show_toast(error, ctx),
        }
    }

    /// Takes a screenshot of the screen with the pointer, once the tray
    /// menu has closed.
    pub(crate) fn screenshot_from_tray(&mut self, ctx: &egui::Context) {
        let _ = self.take_screenshot(Duration::from_millis(300), Target::Pointer, ctx);
    }

    /// Minimizes the window, takes a screenshot of what's behind it, then
    /// brings the window back.
    pub(crate) fn screenshot_from_window(&mut self, ctx: &egui::Context) {
        // Long enough for the minimize animation.
        if self.take_screenshot(Duration::from_millis(700), Target::Foreground, ctx) {
            self.shots.restore = true;
            ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
        }
    }

    /// Starts taking a screenshot; `false` if there's no folder for it.
    fn take_screenshot(&mut self, delay: Duration, target: Target, ctx: &egui::Context) -> bool {
        let Some(dir) = self.screenshot_dir() else {
            self.show_toast("Choose a folder for screenshots in Settings".into(), ctx);
            return false;
        };
        screenshot::take_later(delay, target, dir, self.shots.taken.0.clone(), ctx.clone());
        true
    }

    /// The shortcut's name for messages, if one is on.
    fn shortcut_name(&self) -> Option<&'static str> {
        let shortcut = self.settings.screenshot_shortcut;
        (screenshot::SUPPORTED && shortcut != Shortcut::Off && self.shots.error.is_none())
            .then(|| shortcut.label())
    }

    /// The camera button in the header: takes a screenshot of what's
    /// behind the window.
    pub(crate) fn camera_button(&mut self, ui: &mut egui::Ui) {
        if !screenshot::SUPPORTED {
            return;
        }
        let hint = match self.shortcut_name() {
            Some(keys) => format!(
                "Take an HDR screenshot of what's behind this window. In a game, press \
                 {keys} instead."
            ),
            None => "Take an HDR screenshot of what's behind this window".to_owned(),
        };
        if theme::icon_button(ui, icons::camera)
            .on_hover_text(hint)
            .clicked()
        {
            let ctx = ui.ctx().clone();
            self.screenshot_from_window(&ctx);
        }
    }

    /// Ctrl+V: adds copied files, or else the screenshot just taken, or
    /// says why there's nothing to add.
    pub(crate) fn paste_clipboard(&mut self, pasted: window::Pasted, ctx: &egui::Context) {
        // Pasting into a text field.
        if ctx.memory(|m| m.focused().is_some()) && !matches!(pasted, window::Pasted::Files(_)) {
            return;
        }
        let picture = match pasted {
            window::Pasted::Files(files) => {
                self.add_paths(files);
                self.settings_open = false;
                return;
            }
            window::Pasted::Picture => true,
            window::Pasted::Nothing => false,
        };
        let own = self.screenshot_dir();
        if let Some(path) = watching::recent_capture(own.as_deref(), RECENT_CAPTURE) {
            let name = path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();
            self.add_paths([path]);
            self.settings_open = false;
            self.long_toast(format!("Added your latest HDR screenshot, {name}"), ctx);
            return;
        }
        let take = match self.shortcut_name() {
            Some(keys) => format!("press {keys} or Win+Alt+PrtScn (Game Bar)"),
            None if cfg!(windows) => "press Win+Alt+PrtScn (Game Bar)".to_owned(),
            None => String::new(),
        };
        let text = if picture {
            format!(
                "The clipboard holds a picture, not a file. Windows makes pictures it \
                 copies SDR, so there's no HDR left in it. For an HDR screenshot, {take}, \
                 then press Ctrl+V here."
            )
        } else if cfg!(windows) {
            format!(
                "Nothing to paste. Copy images in Explorer, or for an HDR screenshot, \
                 {take}, then press Ctrl+V here."
            )
        } else if cfg!(target_os = "macos") {
            "Nothing to paste. Copy images in Finder first.".to_owned()
        } else {
            "Nothing to paste. Copy images in your file manager first.".to_owned()
        };
        self.long_toast(text, ctx);
    }

    fn long_toast(&mut self, text: String, ctx: &egui::Context) {
        self.toast = Some(Toast {
            text,
            until: ctx.input(|i| i.time) + PASTE_TOAST_SECONDS,
        });
    }

    /// The shortcut and the folder, on the Settings page.
    pub(crate) fn screenshot_ui(&mut self, ui: &mut egui::Ui) {
        ui.label(
            RichText::new(
                "Press the shortcut in a game to save an HDR screenshot of the screen it's \
                 on, as a JPEG XR file like Game Bar's. hdrshot then converts it with the \
                 settings above. It works while hdrshot is open, or running in the tray \
                 (see Background).",
            )
            .weak(),
        );
        ui.add_space(6.0);
        settings_grid(ui, "screenshots", |ui| {
            theme::row_label(ui, "Shortcut");
            ui.vertical(|ui| {
                let current = self.settings.screenshot_shortcut;
                egui::ComboBox::from_id_salt("screenshot shortcut")
                    .selected_text(current.label())
                    .show_ui(ui, |ui| {
                        for shortcut in Shortcut::ALL {
                            ui.selectable_value(
                                &mut self.settings.screenshot_shortcut,
                                shortcut,
                                shortcut.label(),
                            );
                        }
                    });
                if let Some(error) = &self.shots.error {
                    ui.label(RichText::new(error).color(ui.visuals().error_fg_color));
                }
            });
            ui.end_row();

            theme::row_label(ui, "Save in");
            ui.horizontal(|ui| {
                let dir = self.screenshot_dir();
                let label = dir.as_ref().map_or_else(
                    || "Choose a folder…".to_owned(),
                    |d| d.display().to_string(),
                );
                if ui
                    .add(egui::Button::new(label).truncate())
                    .on_hover_text("Choose the folder screenshots are saved in")
                    .clicked()
                {
                    let mut dialog = rfd::FileDialog::new().set_title("Save screenshots in");
                    if let Some(dir) = dir.as_ref().filter(|d| d.is_dir()) {
                        dialog = dialog.set_directory(dir);
                    }
                    if let Some(dir) = dialog.pick_folder() {
                        self.settings.screenshot_dir = Some(dir);
                    }
                }
                if let Some(dir) = dir.filter(|d| d.is_dir())
                    && theme::small_icon_button(ui, icons::folder)
                        .on_hover_text("Open the folder")
                        .clicked()
                {
                    reveal(&dir);
                }
            });
            ui.end_row();
        });
    }
}