Merge pull request #2599 from ludovic111/feat/launcher-screenshots

🤖 Agent: launcher-features-1 — item 6 (screenshots gallery); base retargeted to main after #2597 merged, merges cleanly, CI green.
This commit is contained in:
Ludovic Marie
2026-10-27 03:17:15 +01:00
committed by GitHub
9 changed files with 546 additions and 3 deletions
+21
View File
@@ -374,6 +374,27 @@ Move a world to the system's trash.
MCP: `worlds_delete`, needs `confirm: true`.
## `horizon-launcher screenshots list`
The screenshots, the newest first, with their files (the default).
horizon-launcher screenshots list
- `--instance`: The instance (default: the selected one)
MCP: `screenshots_list`.
## `horizon-launcher screenshots delete`
Move a screenshot to the system's trash.
horizon-launcher screenshots delete <SCREENSHOT>
- `SCREENSHOT`: Its file name, with or without .png
- `--instance`
MCP: `screenshots_delete`, needs `confirm: true`.
## `horizon-launcher multiplayer list`
The servers of the game's Multiplayer screen (the default).
+7
View File
@@ -89,6 +89,11 @@ The opening, then Play ([clip](docs/opening.webm)):
system's trash after a confirmation; **Open folder**. The same from the command line:
`horizon-launcher worlds [list|backup|copy|delete] [--instance <name>]`.
**Play** on a world starts the game straight into it.
- **Screenshots**: Home shows the selected instance's newest screenshots (what F2 saves in its
`screenshots/` folder) and all of them on request. Clicking one opens it over the window (← and →
step through) with **Copy** (the picture, to the clipboard), **Open**, **Show in folder** and
**Delete** (to the trash, after a confirmation). From the command line:
`horizon-launcher screenshots [list|delete] [--instance <name>]`.
- **Multiplayer**: Home lists the selected instance's servers, the game's own Multiplayer list
(`servers.dat`, each with the picture the game last saw). **Join** starts the game straight into
one; **Add server** and **Remove** (after a confirmation) change the file the game reads,
@@ -197,6 +202,8 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher instance version <instance> <tag|latest> keep it on one installed version, or follow updates
horizon-launcher worlds [list] [--instance <name>] an instance's worlds
horizon-launcher worlds backup|copy|delete <world> [--instance <name>] delete moves it to the trash
horizon-launcher screenshots [list] [--instance <name>] an instance's screenshots, the newest first
horizon-launcher screenshots delete <name> [--instance <name>] moves it to the trash
horizon-launcher multiplayer [list] [--instance <name>] the servers in an instance's Multiplayer list
horizon-launcher multiplayer add <address> [--name <name>] | remove <server>
horizon-launcher modpack [list] the imported packs and their coverage
+70
View File
@@ -214,6 +214,23 @@ enum WorldsCmd {
},
}
#[derive(Subcommand)]
enum ScreenshotsCmd {
/// The screenshots, the newest first, with their files (the default)
List {
/// The instance (default: the selected one)
#[arg(long)]
instance: Option<String>,
},
/// Move a screenshot to the system's trash
Delete {
/// Its file name, with or without .png
screenshot: String,
#[arg(long)]
instance: Option<String>,
},
}
#[derive(Subcommand)]
enum MultiplayerCmd {
/// The servers of the game's Multiplayer screen (the default)
@@ -442,6 +459,11 @@ enum Cmd {
#[command(subcommand)]
action: Option<WorldsCmd>,
},
/// The screenshots F2 took in an instance: list, delete
Screenshots {
#[command(subcommand)]
action: Option<ScreenshotsCmd>,
},
/// The servers in an instance's Multiplayer list (servers.dat): list, add, remove
Multiplayer {
#[command(subcommand)]
@@ -911,6 +933,10 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
action.unwrap_or(WorldsCmd::List { instance: None }),
as_json,
)?,
Cmd::Screenshots { action } => screenshots(
action.unwrap_or(ScreenshotsCmd::List { instance: None }),
as_json,
)?,
Cmd::Multiplayer { action } => multiplayer(
action.unwrap_or(MultiplayerCmd::List { instance: None }),
as_json,
@@ -1542,6 +1568,50 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
Ok(())
}
fn screenshots(action: ScreenshotsCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::screenshots;
let home = |instance: Option<String>| -> Result<PathBuf, String> {
Ok(match instance {
Some(name) => instances::find(&name)?.home,
None => instances::selected().home,
})
};
match action {
ScreenshotsCmd::List { instance } => {
let home = home(instance)?;
let shots = screenshots::list(&home);
if as_json {
json(
shots
.iter()
.map(|s| {
let millis = s
.taken
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64);
serde_json::json!({ "name": s.name, "path": s.path, "taken_ms": millis, "size": s.size })
})
.collect(),
);
} else if shots.is_empty() {
println!("No screenshots in {}", screenshots::folder(&home).display());
}
for s in shots.iter().filter(|_| !as_json) {
println!("{}", s.path.display());
}
}
ScreenshotsCmd::Delete {
screenshot,
instance,
} => {
let shot = screenshots::find(&home(instance)?, &screenshot)?;
screenshots::delete(&shot)?;
println!("{} is in the trash.", shot.name);
}
}
Ok(())
}
fn multiplayer(action: MultiplayerCmd, as_json: bool) -> Result<(), String> {
let home = |instance: Option<String>| -> Result<PathBuf, String> {
Ok(match instance {
+1
View File
@@ -28,6 +28,7 @@ pub const DESTRUCTIVE: &[&str] = &[
"data delete",
"worlds delete",
"multiplayer remove",
"screenshots delete",
];
/// Commands that send something or reach other people: only when the player asks.
+1
View File
@@ -12,6 +12,7 @@ pub mod modpacks;
pub mod mojang;
pub mod process;
pub mod proxy;
pub mod screenshots;
pub mod server_list;
pub mod servers;
pub mod signed;
+15
View File
@@ -22,6 +22,7 @@ mod mods_project;
mod multiplayer_page;
mod partner;
mod perf;
mod screenshots_page;
mod scrollbar;
mod servers_page;
mod theme;
@@ -235,6 +236,7 @@ struct Launcher {
/// Home's Worlds section, of the selected instance (`worlds_page.rs`).
worlds: worlds_page::Worlds,
multiplayer: multiplayer_page::Multiplayer,
screenshots: screenshots_page::Screenshots,
/// The name the game made up for an offline player (`horizon-player.txt`), for the top bar.
offline_name: Option<String>,
/// The player's servers, for the sidebar until the Servers page has read them.
@@ -396,6 +398,7 @@ impl Launcher {
instances: instances_page::Instances::default(),
worlds: worlds_page::Worlds::default(),
multiplayer: multiplayer_page::Multiplayer::default(),
screenshots: screenshots_page::Screenshots::default(),
offline_name: offline_name(),
side_servers: horizon_launcher::servers::list(),
art: art::Art::default(),
@@ -708,6 +711,7 @@ impl Launcher {
// The game saved: last played, sizes and pictures changed.
self.worlds.stale();
self.multiplayer.stale();
self.screenshots.stale();
if let Some((id, started)) = self.client_run.take() {
if let Err(e) = instances::record_play(&id, started.elapsed()) {
eprintln!("Play time not saved: {e}");
@@ -2200,6 +2204,9 @@ impl Launcher {
if let Some(servers) = self.multiplayer_section(cx) {
page = page.child(servers);
}
if let Some(shots) = self.screenshots_section(cx) {
page = page.child(shots);
}
if let Some(e) = self.client_error.clone() {
page = page.child(notice(e, &t));
}
@@ -3547,6 +3554,9 @@ impl Render for Launcher {
}
"escape" if this.servers_escape() => {}
"escape" if this.instance_escape() => {}
"escape" if this.screenshot_escape() => {}
"left" if this.screenshot_step(false) => {}
"right" if this.screenshot_step(true) => {}
_ => return,
}
cx.stop_propagation();
@@ -3610,6 +3620,11 @@ impl Render for Launcher {
if let Some(dialog) = self.instance_dialog(cx) {
root = root.child(dialog);
}
if self.page == Page::Play {
if let Some(viewer) = self.screenshot_viewer(cx) {
root = root.child(viewer);
}
}
if self.asking_consent() {
root = root.child(self.consent_screen(cx));
}
+103
View File
@@ -0,0 +1,103 @@
//! An instance's screenshots: the pictures F2 saves into `screenshots/` in its game folder
//! (vanilla's `Screenshot.grab`, named `<yyyy-MM-dd_HH.mm.ss>.png`).
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
#[derive(Clone, Debug, PartialEq)]
pub struct Shot {
pub path: PathBuf,
/// Its file name, the id commands take.
pub name: String,
/// When the file was written.
pub taken: SystemTime,
pub size: u64,
}
/// The folder F2 saves into for the game folder `home`.
pub fn folder(home: &Path) -> PathBuf {
home.join("screenshots")
}
/// The pictures in `home`'s screenshots folder, the newest first.
pub fn list(home: &Path) -> Vec<Shot> {
let mut shots: Vec<Shot> = fs::read_dir(folder(home))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| {
let path = e.path();
let picture = path
.extension()
.and_then(|x| x.to_str())
.is_some_and(|x| ["png", "jpg", "jpeg"].contains(&x.to_ascii_lowercase().as_str()));
let meta = e.metadata().ok().filter(|m| m.is_file() && picture)?;
Some(Shot {
name: e.file_name().to_string_lossy().into_owned(),
taken: meta.modified().unwrap_or(SystemTime::UNIX_EPOCH),
size: meta.len(),
path,
})
})
.collect();
// Same second: the game names the next ones `_2`, `_3`..., which sort after the first.
shots.sort_by(|a, b| b.taken.cmp(&a.taken).then_with(|| b.name.cmp(&a.name)));
shots
}
/// The screenshot a command names: its file name, with or without the extension.
pub fn find(home: &Path, query: &str) -> Result<Shot, String> {
list(home)
.into_iter()
.find(|s| s.name == query || Path::new(&s.name).file_stem().is_some_and(|n| n == query))
.ok_or_else(|| format!("No screenshot {query} in {}", folder(home).display()))
}
/// Moves the screenshot to the system's trash.
pub fn delete(shot: &Shot) -> Result<(), String> {
crate::worlds::to_trash(&shot.path)
.map_err(|e| format!("Could not move {} to the trash: {e}", shot.name))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn lists_pictures_newest_first() {
let home =
std::env::temp_dir().join(format!("horizon-launcher-shots-{}", std::process::id()));
let _ = fs::remove_dir_all(&home);
let dir = folder(&home);
fs::create_dir_all(dir.join("not-a-picture.png")).unwrap();
let base = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
for (name, age) in [
("2026-10-25_20.00.01.png", 60),
("2026-10-27_09.15.42.png", 0),
("2026-10-27_09.15.42_2.png", 0),
("notes.txt", 0),
("Edited.JPG", 30),
] {
let path = dir.join(name);
fs::write(&path, b"x").unwrap();
let file = fs::File::options().write(true).open(&path).unwrap();
file.set_modified(base - Duration::from_secs(age)).unwrap();
}
let names: Vec<_> = list(&home).into_iter().map(|s| s.name).collect();
assert_eq!(
names,
[
"2026-10-27_09.15.42_2.png",
"2026-10-27_09.15.42.png",
"Edited.JPG",
"2026-10-25_20.00.01.png"
]
);
assert_eq!(find(&home, "2026-10-25_20.00.01").unwrap().size, 1);
assert_eq!(find(&home, "Edited.JPG").unwrap().name, "Edited.JPG");
assert!(find(&home, "notes.txt").is_err());
assert!(list(&home.join("none")).is_empty());
fs::remove_dir_all(&home).unwrap();
}
}
+322
View File
@@ -0,0 +1,322 @@
//! The selected instance's screenshots on Home (`horizon_launcher::screenshots`): the newest as
//! thumbnails, all of them on request, and a viewer (← and → step through) with Copy, Open,
//! Show in folder and Delete (to the trash, after a confirmation).
use super::*;
use gpui::{ClipboardItem, Image, ImageFormat};
use horizon_launcher::screenshots::{self, Shot};
use std::path::PathBuf;
/// Thumbnails shown before "Show all".
const FIRST: usize = 8;
const THUMB_W: f32 = 196.;
const THUMB_H: f32 = THUMB_W * 9. / 16.;
#[derive(Default)]
pub(super) struct Screenshots {
home: Option<PathBuf>,
list: Vec<Shot>,
fresh: bool,
all: bool,
/// The picture open in the viewer, by its place in `list`.
viewing: Option<usize>,
confirm_delete: bool,
/// What the last action did, or why it failed.
note: Option<Result<String, String>>,
}
impl Screenshots {
/// Read again on the next frame: the game may have taken new ones.
pub(super) fn stale(&mut self) {
self.fresh = false;
}
}
impl Launcher {
fn load_screenshots(&mut self, home: PathBuf) {
if self.screenshots.home.as_ref() != Some(&home) {
self.screenshots = Screenshots {
home: Some(home.clone()),
..Screenshots::default()
};
}
if !self.screenshots.fresh {
// One directory listing: cheap enough while drawing.
self.screenshots.list = screenshots::list(&home);
self.screenshots.fresh = true;
let last = self.screenshots.list.len().checked_sub(1);
self.screenshots.viewing = self
.screenshots
.viewing
.and_then(|i| last.map(|l| i.min(l)));
}
}
/// Escape closes the viewer. Whether it did.
pub(super) fn screenshot_escape(&mut self) -> bool {
let open = self.screenshots.viewing.take().is_some();
self.screenshots.confirm_delete = false;
open
}
/// ← and → in the viewer: the newer and the older picture. Whether it moved.
pub(super) fn screenshot_step(&mut self, older: bool) -> bool {
let Some(i) = self.screenshots.viewing else {
return false;
};
let next = match older {
true => (i + 1 < self.screenshots.list.len()).then_some(i + 1),
false => i.checked_sub(1),
};
if let Some(n) = next {
self.screenshots.viewing = Some(n);
self.screenshots.confirm_delete = false;
self.screenshots.note = None;
}
true
}
fn copy_screenshot(&mut self, shot: &Shot, cx: &mut Context<Self>) {
let format = match shot.path.extension().and_then(|x| x.to_str()) {
Some(x) if x.eq_ignore_ascii_case("png") => ImageFormat::Png,
_ => ImageFormat::Jpeg,
};
self.screenshots.note = Some(match std::fs::read(&shot.path) {
Ok(bytes) => {
cx.write_to_clipboard(ClipboardItem::new_image(&Image::from_bytes(format, bytes)));
Ok("Copied to the clipboard.".into())
}
Err(e) => Err(format!("Could not read {}: {e}", shot.name)),
});
}
fn delete_screenshot(&mut self, shot: &Shot) {
self.screenshots.confirm_delete = false;
self.screenshots.note =
Some(screenshots::delete(shot).map(|()| format!("{} moved to the trash.", shot.name)));
self.screenshots.stale();
}
/// Home's Screenshots section, for the selected instance; None while it has none.
pub(super) fn screenshots_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let home = self.selected_instance()?.home.clone();
self.load_screenshots(home.clone());
let list = self.screenshots.list.clone();
if list.is_empty() {
return None;
}
let shown = if self.screenshots.all {
list.len()
} else {
FIRST
};
let folder = screenshots::folder(&home);
let mut buttons = div().flex().items_center().gap(px(6.));
if list.len() > FIRST {
let label = match self.screenshots.all {
true => "Show fewer".to_string(),
false => format!("Show all {}", list.len()),
};
buttons = buttons.child(button("screenshots-all", label, Kind::Ghost, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.screenshots.all = !this.screenshots.all;
cx.notify();
}),
));
}
buttons = buttons.child(
button("screenshots-folder", "Open folder", Kind::Ghost, &t)
.on_click(move |_, _, cx| cx.open_with_system(&folder)),
);
let header = div()
.flex()
.items_center()
.justify_between()
.mb(px(4.))
.child(section_title("Screenshots", "image", &t))
.child(buttons);
let grid = div().flex().flex_wrap().gap(px(10.)).children(
list.into_iter().take(shown).enumerate().map(|(i, shot)| {
div()
.id(SharedString::from(format!("screenshot-{i}")))
.flex_none()
.w(px(THUMB_W))
.h(px(THUMB_H))
.border_2()
.border_color(t.outline)
.bg(t.well)
.cursor_pointer()
.hover(|s| s.border_color(t.accent))
.child(
gpui::img(shot.path.clone())
.size_full()
.object_fit(gpui::ObjectFit::Cover),
)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.screenshots.viewing = Some(i);
this.screenshots.confirm_delete = false;
this.screenshots.note = None;
cx.notify();
}))
}),
);
let mut section = div().flex().flex_col().gap(px(8.)).child(header);
if self.screenshots.viewing.is_none() {
if let Some(Err(e)) = &self.screenshots.note {
section = section.child(notice(e.clone(), &t));
}
}
Some(section.child(grid))
}
/// The viewer over the whole window, while a picture is open.
pub(super) fn screenshot_viewer(&mut self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
let t = self.theme;
let i = self.screenshots.viewing?;
let shot = self.screenshots.list.get(i)?.clone();
let count = self.screenshots.list.len();
let taken: chrono::DateTime<chrono::Local> = shot.taken.into();
let step = |id: &'static str, label: &'static str, older: bool, can: bool| {
let b = button(id, label, Kind::Ghost, &t);
if can {
b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.screenshot_step(older);
cx.notify();
}))
} else {
disabled(b)
}
};
let mut actions = div().flex().items_center().gap(px(6.));
if self.screenshots.confirm_delete {
let gone = shot.clone();
actions =
actions
.child(
text(theme::CAPTION)
.text_color(t.danger)
.child("Move it to the trash?"),
)
.child(button("screenshot-keep", "Keep", Kind::Ghost, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.screenshots.confirm_delete = false;
cx.notify();
}),
))
.child(
button("screenshot-trash", "Move to trash", Kind::Secondary, &t).on_click(
cx.listener(move |this, _: &ClickEvent, _, cx| {
this.delete_screenshot(&gone);
cx.notify();
}),
),
);
} else {
let (copy, open, show) = (shot.clone(), shot.path.clone(), shot.path.clone());
actions =
actions
.child(button("screenshot-copy", "Copy", Kind::Ghost, &t).on_click(
cx.listener(move |this, _: &ClickEvent, _, cx| {
this.copy_screenshot(&copy, cx);
cx.notify();
}),
))
.child(
button("screenshot-open", "Open", Kind::Ghost, &t)
.on_click(move |_, _, cx| cx.open_with_system(&open)),
)
.child(
button("screenshot-show", "Show in folder", Kind::Ghost, &t)
.on_click(move |_, _, cx| cx.reveal_path(&show)),
)
.child(
button("screenshot-delete", "Delete", Kind::Ghost, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.screenshots.confirm_delete = true;
cx.notify();
}),
),
);
}
let note = match &self.screenshots.note {
Some(Ok(m)) => Some(text(theme::CAPTION).text_color(t.muted).child(m.clone())),
Some(Err(e)) => Some(text(theme::CAPTION).text_color(t.danger).child(e.clone())),
None => None,
};
let top = div()
.flex()
.items_center()
.gap(px(12.))
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.child(
blocks::pixel(17., FontWeight::MEDIUM)
.text_color(t.ink)
.child(taken.format("%Y-%m-%d %H:%M:%S").to_string()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(format!("{} · {} of {count}", shot.name, i + 1)),
),
)
.child(step("screenshot-newer", "← Newer", false, i > 0))
.child(step("screenshot-older", "Older →", true, i + 1 < count))
.child(
button("screenshot-close", "Close", Kind::Secondary, &t).on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.screenshot_escape();
cx.notify();
},
)),
);
let bottom = div()
.flex()
.items_center()
.justify_between()
.gap(px(12.))
.child(div().children(note))
.child(actions);
Some(
div()
.id("screenshot-viewer")
.absolute()
.top_0()
.left_0()
.size_full()
.flex()
.flex_col()
.gap(px(14.))
.px(px(32.))
.py(px(24.))
.bg(t.page.opacity(0.96))
.on_scroll_wheel(|_, _, cx| cx.stop_propagation())
.occlude()
.child(top)
.child(
// The picture fills what the bars leave, whatever its own size.
div()
.relative()
.flex_1()
.min_h_0()
.border_2()
.border_color(t.outline)
.bg(t.well)
.child(
gpui::img(shot.path.clone())
.absolute()
.top_0()
.left_0()
.size_full()
.object_fit(gpui::ObjectFit::Contain),
),
)
.child(bottom),
)
}
}
+6 -3
View File
@@ -251,6 +251,11 @@ fn rename_level(world: &Path, name: &str) -> std::io::Result<()> {
/// Moves the world to the system's trash, where the player can still get it back.
pub fn delete(world: &World) -> Result<(), String> {
to_trash(&world.path).map_err(|e| format!("Could not move {} to the trash: {e}", world.name))
}
/// Moves a file or folder to the system's trash.
pub(crate) fn to_trash(path: &Path) -> Result<(), trash::Error> {
#[allow(unused_mut)]
let mut trash = trash::TrashContext::default();
// The crate's default on macOS asks Finder through AppleScript, which needs the player to
@@ -260,9 +265,7 @@ pub fn delete(world: &World) -> Result<(), String> {
&mut trash,
trash::macos::DeleteMethod::NsFileManager,
);
trash
.delete(&world.path)
.map_err(|e| format!("Could not move {} to the trash: {e}", world.name))
trash.delete(path)
}
#[cfg(test)]