use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Condvar, Mutex};
use std::time::SystemTime;
use super::*;
use viewer::Source;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum View {
#[default]
Files,
Screenshots,
}
const MIN_TILE_WIDTH: f32 = 150.0;
const GAP: f32 = 8.0;
const CAPTION_HEIGHT: f32 = 26.0;
const HEADING_HEIGHT: f32 = 30.0;
const RADIUS: u8 = 9;
const THUMB_BOX: u32 = 384;
const CACHE: usize = 160;
const DECODERS: usize = 2;
const MAX_DEPTH: usize = 3;
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",
];
#[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)
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Name<'a> {
pub(crate) game: &'a str,
pub(crate) taken: Option<Stamp>,
pub(crate) number: u32,
}
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));
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,
}
}
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,
};
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)
}
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 folder = relative
.parent()
.into_iter()
.flat_map(Path::components)
.map(|part| part.as_os_str().to_string_lossy().into_owned())
.find(|name| !hdrshot_core::capture::is_month_folder(name));
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)
}
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}")
}
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
}
pub(crate) struct Shot {
pub(crate) path: PathBuf,
pub(crate) game: String,
pub(crate) taken: Option<Stamp>,
number: u32,
modified: Option<SystemTime>,
}
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))
}
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() {
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
}
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()
}
}
struct Thumbnail {
texture: Option<egui::TextureHandle>,
seen: u64,
}
#[derive(Default)]
struct Queue {
wanted: Vec<PathBuf>,
busy: HashSet<PathBuf>,
closed: bool,
}
type Decoded = (PathBuf, Option<egui::ColorImage>);
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()));
if sender.send((path, image)).is_err() {
return;
}
ctx.request_repaint();
}
});
}
Self { queue, done }
}
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
}
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();
}
}
pub(crate) struct Gallery {
open: bool,
dir: Option<PathBuf>,
shots: Vec<Shot>,
scanned: bool,
scan: Option<Receiver<Vec<Shot>>>,
rescan: bool,
filter: Option<String>,
shown: Vec<usize>,
games: Vec<(String, usize)>,
thumbs: HashMap<PathBuf, Thumbnail>,
loader: Option<Loader>,
frame: u64,
under_settings: bool,
trashed: (Sender<Trashed>, Receiver<Trashed>),
}
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 {
pub(crate) fn close(&mut self) {
self.open = false;
self.loader = None;
self.thumbs.clear();
}
pub(crate) fn len(&self) -> usize {
self.shown.len()
}
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])
}
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();
}
}
enum ShotAction {
View(usize),
Copy(PathBuf),
Open(PathBuf),
ShowInFolder(PathBuf),
Convert(PathBuf),
Trash(PathBuf),
}
enum Line {
Heading(Option<(u16, u8, u8)>),
Tiles(std::ops::Range<usize>),
}
impl App {
pub(crate) fn showing_gallery(&self) -> bool {
screenshot::SUPPORTED && self.settings.view == View::Screenshots
}
fn shot_options(&self) -> ConvertOptions {
self.batch_options(Existing::Skip, true)
}
pub(crate) fn sync_gallery(&mut self, ctx: &egui::Context) {
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 {
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 });
}
}
}
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;
self.gallery.scan = None;
self.gallery.rescan = false;
}
}
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();
}
});
}
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"])
}
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);
}
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);
}
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));
}
});
});
}
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;
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),
}
}
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)
}
});
}
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);
}
}
}
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();
});
}
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;
}
});
}
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);
}
});
}
}
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
}
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);
});
}
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 t = theme::fade(ui, response.id, pointed || response.context_menu_opened());
let fill = theme::mix(
visuals.faint_bg_color,
visuals.widgets.inactive.weak_bg_fill,
t,
);
let edge = visuals.widgets.noninteractive.bg_stroke.color;
let edge = theme::mix(edge, theme::mix(edge, visuals.selection.bg_fill, 0.55), t);
let painter = ui.painter();
theme::surface(
painter,
rect,
f32::from(RADIUS),
fill,
edge,
visuals.dark_mode,
);
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);
}
}
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
}
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
}
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.";
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
}
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
}
);
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)",
"Game 0000-01-15 09-05-02",
"",
] {
assert_eq!(
parse_stem(other),
Name {
game: other,
taken: None,
number: 1
}
);
}
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));
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");
let monthly = Path::new("Some Game")
.join("2026-11")
.join("Some Game 2026-11-28 09-05-02.jxr");
assert_eq!(describe(&monthly), ("Some Game".into(), time, 1));
let month_only = Path::new("2026-11").join("Some Game 2026-11-28 09-05-02.jxr");
assert_eq!(describe(&month_only), ("Some Game".into(), time, 1));
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");
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"),
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
);
gallery.shots.clear();
gallery.refilter();
assert_eq!(gallery.filter, None);
let _ = std::fs::remove_dir_all(&dir);
}
}