Merge origin/main into refactor/horizon-items

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 03:49:04 +01:00
33 changed files with 2883 additions and 87 deletions
@@ -592,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> {
pose,
num("maxCrossbowChageDuration"),
num("ticksUsingItem"),
false,
);
}
Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => {
+8 -1
View File
@@ -12707,7 +12707,14 @@ impl<'a> Game<'a> {
level,
session_lock: None,
audio,
music: Default::default(),
music: {
// The manager starts with the saved option (MusicManager's constructor).
let mut music = horizon_client::music::MusicManager::default();
music.frequency = horizon_client::music::MusicFrequency::parse(
&settings.file.name("musicFrequency"),
);
music
},
ambience: Default::default(),
sound_paused: false,
cart_sounds: HashSet::new(),
@@ -145,9 +145,42 @@ impl Game<'_> {
.iter()
.find(|m| m.id == id)
.map_or(0.0, |m| m.eye_y() - m.position.y),
_ => 0.0,
// ArmorStand.getDefaultDimensions: a marker's are empty, a small
// stand's are BABY_DIMENSIONS, whose eye height is 0.9875F.
Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) {
Some(a) if a.marker => 0.0,
Some(a) if a.small => f64::from(0.9875f32),
_ => self.type_eye_height(&self.target_type(t)),
},
// Entity.getEyeHeight: the type's dimensions.
_ => self.type_eye_height(&self.target_type(t)),
}
}
/// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`,
/// read once: a float, widened as `Entity.getEyeY` does.
fn type_eye_height(&self, ty: &str) -> f64 {
static EYE_HEIGHTS: std::sync::OnceLock<std::collections::HashMap<String, f64>> =
std::sync::OnceLock::new();
EYE_HEIGHTS
.get_or_init(|| {
std::fs::read(self.options.resources.join("entity-types.json"))
.ok()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
.and_then(|v| {
v.as_object().map(|o| {
o.iter()
.filter_map(|(k, t)| {
Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32)))
})
.collect()
})
})
.unwrap_or_default()
})
.get(ty)
.copied()
.unwrap_or(0.0)
}
/// EntityAnchorArgument.Anchor.apply.
pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] {
match s.entity {
@@ -467,9 +500,10 @@ impl Game<'_> {
"positioned" if c.has("as") => targets(self)?
.into_iter()
.filter_map(|t| {
// withPosition keeps the anchor (only `positioned <pos>`
// resets it to the feet).
Some(Source {
pos: self.target_position(t)?,
eyes: false,
..s
})
})
+6 -1
View File
@@ -3,7 +3,7 @@
use super::Game;
use horizon_client::{
blocks::Fluid,
music::{BackgroundMusic, Music, Situation},
music::{BackgroundMusic, Music, MusicFrequency, Situation},
sound_engine::TickContext,
};
@@ -11,6 +11,11 @@ impl Game<'_> {
/// `Minecraft.tick` -> `MusicManager.tick`, once per client tick.
pub(super) fn tick_music(&mut self) {
let (music, volume) = self.situational_music();
// Options.musicFrequency's listener: MusicManager.setMinutesBetweenSongs.
let frequency = MusicFrequency::parse(&self.settings.file.name("musicFrequency"));
if frequency != self.music.frequency {
self.music.set_frequency(frequency, music.as_ref());
}
// LevelLoadingScreen: no new track before the player is in the world.
let loading = self.title.is_none() && self.player.is_none() && self.win.is_none();
self.music
+2 -1
View File
@@ -118,8 +118,9 @@ impl Style {
(x, y, w): (f32, f32, f32),
label: &Text,
hover: bool,
active: bool,
) {
ui::button(batch, atlas, x, y, w, 20.0, label, true, hover);
ui::button(batch, atlas, x, y, w, 20.0, label, active, hover);
}
pub fn slider(
&self,
+32 -1
View File
@@ -468,6 +468,10 @@ fn max_workers() -> u32 {
}
impl Item {
/// False for a setting whose system is not in Horizon yet (`Opt::available`).
fn available(self) -> bool {
!matches!(self, Item::Vanilla(o) if !o.available())
}
/// On/off settings and their value.
pub fn switch(self, s: &Settings) -> Option<bool> {
let g = &s.horizon;
@@ -510,6 +514,9 @@ impl Item {
}
}
pub fn set_slider(self, s: &mut Settings, v: f32) {
if !self.available() {
return;
}
match self {
Item::Vanilla(o) => o.set_slider(s, v),
Item::Horizon(h) => h.set_slider(s, v),
@@ -517,6 +524,9 @@ impl Item {
self.touched(s);
}
pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) {
if !self.available() {
return;
}
match self {
Item::Vanilla(o) => o.cycle(s, back, framebuffer),
Item::Horizon(h) => h.cycle(s, back),
@@ -689,6 +699,7 @@ impl GraphicsUi {
})
.collect();
let mut index = 0;
let mut tooltip = None;
for wd in &widgets {
let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0)
&& (!wd.list || (cursor.1 >= top && cursor.1 < bottom));
@@ -700,6 +711,13 @@ impl GraphicsUi {
continue;
}
let label = item.label(s);
let live = item.available();
if hover && !live {
tooltip = Some(atlas.font.split(
&Text::literal("This feature is not yet available in Horizon."),
170.0,
));
}
match item.slider(s) {
Some(value) => STYLE.slider(
batch,
@@ -709,7 +727,14 @@ impl GraphicsUi {
value,
hover || self.dragging == Some(item),
),
None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover),
None => STYLE.button(
batch,
atlas,
(wd.x, wd.y, wd.w),
&label,
hover && live,
live,
),
}
STYLE.description(
batch,
@@ -732,6 +757,7 @@ impl GraphicsUi {
(wd.x, wd.y, wd.w),
&Text::literal(label),
hover,
true,
);
}
}
@@ -751,6 +777,9 @@ impl GraphicsUi {
Level::Advanced => "Graphics: Advanced",
};
STYLE.title(batch, atlas, &Text::literal(title));
if let Some(lines) = tooltip {
ui::tooltip(batch, atlas, &lines, cursor);
}
}
/// A press (or a drag with `drag`) at `(x, y)`.
pub fn click(
@@ -788,6 +817,8 @@ impl GraphicsUi {
}
return match wd.target {
Target::Button(action) => vec![Action::ButtonClick, action],
// A disabled control does nothing: no sound, no preset change.
Target::Item(item) if !item.available() => Vec::new(),
Target::Item(item) => {
if item.slider(s).is_some() {
self.dragging = Some(item);
+27 -12
View File
@@ -248,18 +248,24 @@ pub enum ArmPose {
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm.
pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) {
/// `AnimationUtils.swingWeaponDown`: the main arm swings down, the other
/// one hangs and bobs.
pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32, left_main: bool) {
let attack2 = (swing * PI).msin();
let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
let (main, off) = if left_main {
("left_arm", "right_arm")
} else {
("right_arm", "left_arm")
};
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15);
p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5);
p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4;
p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4;
p.xrot(main, -1.884_955_8 + (age * 0.09).mcos() * 0.15);
p.xrot(off, -0.0 + (age * 0.19).mcos() * 0.5);
p.get(main)[3] += attack2 * 2.2 - attack * 0.4;
p.get(off)[3] += attack2 * 1.2 - attack * 0.4;
bob(p, "right_arm", age, 1.0);
bob(p, "left_arm", age, -1.0);
}
@@ -286,6 +292,8 @@ pub struct Hum {
pub using_item: bool,
/// The arm the current swing moves (`Some(true)` for the right one).
pub swing_right_arm: Option<bool>,
/// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it.
pub left_main: bool,
}
impl Hum {
pub fn new(right: ArmPose, left: ArmPose) -> Self {
@@ -303,6 +311,7 @@ impl Hum {
swim: 0.0,
using_item: false,
swing_right_arm: None,
left_main: false,
}
}
}
@@ -315,7 +324,7 @@ impl ArmPose {
}
}
/// `AnimationUtils.animateCrossbowHold`.
fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
pub(super) fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
let (hold, shoot) = if in_right {
("right_arm", "left_arm")
} else {
@@ -327,7 +336,7 @@ fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
p.xrot(shoot, -1.5 + hx);
}
/// `AnimationUtils.animateCrossbowCharge`.
fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) {
pub(super) fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) {
let (hold, pull) = if in_right {
("right_arm", "left_arm")
} else {
@@ -418,13 +427,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
pose_arm(p, h.right, true, h);
}
}
// setupAttackAnimation (WHACK swing with the right arm).
// setupAttackAnimation (WHACK swing with the arm of the swinging hand).
let hx = p.get("head")[3];
let swing = s.swing;
let swing_left = h.swing_right_arm.map_or(h.left_main, |right| !right);
if swing > 0.0 && h.weapon_swing {
swing_weapon_down(p, swing, s.age);
swing_weapon_down(p, swing, s.age, h.left_main);
} else if swing > 0.0 {
let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2;
let mut body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2;
if swing_left {
body_y = -body_y;
}
p.yrot("body", body_y);
let age_scale = if s.baby { 0.5 } else { 1.0 };
{
@@ -444,7 +457,7 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
let eased = 1.0 - (1.0 - swing).powi(4);
let aa = (eased * PI).msin();
let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75;
let r = p.get("right_arm");
let r = p.get(if swing_left { "left_arm" } else { "right_arm" });
r[3] -= aa * 1.2 + bb;
r[4] += body_y * 2.0;
r[5] += (swing * PI).msin() * -0.4;
@@ -652,6 +665,7 @@ pub fn setup(
} else {
Hum::new(main, ArmPose::Empty)
};
h.left_main = m.main_arm_left();
h.zombie = Some(m.ai.aggressive);
h.holding = m.extra.main_hand.is_some();
h.crouching = m.extra.crouching;
@@ -715,6 +729,7 @@ pub fn setup(
h.swim = m.extra.swim.amount(s.partial);
h.using_item = m.extra.using_item > 0;
h.swing_right_arm = m.extra.swing_right_arm;
h.left_main = m.main_arm_left();
humanoid(p, s, &h);
if m.ai.aggressive && !bow {
// SkeletonModel melee pose.
+8 -3
View File
@@ -681,7 +681,12 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) {
p.xrot("right_arm", x + a * 1.2 - b * 0.4);
p.xrot("left_arm", x + a * 1.2 - b * 0.4);
} else {
// swingWeaponDown (right-handed).
// swingWeaponDown: the main arm swings down.
let (main, off) = if m.main_arm_left() {
("left_arm", "right_arm")
} else {
("right_arm", "left_arm")
};
let swing = s.swing;
let a2 = (swing * PI).msin();
let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
@@ -690,11 +695,11 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) {
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot(
"right_arm",
main,
-1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4),
);
p.xrot(
"left_arm",
off,
-0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4),
);
}
+31 -21
View File
@@ -431,7 +431,14 @@ pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) {
} else {
PiglinPose::Default
};
piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32);
piglin_pose(
p,
s,
pose,
25.0,
m.extra.using_item as f32,
m.main_arm_left(),
);
}
/// `PiglinArmPose`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -443,11 +450,19 @@ pub enum PiglinPose {
CrossbowCharge,
AdmiringItem,
}
/// `PiglinModel.setupAnim` for a piglin facing right-handed.
pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) {
use super::anim::{ArmPose, Hum, humanoid};
/// `PiglinModel.setupAnim`; `left` when the piglin's main arm is the left one.
pub fn piglin_pose(
p: &mut Poses,
s: &State,
pose: PiglinPose,
max_charge: f32,
ticks: f32,
left: bool,
) {
use super::anim::{ArmPose, Hum, crossbow_charge, crossbow_hold, humanoid};
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.weapon_swing = pose == PiglinPose::MeleeWeapon;
h.left_main = left;
h.charge = (max_charge, ticks);
humanoid(p, s, &h);
ears(p, s);
@@ -474,27 +489,22 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32,
p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5;
p.get("body")[1] += (dance * 40.0).msin() * 0.35;
}
PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8),
PiglinPose::CrossbowHold => {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
p.xrot("right_arm", -PI / 2.0 + hx + 0.1);
p.xrot("left_arm", -1.5 + hx);
}
PiglinPose::CrossbowCharge => {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
p.xrot("left_arm", -0.970_796_35);
let alpha = ticks.clamp(0.0, max_charge) / max_charge;
p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4));
let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35);
p.xrot("left_arm", x);
// holdWeaponHigh
PiglinPose::MeleeWeapon if s.swing == 0.0 => {
p.xrot(if left { "left_arm" } else { "right_arm" }, -1.8)
}
PiglinPose::CrossbowHold => crossbow_hold(p, hx, hy, !left),
PiglinPose::CrossbowCharge => crossbow_charge(p, max_charge, ticks, !left),
PiglinPose::AdmiringItem => {
p.xrot("head", 0.5);
p.yrot("head", 0.0);
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
if left {
p.yrot("right_arm", -0.5);
p.xrot("right_arm", -0.9);
} else {
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
}
}
_ => {}
}
+36
View File
@@ -67,6 +67,7 @@ pub enum Opt {
ReducedDebugInfo,
HighContrast,
ShowSubtitles,
MusicFrequency,
NotificationDisplayTime,
Narrator,
TextBackground,
@@ -172,6 +173,10 @@ impl Opt {
| Opt::MonochromeLogo
| Opt::RotateWithMinecarts
| Opt::HighContrastBlockOutlines
// Saved, but nothing in rendering reads them yet.
| Opt::ChunkFade
| Opt::ImprovedTransparency
| Opt::ChunkBuilder
)
}
fn file_key(self) -> Option<&'static str> {
@@ -192,6 +197,7 @@ impl Opt {
Opt::NarratorHotkey => "narratorHotkey",
Opt::RotateWithMinecarts => "rotateWithMinecart",
Opt::HighContrastBlockOutlines => "highContrastBlockOutline",
Opt::MusicFrequency => "musicFrequency",
_ => return None,
})
}
@@ -248,6 +254,7 @@ impl Opt {
Opt::ReducedDebugInfo => "options.reducedDebugInfo",
Opt::HighContrast => "options.accessibility.high_contrast",
Opt::ShowSubtitles => "options.showSubtitles",
Opt::MusicFrequency => "options.music_frequency",
Opt::NotificationDisplayTime => "options.notifications.display_time",
Opt::Narrator => "options.narrator",
Opt::TextBackground => "options.accessibility.text_background",
@@ -578,6 +585,11 @@ impl Opt {
Opt::ReducedDebugInfo => on_off(s.reduced_debug_info),
Opt::HighContrast => on_off(s.high_contrast),
Opt::ShowSubtitles => on_off(s.show_subtitles),
Opt::MusicFrequency => tr([
"options.music_frequency.default",
"options.music_frequency.frequent",
"options.music_frequency.constant",
][s.file.int("musicFrequency").clamp(0, 2) as usize]),
Opt::ForceUnicode => on_off(s.force_unicode),
Opt::JapaneseGlyphs => on_off(s.japanese_glyphs),
Opt::PadEnabled => on_off(s.controller.enabled),
@@ -747,6 +759,11 @@ impl Opt {
Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info,
Opt::HighContrast => s.high_contrast = !s.high_contrast,
Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles,
Opt::MusicFrequency => {
let n = next(s.file.int("musicFrequency").clamp(0, 2) as u8, 3);
s.file
.set("musicFrequency", crate::options_file::V::Int(i32::from(n)));
}
Opt::ForceUnicode => s.force_unicode = !s.force_unicode,
Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs,
Opt::PadEnabled => s.controller.enabled = !s.controller.enabled,
@@ -1412,6 +1429,9 @@ impl OptionsUi {
let others: Vec<Opt> = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect();
rows.extend(pairs(&others));
rows.extend(pairs(&[Opt::ShowSubtitles]));
// SoundOptionsScreen: Music Frequency starts the next row (with
// Music Toast, not in Horizon yet).
rows.extend(pairs(&[Opt::MusicFrequency]));
rows
}
Page::Controls => {
@@ -2533,6 +2553,21 @@ impl OptionsUi {
if opt == Opt::Preset {
apply_preset(s);
}
if opt == Opt::HighContrast {
// Options.highContrast: the built-in pack follows the option.
let on = s.resource_packs.iter().any(|id| id == "high_contrast");
if on != s.high_contrast {
s.resource_packs.retain(|id| id != "high_contrast");
if s.high_contrast {
s.resource_packs.push("high_contrast".into());
}
// PackSelectionScreen reads the repository each time it
// opens: the next one starts from this selection.
self.pack_selection = s.resource_packs.clone();
self.pack_screen = None;
events.push(Event::Packs(s.resource_packs.clone()));
}
}
events.push(Event::Changed);
}
Act::Extra(item) => {
@@ -2701,6 +2736,7 @@ impl OptionsUi {
{
let ids = p.commit();
s.resource_packs = ids.clone();
self.pack_selection = ids.clone();
events.push(Event::Packs(ids));
}
}
+108
View File
@@ -54,6 +54,7 @@ Start the client.
- `--world`: Open or create this world (a folder under saves) at once
- `--creative`: Creative mode for a new world
- `--join`: Join a friend's world with its invite code
- `--server`: Join this server at once: an address, or a server of the list by name or position
- `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --server-thread
MCP: `play`, then the `game_*` tools.
@@ -320,6 +321,113 @@ Make Play start this instance.
MCP: `instance_select`.
## `horizon-launcher instance version`
Keep an instance on one installed Horizon version, or "latest" to follow updates again.
horizon-launcher instance version <INSTANCE> <VERSION>
- `INSTANCE`
MCP: `instance_version`.
## `horizon-launcher worlds list`
The worlds: name, mode, version, last played and size (the default).
horizon-launcher worlds list
- `--instance`: The instance (default: the selected one)
MCP: `worlds_list`.
## `horizon-launcher worlds backup`
Zip a world into the instance's backups/ folder, as the game's Make Backup does.
horizon-launcher worlds backup <WORLD>
- `WORLD`: Its folder or name
- `--instance`
MCP: `worlds_backup`.
## `horizon-launcher worlds copy`
Copy a world beside it, as "<name> (1)".
horizon-launcher worlds copy <WORLD>
- `WORLD`
- `--instance`
MCP: `worlds_copy`.
## `horizon-launcher worlds delete`
Move a world to the system's trash.
horizon-launcher worlds delete <WORLD>
- `WORLD`
- `--instance`
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).
horizon-launcher multiplayer list
- `--instance`: The instance (default: the selected one)
MCP: `multiplayer_list`.
## `horizon-launcher multiplayer add`
Add a server to the list.
horizon-launcher multiplayer add <ADDRESS>
- `ADDRESS`: Its address, as in the game's Add Server (host or host:port)
- `--name`: Its name in the list (default: Minecraft Server)
- `--instance`
MCP: `multiplayer_add`.
## `horizon-launcher multiplayer remove`
Remove a server from the list: its position from 1, name or address.
horizon-launcher multiplayer remove <SERVER>
- `SERVER`
- `--instance`
MCP: `multiplayer_remove`, needs `confirm: true`.
## `horizon-launcher modpack list`
The imported packs and their coverage (the default).
+220 -6
View File
@@ -70,6 +70,15 @@ dependencies = [
"equator",
]
[[package]]
name = "android_system_properties"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
dependencies = [
"libc",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -919,6 +928,17 @@ dependencies = [
"zeroize",
]
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"iana-time-zone",
"num-traits",
"windows-link 0.2.1",
]
[[package]]
name = "cipher"
version = "0.4.4"
@@ -981,6 +1001,15 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "cobs"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "cocoa"
version = "0.25.0"
@@ -1635,6 +1664,18 @@ dependencies = [
"winreg",
]
[[package]]
name = "embedded-io"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
[[package]]
name = "embedded-io"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]]
name = "encoding_rs"
version = "0.8.42"
@@ -2354,7 +2395,7 @@ dependencies = [
"wayland-protocols-plasma",
"windows 0.61.3",
"windows-core 0.61.2",
"windows-numerics",
"windows-numerics 0.2.0",
"windows-registry 0.5.3",
"x11-clipboard",
"x11rb",
@@ -2693,6 +2734,8 @@ dependencies = [
name = "horizon-launcher"
version = "0.2.0"
dependencies = [
"base64",
"chrono",
"clap",
"dirs 5.0.1",
"flate2",
@@ -2708,6 +2751,7 @@ dependencies = [
"horizon-release-sign",
"horizon-telemetry",
"horizon-theme",
"horizon-world",
"image",
"keyring",
"objc2-app-kit",
@@ -2720,6 +2764,7 @@ dependencies = [
"sha1",
"sha2 0.10.9",
"tar",
"trash",
"ureq",
"winresource",
"zip",
@@ -2801,6 +2846,21 @@ dependencies = [
name = "horizon-theme"
version = "0.1.0"
[[package]]
name = "horizon-world"
version = "0.1.0"
dependencies = [
"flate2",
"horizon-core",
"libm",
"lz4_flex",
"postcard",
"serde",
"serde_json",
"sha2 0.10.9",
"xxhash-rust",
]
[[package]]
name = "http"
version = "1.5.0"
@@ -2907,6 +2967,30 @@ dependencies = [
"tracing",
]
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.61.2",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.3.0"
@@ -3425,6 +3509,12 @@ dependencies = [
"num-traits",
]
[[package]]
name = "lz4_flex"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226"
[[package]]
name = "mac"
version = "0.1.1"
@@ -4263,6 +4353,18 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "postcard"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
dependencies = [
"cobs",
"embedded-io 0.4.0",
"embedded-io 0.6.1",
"serde",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -6187,6 +6289,24 @@ dependencies = [
"once_cell",
]
[[package]]
name = "trash"
version = "5.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317"
dependencies = [
"chrono",
"libc",
"log",
"objc2",
"objc2-foundation",
"once_cell",
"percent-encoding",
"scopeguard",
"urlencoding",
"windows 0.62.2",
]
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -6367,6 +6487,12 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "usvg"
version = "0.45.1"
@@ -6820,11 +6946,23 @@ version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-collections 0.2.0",
"windows-core 0.61.2",
"windows-future",
"windows-future 0.2.1",
"windows-link 0.1.3",
"windows-numerics",
"windows-numerics 0.2.0",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
@@ -6837,7 +6975,7 @@ dependencies = [
"rayon",
"thiserror 2.0.21",
"windows 0.61.3",
"windows-future",
"windows-future 0.2.1",
]
[[package]]
@@ -6849,6 +6987,15 @@ dependencies = [
"windows-core 0.61.2",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.57.0"
@@ -6874,6 +7021,19 @@ dependencies = [
"windows-strings 0.4.2",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-future"
version = "0.2.1"
@@ -6882,7 +7042,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
"windows-threading",
"windows-threading 0.1.0",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
@@ -6951,6 +7122,16 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-registry"
version = "0.4.0"
@@ -6991,6 +7172,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.3.1"
@@ -7009,6 +7199,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
@@ -7111,6 +7310,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
@@ -7423,6 +7631,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xxhash-rust"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
[[package]]
name = "y4m"
version = "0.8.0"
+7
View File
@@ -37,6 +37,13 @@ horizon-mods = { path = "../crates/horizon-mods", features = ["index"] }
horizon-release-sign = { path = "../crates/horizon-release-sign" }
# Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md).
horizon-telemetry = { path = "../crates/horizon-telemetry" }
# level.dat and servers.dat (the worlds and server lists of instances)
horizon-world = { path = "../crates/horizon-world" }
# Deleting a world moves it to the system's trash
trash = "5"
# Backup names carry the local time, as vanilla's do
base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["clock"] }
# The session file's random name.
getrandom = "0.3"
# Players' heads on the Servers page, from the default skins in the player's own game files (already
+29 -1
View File
@@ -78,7 +78,28 @@ The opening, then Play ([clip](docs/opening.webm)):
data folder, so renaming moves nothing. Every instance follows the launcher's data collection
answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by
group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and
Open folder.
Open folder. The Instance row shows its play time and when it was last played: every run started
from the window or `horizon-launcher play` adds to it (`instance list` shows it too). Each
instance plays the launcher's version, which follows updates, unless the Play page's version
picker keeps it on another installed one (to keep an old world on the version it was made
with); picking the version marked "follows updates" lets it follow again.
- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played,
size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does
(`<date>_<time>_<folder>.zip`); **Copy** puts "<name> (1)" beside it; **Delete** moves it to the
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,
keeping every field the launcher doesn't show and the servers joined with Direct Connection. The
same from the command line: `horizon-launcher multiplayer [list|add|remove] [--instance <name>]`
and `horizon-launcher play --server <address or name>`.
- **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer.
Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux,
@@ -178,6 +199,13 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher instance create <name> [--copy <instance>] empty, or a copy of one's worlds, options and packs
horizon-launcher instance rename|icon|group <instance> <value> icon: a block or item name, #rrggbb or none
horizon-launcher instance select <instance> make Play start it
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
horizon-launcher modpack import <pack> a .mrpack, CurseForge zip or instance folder
horizon-launcher modpack port <pack> [--from <dir>] [--version <tag>] get the jars and carry them over
+291 -3
View File
@@ -4,6 +4,7 @@ use clap::{Parser, Subcommand};
use horizon_launcher::account::{self, Accounts};
use horizon_launcher::backend::{self, Release};
use horizon_launcher::instances;
use horizon_launcher::server_list;
use std::io::{IsTerminal, Write};
use std::path::PathBuf;
use std::process::Command;
@@ -180,6 +181,80 @@ enum InstanceCmd {
},
/// Make Play start this instance
Select { instance: String },
/// Keep an instance on one installed Horizon version, or "latest" to follow updates again
Version { instance: String, version: String },
}
#[derive(Subcommand)]
enum WorldsCmd {
/// The worlds: name, mode, version, last played and size (the default)
List {
/// The instance (default: the selected one)
#[arg(long)]
instance: Option<String>,
},
/// Zip a world into the instance's backups/ folder, as the game's Make Backup does
Backup {
/// Its folder or name
world: String,
#[arg(long)]
instance: Option<String>,
},
/// Copy a world beside it, as "<name> (1)"
Copy {
world: String,
#[arg(long)]
instance: Option<String>,
},
/// Move a world to the system's trash
Delete {
world: String,
#[arg(long)]
instance: Option<String>,
},
}
#[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)
List {
/// The instance (default: the selected one)
#[arg(long)]
instance: Option<String>,
},
/// Add a server to the list
Add {
/// Its address, as in the game's Add Server (host or host:port)
address: String,
/// Its name in the list (default: Minecraft Server)
#[arg(long)]
name: Option<String>,
#[arg(long)]
instance: Option<String>,
},
/// Remove a server from the list: its position from 1, name or address
Remove {
server: String,
#[arg(long)]
instance: Option<String>,
},
}
#[derive(Subcommand)]
@@ -300,6 +375,9 @@ enum Cmd {
/// Join a friend's world with its invite code
#[arg(long)]
join: Option<String>,
/// Join this server at once: an address, or a server of the list by name or position
#[arg(long, conflicts_with_all = ["world", "join"])]
server: Option<String>,
/// An extra argument for the game, passed through as-is (repeatable), for example
/// --server-thread
#[arg(long = "arg", value_name = "ARG", allow_hyphen_values = true)]
@@ -376,6 +454,21 @@ enum Cmd {
#[command(subcommand)]
action: Option<InstanceCmd>,
},
/// An instance's single-player worlds: list them, back one up, copy or delete it
Worlds {
#[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)]
action: Option<MultiplayerCmd>,
},
/// Modpacks: import a Java pack, see its coverage report, port what this computer can and
/// play it as its own profile (docs/modpacks.md)
Modpack {
@@ -645,13 +738,14 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
world,
creative,
join,
server,
arg,
} => {
let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?;
let instance = match instance {
Some(name) => instances::find(&name)?,
None => instances::selected(),
};
let mut cmd = backend::client(&instance.resolve_version(version.as_deref())?)?;
instances::apply(&mut cmd, &instance)?;
if let Some(code) = join {
backend::join_friend(&mut cmd, &code)?;
@@ -659,11 +753,21 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
if let Some(world) = world {
cmd.arg("--world").arg(world);
}
if let Some(server) = server {
let list = server_list::List::load(&instance.home);
let ip = server_list::find(&list, &server).map_or(server, |(_, s)| s.ip);
cmd.arg("--server").arg(ip);
}
if creative {
cmd.arg("--creative");
}
cmd.args(arg);
attached(cmd)?
let started = std::time::Instant::now();
let played = attached(cmd);
if let Err(e) = instances::record_play(&instance.id, started.elapsed()) {
eprintln!("Play time not saved: {e}");
}
played?
}
Cmd::Server {
dir,
@@ -825,6 +929,18 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
println!("Horizon is in the applications menu.");
}
}
Cmd::Worlds { action } => worlds(
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,
)?,
Cmd::Instance { action } => instance(action.unwrap_or(InstanceCmd::List), as_json)?,
Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?,
Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?,
@@ -1385,6 +1501,8 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
serde_json::json!({
"id": i.id, "name": i.name, "kind": format!("{:?}", i.kind).to_lowercase(),
"home": i.home, "icon": i.icon, "group": i.group, "selected": selected,
"version": i.version, "played_secs": i.played.as_secs(),
"last_played_ms": i.last_played.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as u64),
})
};
let line = |i: &instances::Instance, selected: bool| {
@@ -1394,8 +1512,17 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
.as_ref()
.map(|g| format!(" [{g}]"))
.unwrap_or_default();
let pinned = i
.version
.as_ref()
.map(|v| format!(" {v}"))
.unwrap_or_default();
let played = match i.last_played {
Some(_) => format!(" {} played", instances::play_time(i.played)),
None => String::new(),
};
println!(
"{mark} {} ({}){group}\n {}",
"{mark} {} ({}){pinned}{group}{played}\n {}",
i.name,
i.id,
i.home.display()
@@ -1430,6 +1557,167 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
changed(instances::edit(&instance, |m| m.group = group)?)
}
InstanceCmd::Select { instance } => changed(instances::select(&instance)?),
InstanceCmd::Version { instance, version } => {
let pin = match version.as_str() {
"latest" => None,
tag => Some(backend::resolve_version(Some(tag))?),
};
changed(instances::edit(&instance, |m| m.version = pin)?)
}
}
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 {
Some(name) => instances::find(&name)?.home,
None => instances::selected().home,
})
};
match action {
MultiplayerCmd::List { instance } => {
let home = home(instance)?;
let servers = server_list::List::load(&home).servers();
if as_json {
json(
servers
.iter()
.map(|s| serde_json::json!({ "name": s.name, "address": s.ip, "icon": s.icon.is_some() }))
.collect(),
);
} else if servers.is_empty() {
println!("No servers in {}", home.join("servers.dat").display());
}
for (i, s) in servers.iter().enumerate().filter(|_| !as_json) {
println!("{}. {} ({})", i + 1, s.name, s.ip);
}
}
MultiplayerCmd::Add {
address,
name,
instance,
} => {
let home = home(instance)?;
let mut list = server_list::List::load(&home);
list.add(name.as_deref().unwrap_or(""), &address)?;
list.save(&home)?;
println!("Added {}.", address.trim());
}
MultiplayerCmd::Remove { server, instance } => {
let home = home(instance)?;
let mut list = server_list::List::load(&home);
let (i, _) = server_list::find(&list, &server)?;
let gone = list.remove(i)?;
list.save(&home)?;
println!("Removed {} ({}).", gone.name, gone.ip);
}
}
Ok(())
}
fn worlds(action: WorldsCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::worlds::{self, World};
let home = |instance: Option<String>| -> Result<PathBuf, String> {
Ok(match instance {
Some(name) => instances::find(&name)?.home,
None => instances::selected().home,
})
};
let value = |w: &World| {
let millis = w
.last_played
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64);
serde_json::json!({
"folder": w.folder, "name": w.name, "mode": w.mode, "version": w.version,
"last_played_ms": millis, "size": w.size, "path": w.path, "icon": w.icon,
})
};
match action {
WorldsCmd::List { instance } => {
let home = home(instance)?;
let all = worlds::list(&home);
if as_json {
json(all.iter().map(value).collect());
} else if all.is_empty() {
println!("No worlds in {}", home.join("saves").display());
}
for w in all.iter().filter(|_| !as_json) {
let version = w.version.as_deref().unwrap_or("unknown version");
let mb = w.size as f64 / 1_000_000.0;
println!(
"{} ({})\n {}, {version}, {mb:.1} MB",
w.name, w.folder, w.mode
);
}
}
WorldsCmd::Backup { world, instance } => {
let home = home(instance)?;
let zip = worlds::backup(&home, &worlds::find(&home, &world)?)?;
match as_json {
true => json(serde_json::json!({ "backup": zip })),
false => println!("{}", zip.display()),
}
}
WorldsCmd::Copy { world, instance } => {
let home = home(instance)?;
let copy = worlds::copy(&worlds::find(&home, &world)?)?;
match as_json {
true => json(value(&copy)),
false => println!("Copied to {} ({})", copy.name, copy.folder),
}
}
WorldsCmd::Delete { world, instance } => {
let home = home(instance)?;
let w = worlds::find(&home, &world)?;
worlds::delete(&w)?;
println!("{} is in the trash.", w.name);
}
}
Ok(())
}
+3
View File
@@ -26,6 +26,9 @@ pub const DESTRUCTIVE: &[&str] = &[
"servers forget",
"account sign-out",
"data delete",
"worlds delete",
"multiplayer remove",
"screenshots delete",
];
/// Commands that send something or reach other people: only when the player asks.
+71
View File
@@ -14,6 +14,7 @@ use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// The default instance's id: the game's home itself.
pub const DEFAULT: &str = "horizon";
@@ -86,6 +87,20 @@ pub struct Meta {
pub icon: Option<Icon>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
/// The Horizon version this instance plays, kept when newer ones are installed. None: the
/// launcher's own version, which follows updates.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Seconds played in it, every run started by the launcher (the window or `play`) added up.
#[serde(default, skip_serializing_if = "is_zero")]
pub played_secs: u64,
/// When its last run ended, in seconds since 1970.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_played: Option<u64>,
}
fn is_zero(n: &u64) -> bool {
*n == 0
}
/// `instances.json`: each instance's choices, by id.
@@ -121,6 +136,27 @@ pub struct Instance {
pub home: PathBuf,
pub icon: Option<Icon>,
pub group: Option<String>,
/// Its pinned Horizon version, if any (`Meta::version`).
pub version: Option<String>,
pub played: Duration,
pub last_played: Option<SystemTime>,
}
impl Instance {
/// The installed version this instance plays: its pinned one, else `requested` (the
/// command line's `--version`) or the launcher's (`backend::resolve_version`).
pub fn resolve_version(&self, requested: Option<&str>) -> Result<String, String> {
match (requested, &self.version) {
(None, Some(pinned)) => backend::resolve_version(Some(pinned)).map_err(|_| {
format!(
"{} plays {pinned}, which is not installed: install it, or horizon-launcher \
instance version \"{}\" latest",
self.name, self.name
)
}),
_ => backend::resolve_version(requested),
}
}
}
/// The instances, by the default game home and the launcher's data folder: Horizon first, then
@@ -172,6 +208,11 @@ fn list_in(game_home: &Path, data: &Path) -> Vec<Instance> {
name: meta.name.unwrap_or(name),
icon: meta.icon,
group: meta.group,
version: meta.version,
played: Duration::from_secs(meta.played_secs),
last_played: meta
.last_played
.map(|s| UNIX_EPOCH + Duration::from_secs(s)),
id,
kind,
work,
@@ -373,6 +414,36 @@ fn edit_in(
find_in(&list_in(game_home, data), &instance.id)
}
/// Adds a finished run of the game to the instance's play time (by id: a renamed instance keeps
/// it).
pub fn record_play(id: &str, played: Duration) -> Result<(), String> {
record_play_in(&backend::data_dir(), id, played, SystemTime::now())
}
fn record_play_in(
data: &Path,
id: &str,
played: Duration,
ended: SystemTime,
) -> Result<(), String> {
let mut store = Store::load(data);
let meta = store.instances.entry(id.to_string()).or_default();
meta.played_secs = meta.played_secs.saturating_add(played.as_secs());
meta.last_played = ended.duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs());
store.save(data)
}
/// "12 min", "3 h 05 min", "140 h": the play time as players read it.
pub fn play_time(played: Duration) -> String {
let minutes = played.as_secs() / 60;
match (minutes / 60, minutes % 60) {
(0, 0) => "under a minute".into(),
(0, m) => format!("{m} min"),
(h, m) if h < 100 => format!("{h} h {m:02} min"),
(h, _) => format!("{h} h"),
}
}
/// Turns the game's command into this instance: its own game folder, and a pack's mods. The
/// player's answers that hold everywhere follow it in: data collection and No AI as the
/// launcher has them, and options.txt and the offline name when it has none yet.
+57
View File
@@ -201,3 +201,60 @@ fn icons_are_a_texture_name_or_a_colour() {
assert_eq!(Icon::Texture("stone".into()).texture(&root), None);
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn an_instance_keeps_its_own_version_until_it_follows_updates_again() {
let root = scratch("version");
let (home, data) = (root.join("horizon"), root.join("launcher"));
player_home(&home);
create_in(&home, &data, "Old world", None).unwrap();
let pinned = edit_in(&home, &data, "Old world", |m| {
m.version = Some("v0.1.0".into())
})
.unwrap();
assert_eq!(pinned.version.as_deref(), Some("v0.1.0"));
// Renaming keeps it; the other instances follow the launcher's version.
let renamed = edit_in(&home, &data, "old-world", |m| m.name = Some("Older".into())).unwrap();
assert_eq!(renamed.version.as_deref(), Some("v0.1.0"));
assert!(list_in(&home, &data)
.iter()
.filter(|i| i.id != "old-world")
.all(|i| i.version.is_none()));
let follows = edit_in(&home, &data, "Older", |m| m.version = None).unwrap();
assert_eq!(follows.version, None);
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn play_time_adds_up_per_instance_and_survives_a_rename() {
let root = scratch("play-time");
let (home, data) = (root.join("home"), root.join("data"));
fs::create_dir_all(home.join(OWN).join("skyblock")).unwrap();
let ended = UNIX_EPOCH + Duration::from_secs(1_800_000_000);
record_play_in(&data, "skyblock", Duration::from_secs(25 * 60 + 10), ended).unwrap();
edit_in(&home, &data, "skyblock", |m| m.name = Some("Sky".into())).unwrap();
let later = ended + Duration::from_secs(3600);
record_play_in(&data, "skyblock", Duration::from_secs(40 * 60), later).unwrap();
let all = list_in(&home, &data);
let sky = find_in(&all, "Sky").unwrap();
assert_eq!(sky.played, Duration::from_secs(65 * 60 + 10));
assert_eq!(sky.last_played, Some(later));
let default = find_in(&all, DEFAULT).unwrap();
assert_eq!(
(default.played, default.last_played),
(Duration::ZERO, None)
);
// Never played: nothing written for it.
let text = fs::read_to_string(data.join(FILE)).unwrap();
assert!(!text.contains("horizon"), "{text}");
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn play_time_reads_as_minutes_then_hours() {
let t = |s| play_time(Duration::from_secs(s));
assert_eq!(t(59), "under a minute");
assert_eq!(t(12 * 60 + 59), "12 min");
assert_eq!(t(3 * 3600 + 5 * 60), "3 h 05 min");
assert_eq!(t(140 * 3600 + 7 * 60), "140 h");
}
+53 -11
View File
@@ -77,6 +77,25 @@ impl Launcher {
list.iter().find(|i| i.id == id).or(list.first())
}
/// The installed version `instance` plays: its own, else the launcher's.
pub(super) fn version_of(&self, instance: &Instance) -> Option<&String> {
match &instance.version {
Some(own) => self.installed.iter().find(|t| *t == own),
None => self.launcher_version(),
}
}
/// Keeps the selected instance on `tag`, or lets it follow the launcher's version.
pub(super) fn pin_version(&mut self, tag: Option<String>) {
let Some(id) = self.selected_instance().map(|i| i.id.clone()) else {
return;
};
match instances::edit(&id, |m| m.version = tag) {
Ok(_) => self.reload_instances(),
Err(e) => self.client_error = Some(e),
}
}
fn select_instance(&mut self, instance: &Instance) {
self.settings.instance =
(instance.kind != InstanceKind::Default).then(|| instance.id.clone());
@@ -154,15 +173,6 @@ impl Launcher {
cx: &mut Context<Self>,
) -> Vec<AnyElement> {
let t = self.theme;
let tag = self.selected().cloned();
let prepared = tag.as_deref().is_some_and(backend::is_prepared);
let status = if tag.is_none() {
"No version installed"
} else if prepared {
"Ready"
} else {
"Needs preparing"
};
let selected = self.selected_instance().map(|i| i.id.clone());
let on_packs = self.page == Page::Mods && self.mods.on_modpacks();
let mut out = Vec::new();
@@ -174,10 +184,18 @@ impl Launcher {
out.push(heading(g.to_uppercase()).into_any_element());
}
}
let tag = self.version_of(&i).cloned();
let prepared = tag.as_deref().is_some_and(backend::is_prepared);
let (open, sub) = match i.kind {
InstanceKind::Default | InstanceKind::Own => (
self.page == Page::Play && selected.as_ref() == Some(&i.id),
status.to_string(),
match (&tag, &i.version) {
(None, Some(own)) => format!("{own} is not installed"),
(None, None) => "No version installed".into(),
(Some(_), _) if !prepared => "Needs preparing".into(),
(Some(tag), Some(_)) => format!("Ready · {tag}"),
(Some(_), None) => "Ready".into(),
},
),
InstanceKind::Port => {
let slug = &i.id["port:".len()..];
@@ -566,13 +584,37 @@ impl Launcher {
Some(index_row(
n,
"Instance",
Some(div().child(instance.name.clone()).into_any_element()),
Some(
div()
.flex()
.items_baseline()
.gap(px(10.))
.child(instance.name.clone())
.child(
text(theme::CAPTION)
.text_color(t.muted)
.child(played_line(&instance)),
)
.into_any_element(),
),
Some(actions.into_any_element()),
&t,
))
}
}
/// "3 h 05 min in total · last played today", or "Not played yet".
fn played_line(instance: &Instance) -> String {
match instance.last_played {
Some(when) => format!(
"{} in total · last played {}",
instances::play_time(instance.played),
worlds_page::ago(when)
),
None => "Not played yet".into(),
}
}
/// The first letter or digit of a name, for an icon without a picture.
fn initial(name: &str) -> String {
name.chars()
+3
View File
@@ -12,8 +12,11 @@ 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;
pub mod sources;
pub mod tailscale;
pub mod telemetry;
pub mod worlds;
+98 -10
View File
@@ -19,12 +19,15 @@ mod mcp;
mod modpacks_page;
mod mods_page;
mod mods_project;
mod multiplayer_page;
mod partner;
mod perf;
mod screenshots_page;
mod scrollbar;
mod servers_page;
mod theme;
mod titlebar;
mod worlds_page;
use gpui::{
actions, div, ease_out_quint, prelude::*, px, relative, size, Animation, AnimationExt,
@@ -185,6 +188,10 @@ struct Launcher {
friend_focused: bool,
friend_focus: FocusHandle,
joining: Option<String>,
/// Where the next start goes at once: `--world <folder>` or `--server <address>`.
quick_play: Option<(&'static str, String)>,
/// The instance the running game plays and when it started: its play time grows on exit.
client_run: Option<(String, Instant)>,
/// Settings' Game arguments field: the line, whether it has focus, and its focus handle.
args_input: String,
args_focused: bool,
@@ -226,6 +233,10 @@ struct Launcher {
mods: mods_page::Mods,
/// The instances, for the sidebar and Play, and their dialog (`instances_page.rs`).
instances: instances_page::Instances,
/// 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.
@@ -361,6 +372,8 @@ impl Launcher {
friend_focused: false,
friend_focus: cx.focus_handle(),
joining: None,
quick_play: None,
client_run: None,
collection: collection::Collection::load(),
agents: agents_page::AgentsUi::default(),
playing: None,
@@ -383,6 +396,9 @@ impl Launcher {
starting_pack: None,
mods: mods_page::Mods::new(cx),
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(),
@@ -542,11 +558,20 @@ impl Launcher {
}
self.accounts = Accounts::load();
// A pack's Play button plays that pack; Play plays the selected instance.
let profile = match self.starting_pack.take() {
let (profile, run) = match self.starting_pack.take() {
Some(work) => {
horizon_launcher::modpacks::apply_profile(&mut cmd, &work)
let id = instances::list()
.into_iter()
.find(|i| i.work == work)
.map(|i| i.id);
let applied =
horizon_launcher::modpacks::apply_profile(&mut cmd, &work);
(applied, id)
}
None => {
let instance = instances::selected();
(instances::apply(&mut cmd, &instance), Some(instance.id))
}
None => instances::apply(&mut cmd, &instances::selected()),
};
if let Err(e) = profile {
self.client_error = Some(e);
@@ -557,10 +582,16 @@ impl Launcher {
self.client_error = Some(e);
}
}
if let Some((flag, value)) = self.quick_play.take() {
cmd.arg(flag).arg(value);
}
backend::append_game_args(&mut cmd);
self.client_home = cmd.get_current_dir().map(|d| d.to_path_buf());
match backend::spawn(Job::Client, cmd, self.tx.clone()) {
Ok(r) => self.client = Some(r),
Ok(r) => {
self.client = Some(r);
self.client_run = run.map(|id| (id, Instant::now()));
}
Err(e) => self.client_error = Some(e),
}
}
@@ -677,6 +708,16 @@ impl Launcher {
}
Job::Client => {
self.client = None;
// 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}");
}
self.reload_instances();
}
// The run's own game folder: an instance's or a pack's keeps its reports.
let home = self.client_home.clone().unwrap_or_else(backend::game_home);
let report = self
@@ -764,7 +805,15 @@ impl Launcher {
switched
}
/// The version Play starts: the selected instance's own, else the launcher's.
fn selected(&self) -> Option<&String> {
self.selected_instance()
.and_then(|i| self.version_of(i))
.or_else(|| self.launcher_version())
}
/// The launcher's version: what instances without one of their own play.
fn launcher_version(&self) -> Option<&String> {
self.settings
.selected
.as_ref()
@@ -1850,16 +1899,20 @@ impl Launcher {
.absolute()
.top(px(66.))
.right_0()
.w(px(240.))
.w(px(300.))
.p(px(6.))
.border_2()
.border_color(t.outline)
.bg(t.surface)
.flex()
.flex_col();
// Picking a version keeps the selected instance on it; the launcher's own version
// (newest unless chosen otherwise on Versions) follows updates.
let follows = self.launcher_version().cloned();
for tag in &self.installed {
let selected = self.selected() == Some(tag);
let tag = tag.clone();
let latest = follows.as_ref() == Some(&tag);
menu = menu.child(
div()
.id(SharedString::from(format!("pick-{tag}")))
@@ -1875,12 +1928,20 @@ impl Launcher {
.cursor_pointer()
.hover(move |s| s.bg(t.plate_soft))
.child(tag.clone())
.when(selected, |d| {
d.child(div().size(px(6.)).rounded_full().bg(t.accent))
})
.child(
div()
.flex()
.items_center()
.gap(px(8.))
.when(latest, |d| {
d.child(caps("follows updates").text_color(t.muted))
})
.when(selected, |d| {
d.child(div().size(px(6.)).rounded_full().bg(t.accent))
}),
)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.settings.selected = Some(tag.clone());
this.settings.save();
this.pin_version((!latest).then(|| tag.clone()));
this.picker_open = false;
cx.notify();
})),
@@ -2137,6 +2198,15 @@ impl Launcher {
page = page.child(notice(e, &t));
}
page = page.child(rows);
if let Some(worlds) = self.worlds_section(cx) {
page = page.child(worlds);
}
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));
}
@@ -3034,6 +3104,16 @@ impl Launcher {
)
}
/// Plays the selected instance straight into a world (`--world`) or a server (`--server`):
/// flags every Horizon release takes.
pub(crate) fn quick_play(&mut self, flag: &'static str, value: String) {
self.quick_play = Some((flag, value));
self.play();
if self.starting_client.is_none() {
self.quick_play = None;
}
}
fn join_friend(&mut self) {
if horizon_friends::invite::parse(&self.friend_code).is_none() {
return;
@@ -3474,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();
@@ -3537,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));
}
+10 -3
View File
@@ -25,7 +25,7 @@ struct Session {
/// The tools the session runs itself, under their CLI names: they keep a process (the game, a
/// server) or a sign-in going between calls. Every other CLI command is generated (cli_tools.rs).
fn session_tools() -> Value {
let version = json!({ "type": "string", "description": "An installed version tag such as v2026.10.13. Default: the selected version." });
let version = json!({ "type": "string", "description": "An installed version tag such as v2026.10.13. Default: the selected version (play: the instance's own first)." });
let none = json!({ "type": "object", "properties": {} });
json!([
{ "name": "play", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world. CLI: horizon-launcher play",
@@ -34,6 +34,7 @@ fn session_tools() -> Value {
"world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." },
"creative": { "type": "boolean", "description": "Creative mode for a new world." },
"join": { "type": "string", "description": "Join a friend's world with its invite code. Only when the player asks." },
"server": { "type": "string", "description": "Join this server at once: an address, or a server of the instance's list (multiplayer_list) by name or position. Only when the player asks." },
"offscreen": { "type": "boolean", "description": "Render without showing a window (game_screenshot still works)." },
"arg": { "type": "array", "items": { "type": "string" }, "description": "Extra game arguments, passed through as-is (for example \"--server-thread\")." } } } },
{ "name": "server", "description": "Start a Horizon dedicated server. It runs until server_stop or the end of this MCP session. Requires agreeing to the Minecraft EULA. CLI: horizon-launcher server",
@@ -68,12 +69,12 @@ impl Session {
if self.client.as_ref().is_some_and(|c| c.finished().is_none()) {
return Err("The client is already running.".into());
}
let tag = backend::resolve_version(arg_str(args, "version"))?;
let mut cmd = backend::client(&tag)?;
let instance = match arg_str(args, "instance") {
Some(name) => instances::find(name)?,
None => instances::selected(),
};
let tag = instance.resolve_version(arg_str(args, "version"))?;
let mut cmd = backend::client(&tag)?;
instances::apply(&mut cmd, &instance)?;
cmd.args(game_tools::control_args());
if let Some(world) = arg_str(args, "world") {
@@ -87,6 +88,12 @@ impl Session {
if let Some(code) = arg_str(args, "join") {
backend::join_friend(&mut cmd, code)?;
}
if let Some(server) = arg_str(args, "server") {
let list = horizon_launcher::server_list::List::load(&instance.home);
let ip = horizon_launcher::server_list::find(&list, server)
.map_or_else(|_| server.to_string(), |(_, s)| s.ip);
cmd.arg("--server").arg(ip);
}
if let Some(extra) = args.get("arg").and_then(Value::as_array) {
cmd.args(extra.iter().filter_map(Value::as_str));
}
+7 -1
View File
@@ -116,7 +116,13 @@ impl Launcher {
}
fn play_pack(&mut self, work: PathBuf) {
let Some(tag) = self.selected().cloned() else {
// The pack's instance plays its own version, if it has one.
let pack = self.instances.list.iter().find(|i| i.work == work);
let Some(tag) = pack
.and_then(|i| self.version_of(i))
.or_else(|| self.launcher_version())
.cloned()
else {
return;
};
if self.client.is_some() || self.starting_client.is_some() {
+251
View File
@@ -0,0 +1,251 @@
//! The selected instance's server list on Home (`horizon_launcher::server_list`, the game's own
//! `servers.dat`): each server with the picture the game last saw, Join (the game starts straight
//! into it), Remove after a confirmation, and a line to add one.
use super::*;
use gpui::{Image, ImageFormat};
use horizon_launcher::server_list::{self, Server};
use servers_page::Field;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Default)]
pub(super) struct Multiplayer {
/// The game folder the list is of, and the list as last read with each picture decoded.
home: Option<PathBuf>,
list: Vec<(Server, Option<Arc<Image>>)>,
fresh: bool,
adding: bool,
confirm_remove: Option<usize>,
error: Option<String>,
}
impl Multiplayer {
/// Read again on the next frame: the game may have changed its list.
pub(super) fn stale(&mut self) {
self.fresh = false;
}
}
impl Launcher {
fn load_servers(&mut self, home: PathBuf) {
if self.multiplayer.home.as_ref() != Some(&home) {
self.multiplayer = Multiplayer {
home: Some(home.clone()),
..Multiplayer::default()
};
}
if self.multiplayer.fresh {
return;
}
// A few servers and their 64×64 pictures: small enough to read while drawing.
self.multiplayer.list = server_list::List::load(&home)
.servers()
.into_iter()
.map(|s| {
let icon = s
.icon
.clone()
.map(|png| Arc::new(Image::from_bytes(ImageFormat::Png, png)));
(s, icon)
})
.collect();
self.multiplayer.fresh = true;
}
fn edit_servers(&mut self, edit: impl FnOnce(&mut server_list::List) -> Result<(), String>) {
let Some(home) = self.multiplayer.home.clone() else {
return;
};
let mut list = server_list::List::load(&home);
self.multiplayer.error = edit(&mut list).and_then(|()| list.save(&home)).err();
self.multiplayer.confirm_remove = None;
self.multiplayer.stale();
}
/// Enter in the address field, or Add.
pub(super) fn add_server(&mut self) {
let name = self.servers.value(Field::ServerName).to_string();
let address = self.servers.value(Field::ServerAddress).to_string();
self.edit_servers(|list| list.add(&name, &address));
if self.multiplayer.error.is_none() {
self.servers.text(Field::ServerName).clear();
self.servers.text(Field::ServerAddress).clear();
self.multiplayer.adding = false;
}
}
/// Home's Multiplayer section, for the selected instance.
pub(super) fn multiplayer_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let home = self.selected_instance()?.home.clone();
self.load_servers(home);
let header = div()
.flex()
.items_center()
.justify_between()
.mb(px(4.))
.child(section_title("Multiplayer", "server", &t))
.child(
button("server-add", "Add server", Kind::Ghost, &t).on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.multiplayer.adding = !this.multiplayer.adding;
this.multiplayer.error = None;
if this.multiplayer.adding {
this.servers.focus_soon = Some(Field::ServerAddress);
}
cx.notify();
},
)),
);
let mut section = div().flex().flex_col().gap(px(8.)).child(header);
if let Some(e) = self.multiplayer.error.clone() {
section = section.child(notice(e, &t));
}
if self.multiplayer.adding {
section = section.child(
plate(&t)
.flex()
.items_center()
.gap(px(8.))
.px(px(14.))
.py(px(10.))
.child(self.field(Field::ServerName, "Minecraft Server", 220., cx))
.child(self.field(Field::ServerAddress, "play.example.com", 300., cx))
.child(button("server-save", "Add", Kind::Secondary, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.add_server();
cx.notify();
}),
)),
);
}
let list = self.multiplayer.list.clone();
if list.is_empty() && !self.multiplayer.adding {
section = section.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("No servers yet: add one here or in the game's Multiplayer screen."),
);
}
for (i, (server, icon)) in list.into_iter().enumerate() {
section = section.child(self.server_row(i, server, icon, cx));
}
Some(section)
}
fn server_row(
&mut self,
i: usize,
server: Server,
icon: Option<Arc<Image>>,
cx: &mut Context<Self>,
) -> Div {
let t = self.theme;
let picture = div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(48.))
.border_2()
.border_color(t.outline)
.bg(t.well);
let picture = match icon {
Some(image) => picture.child(gpui::img(image).size(px(44.))),
None => picture.child(blocks::icon("server", 22., t.muted)),
};
let mut actions = div().flex().items_center().gap(px(6.));
if self.multiplayer.confirm_remove == Some(i) {
actions = actions
.child(
text(theme::CAPTION)
.text_color(t.danger)
.child("Remove it from the list?"),
)
.child(
button(
SharedString::from(format!("server-keep-{i}")),
"Keep",
Kind::Ghost,
&t,
)
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.multiplayer.confirm_remove = None;
cx.notify();
})),
)
.child(
button(
SharedString::from(format!("server-remove-{i}")),
"Remove",
Kind::Secondary,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.edit_servers(|list| list.remove(i).map(|_| ()));
cx.notify();
},
)),
);
} else {
let ip = server.ip.clone();
let busy = self.client.is_some() || self.starting_client.is_some();
let join = button(
SharedString::from(format!("server-join-{i}")),
"Join",
Kind::Secondary,
&t,
);
let join = if busy { disabled(join) } else { join };
actions = actions
.child(
join.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.quick_play("--server", ip.clone());
cx.notify();
})),
)
.child(
button(
SharedString::from(format!("server-delete-{i}")),
"Remove",
Kind::Ghost,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.multiplayer.confirm_remove = Some(i);
cx.notify();
},
)),
);
}
plate(&t)
.flex()
.items_center()
.gap(px(14.))
.px(px(14.))
.py(px(10.))
.child(picture)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.child(
blocks::pixel(15., FontWeight::MEDIUM)
.text_color(t.ink)
.truncate()
.child(server.name.clone()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(server.ip.clone()),
),
)
.child(actions)
}
}
+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),
)
}
}
+159
View File
@@ -0,0 +1,159 @@
//! The player's server list, `servers.dat` in an instance's game folder: the game's Multiplayer
//! screen reads and writes the same file. Its format is vanilla's (`ServerList.load`/`save`,
//! `ServerData.read`/`write`): uncompressed NBT, `servers` a list of compounds with `name`, `ip`,
//! an optional `icon` (a PNG in base64), `acceptTextures`, `acceptedCodeOfConduct` and `hidden`.
//! The launcher only adds and removes entries: every other field of every entry is written back
//! as it was read.
use base64::Engine;
use horizon_world::nbt::{self, Compound, JavaString, Limits, NamedTag, Tag};
use std::fs;
use std::path::Path;
const FILE: &str = "servers.dat";
#[derive(Clone, Debug, PartialEq)]
pub struct Server {
pub name: String,
pub ip: String,
/// The server's picture, as the game last saw it (PNG).
pub icon: Option<Vec<u8>>,
}
/// The entries as they are in the file, the hidden ones (servers joined with Direct
/// Connection) too.
pub struct List {
entries: Vec<Compound>,
}
fn key(k: &str) -> JavaString {
JavaString::from(k)
}
fn text(entry: &Compound, k: &str) -> String {
match entry.get(&key(k)) {
Some(Tag::String(s)) => s.to_string_lossy(),
_ => String::new(),
}
}
fn hidden(entry: &Compound) -> bool {
matches!(entry.get(&key("hidden")), Some(Tag::Byte(b)) if *b != 0)
}
impl List {
/// The list in `home`; empty when there is none or it can't be read, as the game does.
pub fn load(home: &Path) -> List {
let entries = fs::read(home.join(FILE))
.ok()
.and_then(|bytes| nbt::read_named(&bytes, Limits::default()).ok())
.and_then(|(root, _)| match root.tag.get("servers") {
Some(Tag::List(list)) => Some(
list.iter()
.filter_map(|t| match t {
Tag::Compound(c) => Some(c.clone()),
_ => None,
})
.collect(),
),
_ => None,
})
.unwrap_or_default();
List { entries }
}
/// The servers the Multiplayer screen shows, in its order.
pub fn servers(&self) -> Vec<Server> {
self.entries
.iter()
.filter(|e| !hidden(e))
.map(|e| Server {
name: text(e, "name"),
ip: text(e, "ip"),
icon: Some(text(e, "icon"))
.filter(|s| !s.is_empty())
.and_then(|s| base64::engine::general_purpose::STANDARD.decode(s).ok()),
})
.collect()
}
/// Adds a server at the end of the shown ones, as the game's Add Server does.
pub fn add(&mut self, name: &str, ip: &str) -> Result<(), String> {
let (name, ip) = (name.trim(), ip.trim());
if ip.is_empty() {
return Err("A server needs an address.".into());
}
let name = if name.is_empty() {
"Minecraft Server"
} else {
name
};
let at = self
.entries
.iter()
.rposition(|e| !hidden(e))
.map_or(0, |i| i + 1);
let entry: Compound = [
(key("name"), Tag::String(name.into())),
(key("ip"), Tag::String(ip.into())),
(key("hidden"), Tag::Byte(0)),
]
.into_iter()
.collect();
self.entries.insert(at, entry);
Ok(())
}
/// Removes the `index`th shown server.
pub fn remove(&mut self, index: usize) -> Result<Server, String> {
let server = self
.servers()
.into_iter()
.nth(index)
.ok_or_else(|| format!("There is no server {}.", index + 1))?;
let at = (0..self.entries.len())
.filter(|&i| !hidden(&self.entries[i]))
.nth(index)
.unwrap();
self.entries.remove(at);
Ok(server)
}
/// Writes the list as the game does: a new file first, the old one kept as `servers.dat_old`.
pub fn save(&self, home: &Path) -> Result<(), String> {
let root = NamedTag {
name: "".into(),
tag: Tag::compound([(
"servers",
Tag::List(self.entries.iter().cloned().map(Tag::Compound).collect()),
)]),
};
let bytes = nbt::write_named(&root, Limits::default()).map_err(|e| e.to_string())?;
let (new, current) = (home.join("servers.dat_new"), home.join(FILE));
let written = fs::create_dir_all(home)
.and_then(|()| fs::write(&new, bytes))
.and_then(|()| match current.exists() {
true => fs::copy(&current, home.join("servers.dat_old")).map(|_| ()),
false => Ok(()),
})
.and_then(|()| fs::rename(&new, &current));
written.map_err(|e| format!("Could not save the server list: {e}"))
}
}
/// The shown server a command names: its position from 1, its name (any case) or its address.
pub fn find(list: &List, query: &str) -> Result<(usize, Server), String> {
let servers = list.servers();
let q = query.trim();
q.parse::<usize>()
.ok()
.filter(|n| (1..=servers.len()).contains(n))
.map(|n| n - 1)
.or_else(|| servers.iter().position(|s| s.name.eq_ignore_ascii_case(q)))
.or_else(|| servers.iter().position(|s| s.ip.eq_ignore_ascii_case(q)))
.map(|i| (i, servers[i].clone()))
.ok_or_else(|| format!("No server {q} in the list"))
}
#[cfg(test)]
#[path = "server_list/tests.rs"]
mod tests;
+143
View File
@@ -0,0 +1,143 @@
use super::*;
use std::path::PathBuf;
fn scratch(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"horizon-launcher-servers-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
root
}
fn s(v: &str) -> Tag {
Tag::String(v.into())
}
/// A servers.dat as the game writes it: one shown server with a picture and the fields the
/// launcher doesn't use, then one joined through Direct Connection.
fn vanilla_file(home: &Path) -> Vec<u8> {
let png = [0x89, b'P', b'N', b'G', 1, 2, 3];
let icon = base64::engine::general_purpose::STANDARD.encode(png);
let root = NamedTag {
name: "".into(),
tag: Tag::compound([(
"servers",
Tag::List(vec![
Tag::compound([
("name", s("Friends")),
("ip", s("friends.example:25570")),
("icon", s(&icon)),
("acceptTextures", Tag::Byte(1)),
("acceptedCodeOfConduct", Tag::Int(-12345)),
("hidden", Tag::Byte(0)),
]),
Tag::compound([
("name", s("Minecraft Server")),
("ip", s("direct.example")),
("hidden", Tag::Byte(1)),
]),
]),
)]),
};
let bytes = nbt::write_named(&root, Limits::default()).unwrap();
fs::write(home.join(FILE), &bytes).unwrap();
bytes
}
fn entries(home: &Path) -> Vec<Tag> {
let bytes = fs::read(home.join(FILE)).unwrap();
match nbt::read_named(&bytes, Limits::default())
.unwrap()
.0
.tag
.get("servers")
{
Some(Tag::List(list)) => list.clone(),
other => panic!("no servers list: {other:?}"),
}
}
#[test]
fn reads_the_shown_servers_with_their_pictures() {
let home = scratch("reads");
vanilla_file(home.as_path());
let list = List::load(home.as_path());
assert_eq!(
list.servers(),
vec![Server {
name: "Friends".into(),
ip: "friends.example:25570".into(),
icon: Some(vec![0x89, b'P', b'N', b'G', 1, 2, 3]),
}]
);
// No file, or one that isn't NBT: an empty list, as in the game.
assert!(List::load(&home.as_path().join("none"))
.servers()
.is_empty());
fs::write(home.as_path().join(FILE), b"not nbt").unwrap();
assert!(List::load(home.as_path()).servers().is_empty());
}
#[test]
fn adding_and_removing_keeps_every_other_field_and_the_hidden_servers() {
let home = scratch("keeps");
let original = vanilla_file(home.as_path());
let before = entries(home.as_path());
let mut list = List::load(home.as_path());
list.add(" Hub ", " hub.example ").unwrap();
assert!(list.add("x", " ").is_err());
list.save(home.as_path()).unwrap();
// The game's own backup of what was there.
assert_eq!(
fs::read(home.as_path().join("servers.dat_old")).unwrap(),
original
);
assert!(!home.as_path().join("servers.dat_new").exists());
let after = entries(home.as_path());
assert_eq!(after.len(), 3);
assert_eq!(
after[0], before[0],
"the first server is written back untouched"
);
assert_eq!(
after[1],
Tag::compound([
("name", s("Hub")),
("ip", s("hub.example")),
("hidden", Tag::Byte(0)),
]),
"a new server goes after the shown ones, before the hidden ones"
);
assert_eq!(after[2], before[1], "the hidden server stays");
let mut list = List::load(home.as_path());
let (i, found) = find(&list, "friends").unwrap();
assert_eq!((i, found.ip.as_str()), (0, "friends.example:25570"));
assert_eq!(find(&list, "2").unwrap().1.name, "Hub");
assert_eq!(find(&list, "HUB.example").unwrap().0, 1);
assert!(find(&list, "3").is_err(), "the hidden one can't be named");
assert_eq!(list.remove(0).unwrap().name, "Friends");
assert!(list.remove(5).is_err());
list.save(home.as_path()).unwrap();
assert_eq!(
entries(home.as_path()),
vec![after[1].clone(), before[1].clone()]
);
}
#[test]
fn a_server_without_a_name_gets_the_games_default() {
let home = scratch("default");
let mut list = List::load(home.as_path());
list.add("", "play.example").unwrap();
list.save(home.as_path()).unwrap();
assert!(!home.as_path().join("servers.dat_old").exists());
assert_eq!(
List::load(home.as_path()).servers()[0].name,
"Minecraft Server"
);
}
+7 -1
View File
@@ -35,10 +35,13 @@ pub(super) enum Field {
/// The instance dialog's (`instances_page.rs`).
InstanceName,
InstanceGroup,
/// Home's Multiplayer section's (`multiplayer_page.rs`).
ServerName,
ServerAddress,
}
impl Field {
const ALL: [Field; 11] = [
const ALL: [Field; 13] = [
Field::Name,
Field::Seed,
Field::Players,
@@ -50,6 +53,8 @@ impl Field {
Field::Email,
Field::InstanceName,
Field::InstanceGroup,
Field::ServerName,
Field::ServerAddress,
];
}
@@ -1027,6 +1032,7 @@ impl Launcher {
Field::Token => self.save_token(),
Field::Email => self.invite_friend(),
Field::InstanceName | Field::InstanceGroup => {}
Field::ServerName | Field::ServerAddress => self.add_server(),
}
}
+273
View File
@@ -0,0 +1,273 @@
//! An instance's single-player worlds (`saves/` in its game folder): what each is, and backing
//! up, copying and deleting them. Backups are made as vanilla's Make Backup makes them
//! (`LevelStorageAccess.makeWorldBackup`): `backups/<yyyy-MM-dd_HH-mm-ss>_<folder>.zip` in the
//! game folder, every file under `<folder>/` but the world's `session.lock`.
use horizon_world::nbt::{self, Limits, Tag};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// The lock a running game holds on a world; vanilla's backups leave it out.
const LOCK: &str = "session.lock";
#[derive(Clone, Debug, PartialEq)]
pub struct World {
/// Its folder's name under `saves/`, the id commands take.
pub folder: String,
pub path: PathBuf,
/// `LevelName`, else the folder's name.
pub name: String,
/// Survival, Creative, Adventure, Spectator or Hardcore.
pub mode: &'static str,
/// `LastPlayed`, else when level.dat changed.
pub last_played: SystemTime,
/// The version that last saved it (`Version.Name`).
pub version: Option<String>,
/// Bytes on disk, every file in its folder.
pub size: u64,
/// `icon.png`, the picture the game took of it.
pub icon: Option<PathBuf>,
}
/// The worlds in a game folder's `saves/`, the last played first.
pub fn list(home: &Path) -> Vec<World> {
let mut worlds: Vec<World> = fs::read_dir(home.join("saves"))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| read(&e.path()))
.collect();
worlds.sort_by_key(|w| std::cmp::Reverse(w.last_played));
worlds
}
/// level.dat: gzip, as vanilla writes it, or plain.
fn level_dat(path: &Path) -> Option<Tag> {
let bytes = fs::read(path).ok()?;
let mut raw = Vec::new();
let raw = match flate2::read::GzDecoder::new(&bytes[..])
.take(64 << 20)
.read_to_end(&mut raw)
{
Ok(_) => raw,
Err(_) => bytes,
};
Some(nbt::read_named(&raw, Limits::default()).ok()?.0.tag)
}
fn read(path: &Path) -> Option<World> {
let dat = path.join("level.dat");
let changed = fs::metadata(&dat).and_then(|m| m.modified()).ok()?;
let folder = path.file_name()?.to_string_lossy().into_owned();
let root = level_dat(&dat);
let data = root.as_ref().and_then(|r| r.get("Data"));
let field = |key: &str| data.and_then(|d| d.get(key));
let number = |tag: Option<&Tag>| match tag {
Some(Tag::Byte(v)) => i64::from(*v),
Some(Tag::Int(v)) => i64::from(*v),
Some(Tag::Long(v)) => *v,
_ => 0,
};
let text = |tag: Option<&Tag>| match tag {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
// 26.3 keeps hardcore with the difficulty; older saves at the top of Data.
let hardcore = number(field("difficulty_settings").and_then(|d| d.get("hardcore"))) != 0
|| number(field("hardcore")) != 0;
let mode = match (hardcore, number(field("GameType"))) {
(true, _) => "Hardcore",
(_, 1) => "Creative",
(_, 2) => "Adventure",
(_, 3) => "Spectator",
_ => "Survival",
};
let last_played = match number(field("LastPlayed")) {
millis if millis > 0 => UNIX_EPOCH + Duration::from_millis(millis as u64),
_ => changed,
};
let icon = path.join("icon.png");
Some(World {
name: text(field("LevelName"))
.filter(|n| !n.trim().is_empty())
.unwrap_or_else(|| folder.clone()),
folder,
path: path.to_path_buf(),
mode,
last_played,
version: text(field("Version").and_then(|v| v.get("Name"))),
size: size(path),
icon: icon.is_file().then_some(icon),
})
}
fn size(dir: &Path) -> u64 {
fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| match e.file_type() {
Ok(t) if t.is_dir() => size(&e.path()),
Ok(_) => e.metadata().map_or(0, |m| m.len()),
Err(_) => 0,
})
.sum()
}
/// The world in `home` a command names: its folder, or its name (any case).
pub fn find(home: &Path, query: &str) -> Result<World, String> {
let all = list(home);
all.iter()
.find(|w| w.folder == query)
.or_else(|| all.iter().find(|w| w.name.eq_ignore_ascii_case(query)))
.cloned()
.ok_or_else(|| format!("No world {query} in {}", home.join("saves").display()))
}
/// `base`, else `base (1)`, `base (2)`... from the `first` count: the first name free in `dir`
/// (vanilla's `FileUtil.findAvailableName`, after making the name safe for every file system).
fn free_name(dir: &Path, base: &str, suffix: &str, first: u32) -> String {
let safe: String = base
.chars()
.map(|c| match c {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
c if c.is_control() => '_',
c => c,
})
.collect();
let safe = safe.trim_matches(|c: char| c == '.' || c.is_whitespace());
let safe = if safe.is_empty() { "World" } else { safe };
(first..)
.map(|n| match n {
0 => format!("{safe}{suffix}"),
n => format!("{safe} ({n}){suffix}"),
})
.find(|name| !dir.join(name).exists())
.unwrap()
}
/// Zips the world into the game folder's `backups/`, as vanilla's Make Backup does. Returns the
/// zip's path.
pub fn backup(home: &Path, world: &World) -> Result<PathBuf, String> {
backup_at(home, world, chrono::Local::now())
}
fn backup_at(
home: &Path,
world: &World,
now: chrono::DateTime<chrono::Local>,
) -> Result<PathBuf, String> {
let dir = home.join("backups");
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let prefix = format!("{}_{}", now.format("%Y-%m-%d_%H-%M-%S"), world.folder);
let zip_path = dir.join(free_name(&dir, &prefix, ".zip", 0));
let made = (|| -> std::io::Result<()> {
let mut zip = zip::ZipWriter::new(std::io::BufWriter::new(fs::File::create(&zip_path)?));
let options = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.large_file(true);
let mut stack = vec![world.path.clone()];
while let Some(dir) = stack.pop() {
let mut entries: Vec<_> = fs::read_dir(&dir)?.collect::<Result<_, _>>()?;
entries.sort_by_key(|e| e.file_name());
for e in entries {
let path = e.path();
if e.file_type()?.is_dir() {
stack.push(path);
continue;
}
if path.file_name() == Some(LOCK.as_ref()) {
continue;
}
let relative = path.strip_prefix(&world.path).unwrap_or(&path);
let mut entry = world.folder.clone();
for part in relative.components() {
entry.push('/');
entry.push_str(&part.as_os_str().to_string_lossy());
}
zip.start_file(entry, options)?;
std::io::copy(&mut fs::File::open(&path)?, &mut zip)?;
}
}
zip.finish()?.flush()
})();
made.map(|()| zip_path.clone()).map_err(|e| {
let _ = fs::remove_file(&zip_path);
format!("Could not back up {}: {e}", world.name)
})
}
/// Copies the world into a new folder of the same `saves/`, named "<name> (1)", "<name> (2)"...
/// and gives the copy that name in its level.dat so the game's list tells them apart.
pub fn copy(world: &World) -> Result<World, String> {
let saves = world.path.parent().ok_or("A world folder has a parent")?;
let folder = free_name(saves, &world.name, "", 1);
let to = saves.join(&folder);
let made = copy_dir(&world.path, &to).and_then(|()| rename_level(&to, &folder));
if let Err(e) = made {
let _ = fs::remove_dir_all(&to);
return Err(format!("Could not copy {}: {e}", world.name));
}
read(&to).ok_or_else(|| format!("{} has no level.dat", to.display()))
}
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
fs::create_dir_all(to)?;
for e in fs::read_dir(from)? {
let e = e?;
let target = to.join(e.file_name());
if e.file_type()?.is_dir() {
copy_dir(&e.path(), &target)?;
} else if e.file_name() != LOCK {
fs::copy(e.path(), target)?;
}
}
Ok(())
}
/// Sets `Data.LevelName`; a level.dat that can't be read is left as it is.
fn rename_level(world: &Path, name: &str) -> std::io::Result<()> {
let dat = world.join("level.dat");
let Some(mut root) = level_dat(&dat) else {
return Ok(());
};
let Some(Tag::Compound(data)) = root.get_mut("Data") else {
return Ok(());
};
data.insert("LevelName".into(), Tag::String(name.into()));
let bytes = nbt::write_named(
&nbt::NamedTag {
name: "".into(),
tag: root,
},
Limits::default(),
)
.map_err(std::io::Error::other)?;
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&bytes)?;
fs::write(dat, gz.finish()?)
}
/// 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
// allow the launcher to control Finder first; the file manager call needs nothing.
#[cfg(target_os = "macos")]
trash::macos::TrashContextExtMacos::set_delete_method(
&mut trash,
trash::macos::DeleteMethod::NsFileManager,
);
trash.delete(path)
}
#[cfg(test)]
#[path = "worlds/tests.rs"]
mod tests;
+157
View File
@@ -0,0 +1,157 @@
use super::*;
use chrono::TimeZone;
fn scratch(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"horizon-launcher-worlds-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
root
}
/// A world as the game saves it: a gzip level.dat with `data`'s fields under `Data`.
fn world(home: &Path, folder: &str, data: Vec<(&str, Tag)>) -> PathBuf {
let dir = home.join("saves").join(folder);
fs::create_dir_all(dir.join("region")).unwrap();
let root = Tag::compound([("Data", Tag::compound(data))]);
let bytes = nbt::write_named(
&nbt::NamedTag {
name: "".into(),
tag: root,
},
Limits::default(),
)
.unwrap();
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&bytes).unwrap();
fs::write(dir.join("level.dat"), gz.finish().unwrap()).unwrap();
fs::write(dir.join("region/r.0.0.mca"), [7u8; 1000]).unwrap();
fs::write(dir.join(LOCK), "lock").unwrap();
dir
}
fn name(n: &str) -> Tag {
Tag::String(n.into())
}
#[test]
fn lists_what_each_world_is() {
let home = scratch("list");
let survival = world(
&home,
"Survival",
vec![
("LevelName", name("My survival")),
("GameType", Tag::Int(0)),
("LastPlayed", Tag::Long(1_700_000_000_000)),
("Version", Tag::compound([("Name", name("26.3"))])),
],
);
fs::write(survival.join("icon.png"), "png").unwrap();
world(
&home,
"Hard",
vec![
("LevelName", name("Hard")),
("GameType", Tag::Int(0)),
("LastPlayed", Tag::Long(1_800_000_000_000)),
(
"difficulty_settings",
Tag::compound([("hardcore", Tag::Byte(1))]),
),
],
);
world(
&home,
"Old",
vec![
("GameType", Tag::Int(1)),
("hardcore", Tag::Byte(0)),
("LastPlayed", Tag::Long(1_600_000_000_000)),
],
);
fs::create_dir_all(home.join("saves/not a world")).unwrap();
let all = list(&home);
let names: Vec<&str> = all.iter().map(|w| w.name.as_str()).collect();
assert_eq!(names, ["Hard", "My survival", "Old"]);
assert_eq!(all[0].mode, "Hardcore");
assert_eq!(all[1].mode, "Survival");
assert_eq!(all[1].folder, "Survival");
assert_eq!(all[1].version.as_deref(), Some("26.3"));
assert_eq!(all[1].icon, Some(survival.join("icon.png")));
assert_eq!(
all[1].last_played,
UNIX_EPOCH + Duration::from_millis(1_700_000_000_000)
);
assert!(all[1].size >= 1000);
// No LevelName: the folder's name.
assert_eq!(all[2].mode, "Creative");
assert_eq!(find(&home, "my SURVIVAL").unwrap().folder, "Survival");
assert!(find(&home, "nope").is_err());
fs::remove_dir_all(&home).unwrap();
}
#[test]
fn a_backup_is_named_and_laid_out_as_vanillas() {
let home = scratch("backup");
world(&home, "World", vec![("LevelName", name("World"))]);
let w = find(&home, "World").unwrap();
let at = chrono::Local
.with_ymd_and_hms(2026, 10, 27, 1, 2, 3)
.unwrap();
let first = backup_at(&home, &w, at).unwrap();
assert_eq!(first, home.join("backups/2026-10-27_01-02-03_World.zip"));
// The same second again: the next free name.
let second = backup_at(&home, &w, at).unwrap();
assert_eq!(
second,
home.join("backups/2026-10-27_01-02-03_World (1).zip")
);
let mut zip = zip::ZipArchive::new(fs::File::open(&first).unwrap()).unwrap();
let mut entries: Vec<String> = zip.file_names().map(str::to_string).collect();
entries.sort();
assert_eq!(entries, ["World/level.dat", "World/region/r.0.0.mca"]);
let mut region = Vec::new();
zip.by_name("World/region/r.0.0.mca")
.unwrap()
.read_to_end(&mut region)
.unwrap();
assert_eq!(region, [7u8; 1000]);
fs::remove_dir_all(&home).unwrap();
}
#[test]
fn a_copy_gets_the_next_free_name_in_its_folder_and_level_dat() {
let home = scratch("copy");
world(
&home,
"Base",
vec![("LevelName", name("Base")), ("GameType", Tag::Int(1))],
);
let base = find(&home, "Base").unwrap();
let copy1 = copy(&base).unwrap();
assert_eq!(copy1.folder, "Base (1)");
assert_eq!(copy1.name, "Base (1)");
assert_eq!(copy1.mode, "Creative");
assert!(!copy1.path.join(LOCK).exists());
assert_eq!(
fs::read(copy1.path.join("region/r.0.0.mca")).unwrap(),
[7u8; 1000]
);
assert_eq!(copy(&base).unwrap().folder, "Base (2)");
// The original is untouched.
assert_eq!(find(&home, "Base").unwrap(), base);
// A name that can't be a folder name is made safe.
assert_eq!(free_name(&home, "a/b: c?", "", 0), "a_b_ c_");
// A world whose folder isn't its name: the copy still gets a new name.
world(&home, "f", vec![("LevelName", name("Named"))]);
let named = copy(&find(&home, "f").unwrap()).unwrap();
assert_eq!(
(named.folder.as_str(), named.name.as_str()),
("Named (1)", "Named (1)")
);
fs::remove_dir_all(&home).unwrap();
}
+311
View File
@@ -0,0 +1,311 @@
//! The selected instance's worlds on Home (`horizon_launcher::worlds`): each with its picture,
//! mode, version, when it was last played and its size, and Back up, Copy, Delete (to the
//! trash, after a confirmation) and Open folder. Reading sizes and copying run in the background.
use super::*;
use horizon_launcher::worlds::{self, World};
use std::path::{Path, PathBuf};
#[derive(Default)]
pub(super) struct Worlds {
/// The game folder the list is of, and the list as last read: kept on screen while it is
/// read again, so the page doesn't jump.
home: Option<PathBuf>,
list: Vec<World>,
fresh: bool,
reading: bool,
/// The world being backed up, copied or deleted now.
busy: Option<String>,
confirm_delete: Option<String>,
/// What the last action did (a backup's zip), or why it failed.
done: Option<Result<(String, Option<PathBuf>), String>>,
}
impl Worlds {
/// Read again on the next frame: the game may have saved, or an action changed the list.
pub(super) fn stale(&mut self) {
self.fresh = false;
}
}
/// "today", "yesterday", "3 days ago", else the date.
pub(super) fn ago(when: std::time::SystemTime) -> String {
let when: chrono::DateTime<chrono::Local> = when.into();
let days = (chrono::Local::now().date_naive() - when.date_naive()).num_days();
match days {
..=0 => "today".into(),
1 => "yesterday".into(),
2..=13 => format!("{days} days ago"),
_ => when.format("%Y-%m-%d").to_string(),
}
}
enum Action {
Backup,
Copy,
Delete,
}
impl Launcher {
/// Reads the worlds of `home` in the background when the list is missing or of another
/// instance.
fn load_worlds(&mut self, home: PathBuf, cx: &mut Context<Self>) {
if self.worlds.home.as_ref() != Some(&home) {
self.worlds = Worlds {
home: Some(home.clone()),
..Worlds::default()
};
}
if self.worlds.fresh || self.worlds.reading {
return;
}
self.worlds.reading = true;
let read = home.clone();
let task = cx
.background_executor()
.spawn(async move { worlds::list(&read) });
cx.spawn(async move |this, cx| {
let list = task.await;
let _ = this.update(cx, |this, cx| {
// Another instance may have been picked meanwhile.
if this.worlds.home.as_ref() == Some(&home) {
this.worlds.list = list;
this.worlds.fresh = true;
this.worlds.reading = false;
}
cx.notify();
});
})
.detach();
}
fn world_action(&mut self, action: Action, world: World, cx: &mut Context<Self>) {
let Some(home) = self.worlds.home.clone() else {
return;
};
if self.worlds.busy.is_some() {
return;
}
self.worlds.busy = Some(world.folder.clone());
self.worlds.confirm_delete = None;
self.worlds.done = None;
let task = cx.background_executor().spawn(async move {
match action {
Action::Backup => worlds::backup(&home, &world)
.map(|zip| (format!("{} backed up.", world.name), Some(zip))),
Action::Copy => {
worlds::copy(&world).map(|c| (format!("Copied to {}.", c.name), None))
}
Action::Delete => worlds::delete(&world)
.map(|()| (format!("{} moved to the trash.", world.name), None)),
}
});
cx.spawn(async move |this, cx| {
let done = task.await;
let _ = this.update(cx, |this, cx| {
this.worlds.busy = None;
this.worlds.done = Some(done);
this.worlds.stale();
cx.notify();
});
})
.detach();
}
/// Home's Worlds section, for the selected instance.
pub(super) fn worlds_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let home = self.selected_instance()?.home.clone();
self.load_worlds(home.clone(), cx);
let list = self.worlds.list.clone();
let mut section = div()
.flex()
.flex_col()
.gap(px(8.))
.child(section_title("Worlds", "globe", &t).mb(px(4.)));
match &self.worlds.done {
Some(Ok((message, zip))) => {
let mut line = div().flex().items_center().gap(px(12.)).child(
text(theme::CAPTION)
.text_color(t.muted)
.child(message.clone()),
);
if let Some(zip) = zip.clone() {
let dir = zip.parent().map(Path::to_path_buf).unwrap_or(zip);
line = line.child(
button("world-backups", "Open backups", Kind::Ghost, &t)
.on_click(move |_, _, cx| cx.open_with_system(&dir)),
);
}
section = section.child(line);
}
Some(Err(e)) => section = section.child(notice(e.clone(), &t)),
None => {}
}
if list.is_empty() {
let saves = home.join("saves");
return Some(
section.child(
div()
.flex()
.items_center()
.justify_between()
.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("No worlds yet: they appear here once you play one."),
)
.child(
button("worlds-folder", "Open folder", Kind::Ghost, &t).on_click(
move |_, _, cx| {
let _ = std::fs::create_dir_all(&saves);
cx.open_with_system(&saves);
},
),
),
),
);
}
for (i, w) in list.into_iter().enumerate() {
section = section.child(self.world_row(i, w, cx));
}
Some(section)
}
fn world_row(&mut self, i: usize, w: World, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let busy = self.worlds.busy.is_some();
let this_busy = self.worlds.busy.as_ref() == Some(&w.folder);
let confirming = self.worlds.confirm_delete.as_ref() == Some(&w.folder);
let picture = match &w.icon {
Some(icon) => div()
.flex_none()
.size(px(48.))
.border_2()
.border_color(t.outline)
.child(gpui::img(icon.clone()).size(px(44.)))
.into_any_element(),
None => div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(48.))
.border_2()
.border_color(t.outline)
.bg(t.well)
.child(blocks::icon("image", 22., t.muted))
.into_any_element(),
};
let mut facts = vec![w.mode.to_string()];
facts.extend(w.version.clone());
facts.push(ago(w.last_played));
facts.push(megabytes(w.size));
let act = |id: &str, label: &'static str, kind: Kind| {
let b = button(SharedString::from(format!("{id}-{i}")), label, kind, &t);
if busy {
disabled(b)
} else {
b
}
};
let mut actions = div().flex().items_center().gap(px(6.));
if confirming {
let gone = w.clone();
actions = actions
.child(
text(theme::CAPTION)
.text_color(t.danger)
.child("Move it to the trash?"),
)
.child(act("world-keep", "Keep", Kind::Ghost).on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.worlds.confirm_delete = None;
cx.notify();
},
)))
.child(
act("world-trash", "Move to trash", Kind::Secondary).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_action(Action::Delete, gone.clone(), cx);
cx.notify();
},
)),
);
} else if this_busy {
actions = actions.child(text(theme::CAPTION).text_color(t.muted).child("Working…"));
} else {
let (backup, copy, folder) = (w.clone(), w.clone(), w.path.clone());
let (delete, play) = (w.folder.clone(), w.folder.clone());
let running = self.client.is_some() || self.starting_client.is_some();
let play_button = act("world-play", "Play", Kind::Secondary);
let play_button = if running {
disabled(play_button)
} else {
play_button
};
actions = actions
.child(
play_button.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.quick_play("--world", play.clone());
cx.notify();
})),
)
.child(
act("world-backup", "Back up", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_action(Action::Backup, backup.clone(), cx);
cx.notify();
},
)),
)
.child(act("world-copy", "Copy", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_action(Action::Copy, copy.clone(), cx);
cx.notify();
},
)))
.child(
act("world-delete", "Delete", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
// Buttons look disabled while something runs, but still click.
if this.worlds.busy.is_none() {
this.worlds.confirm_delete = Some(delete.clone());
}
cx.notify();
},
)),
)
.child(
act("world-folder", "Open folder", Kind::Ghost)
.on_click(move |_, _, cx| cx.open_with_system(&folder)),
);
}
plate(&t)
.flex()
.items_center()
.gap(px(14.))
.px(px(14.))
.py(px(10.))
.child(picture)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.child(
blocks::pixel(15., FontWeight::MEDIUM)
.text_color(t.ink)
.truncate()
.child(w.name.clone()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(facts.join(" · ")),
),
)
.child(actions)
}
}
+13 -9
View File
@@ -2971,13 +2971,15 @@ def check_fireworks(host, guest, out):
game('command', command=f'tp @s {x + dx + 0.5} {y} {z + 0.5}')
game.raw('look-at', x + 0.5, y + 1.5, z + 3.5)
def red(path):
def reds(path):
"""The red pixels' positions, above the hotbar."""
rows, bpp = png_rows(path)
# Exclude the hotbar and chat at the bottom of the view.
return sum(row[i] > 80 and row[i] > 2 * row[i + 1] and row[i] > 2 * row[i + 2]
for row in rows[:len(rows) * 3 // 4] for i in range(0, len(row), bpp))
return {(y, i) for y, row in enumerate(rows[:len(rows) * 3 // 4]) for i in range(0, len(row), bpp)
if row[i] > 80 and row[i] > 2 * row[i + 1] and row[i] > 2 * row[i + 2]}
baseline = {g.name: red(g.shot(out, 'fireworks-before')) for g in (host, guest)}
# Red where the view had none: the setup's own red chat lines (a fill that changed nothing) are in the
# baseline, and fade out before the later shots, which a plain count difference would take as missing sparks.
baseline = {g.name: reds(g.shot(out, 'fireworks-before')) for g in (host, guest)}
before = {g.name: made(g, 'flash') for g in (host, guest)}
host('command', command='item replace entity @s weapon.mainhand with minecraft:firework_rocket'
'[fireworks={flight_duration:0,explosions:[{shape:"large_ball",colors:[I;16711680],has_trail:true}]}]')
@@ -2990,12 +2992,14 @@ def check_fireworks(host, guest, out):
break
flashes = {g.name: made(g, 'flash') - before[g.name] for g in (host, guest)}
assert all(n == 1 for n in flashes.values()), f'configured burst missing or duplicated: {flashes}'
# Capture both views before decoding PNGs: decoding must not consume the sparks' lifetime.
# Capture both views before decoding PNGs: decoding must not consume the sparks' lifetime (48-59 ticks). A
# screenshot takes ~0.6 s where the frame is drawn on the CPU (lavapipe), so the later shots come 4 ticks after
# the burst's, not more: by then the tracked rocket is gone.
burst_shots = {g.name: g.shot(out, 'fireworks-burst') for g in (host, guest)}
host.wait(16)
host.wait(4)
trail_shots = {g.name: g.shot(out, 'fireworks-trail-fade') for g in (host, guest)}
burst = {name: red(path) - baseline[name] for name, path in burst_shots.items()}
trails = {name: red(path) - baseline[name] for name, path in trail_shots.items()}
burst = {name: len(reds(path) - baseline[name]) for name, path in burst_shots.items()}
trails = {name: len(reds(path) - baseline[name]) for name, path in trail_shots.items()}
rockets = {g.name: g('status')['rockets'] for g in (host, guest)}
assert not any(rockets.values()), f'exploded rocket remains: {rockets}'
assert all(n > 20 for n in burst.values()), f'no red burst: {burst}'