Merge main into docs/server-api-reference

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-24 22:09:34 +02:00
63 changed files with 4332 additions and 380 deletions
Generated
+1
View File
@@ -1278,6 +1278,7 @@ dependencies = [
"rustix 1.1.5",
"serde",
"serde_json",
"sha1",
"sha2",
"symphonia",
"ureq",
+1 -8
View File
@@ -1,8 +1,7 @@
//! The machine a report was measured on. CPU, RAM and OS are detected here; the GPU and the display
//! come from the program that rendered (the game knows its adapter, the launcher its window).
use std::process::Command;
use horizon_telemetry::system::command_output as output;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -173,12 +172,6 @@ pub fn cpu_seconds(pid: u32) -> Option<f64> {
Some(ticks / 100.0)
}
fn output(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
let text = String::from_utf8(out.stdout).ok()?.trim().to_owned();
(out.status.success() && !text.is_empty()).then_some(text)
}
#[cfg(target_os = "macos")]
fn os_version() -> Option<String> {
output("sw_vers", &["-productVersion"])
+7 -1
View File
@@ -245,13 +245,19 @@ pub struct Report {
impl Report {
/// An empty report for this machine, created now.
pub fn new(kind: Kind, app: App) -> Report {
Self::with_hardware(kind, app, Hardware::detect())
}
/// Starts a report using supplied hardware, without running system probes.
/// Interactive apps can collect the remaining machine details after their first frame.
pub fn with_hardware(kind: Kind, app: App, hardware: Hardware) -> Report {
Report {
format: FORMAT.to_owned(),
version: VERSION,
kind,
created: utc_now(),
app,
hardware: Hardware::detect(),
hardware,
conditions: Conditions::default(),
metrics: BTreeMap::new(),
frames: Vec::new(),
+2
View File
@@ -27,6 +27,8 @@ bytemuck = { version = "1.24", features = ["derive"] }
glam = "0.30"
png = "0.18"
sha2 = "0.10.9"
# Server resource packs are checked and cached by their SHA-1, as vanilla does.
sha1 = "0.10"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["raw_value"] }
# hlsl-out: the gfx.rs tests translate every shader as wgpu's DirectX 12 backend does. A normal feature,
@@ -5,7 +5,7 @@
//!
//! usage: pack_screen_fixture RESOURCES CASES OUTPUT
use horizon_client::{
hud::HudAtlas,
hud::{HudAtlas, PACK_ICON_SIZE},
lang,
pack_screen::{Compat, PackInfo, PackScreen, Source},
packs::{self, Position},
@@ -13,7 +13,7 @@ use horizon_client::{
text::Text,
};
use serde_json::{Value, json};
use std::{fmt::Write as _, fs, path::PathBuf};
use std::{fmt::Write as _, fs, path::PathBuf, sync::Arc};
/// Styled runs: [text, rgb or null, bold, italic, underlined, strikethrough, obfuscated].
pub fn runs(t: &Text) -> Value {
@@ -105,7 +105,9 @@ pub fn main() -> horizon_client::Result<()> {
Some("unknown") => Compat::Unknown,
_ => Compat::Compatible,
},
icon: p["icon"].as_bool().unwrap_or(false),
icon: p["icon"].as_bool().unwrap_or(false).then(|| {
Arc::from(vec![0; (PACK_ICON_SIZE * PACK_ICON_SIZE * 4) as usize])
}),
required: p["required"].as_bool().unwrap_or(false),
position: if p["position"] == "top" {
Position::Top
@@ -0,0 +1,75 @@
//! `ConfirmScreen`: a title, a message wrapped to `width - 50` (15 lines at
//! most) and two 150-wide buttons 4 apart and 16 below it, the whole column
//! centred; Escape answers no.
use crate::{
font::Font,
hud::{HudAtlas, HudBatch},
text::Text,
ui,
};
pub struct Confirm {
/// Each line and where it is drawn.
pub lines: Vec<(Text, f32, f32)>,
/// The yes and no buttons' corners.
pub buttons: [(f32, f32); 2],
}
impl Confirm {
pub fn new(font: &Font, (w, h): (f32, f32), title: &Text, message: &Text) -> Self {
let message: Vec<Text> = font
.split_lines(message, w - 50.0)
.into_iter()
.map(|(line, _)| line)
.take(15)
.collect();
let tw = font.width_text(title);
let mw = message
.iter()
.map(|l| font.width_text(l))
.fold(0.0, f32::max);
let mh = 9.0 * message.len() as f32;
let col = tw.max(mw).max(304.0);
let total = 9.0 + 8.0 + mh + 8.0 + 36.0;
let (lx, ly) = (((w - col) / 2.0).trunc(), ((h - total) / 2.0).trunc());
let cell = |cw: f32| lx + ((col - cw) / 2.0).trunc();
let mid = cell(mw) + (mw / 2.0).trunc();
let mut lines = vec![(title.clone(), cell(tw), ly)];
for (i, line) in message.into_iter().enumerate() {
let x = mid - (font.width_text(&line) / 2.0).trunc();
lines.push((line, x, ly + 17.0 + 9.0 * i as f32));
}
let (bx, by) = (cell(304.0), ly + 9.0 + 8.0 + mh + 8.0 + 16.0);
Self {
lines,
buttons: [(bx, by), (bx + 154.0, by)],
}
}
/// The answer a click at `cursor` gives: true for yes, false for no.
pub fn answer_at(&self, cursor: (f32, f32)) -> Option<bool> {
let [yes, no] = self.buttons;
let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0);
if on(yes) {
Some(true)
} else if on(no) {
Some(false)
} else {
None
}
}
/// The lines and the buttons (yes first), over whatever is behind.
pub fn draw(
&self,
batch: &mut HudBatch,
atlas: &HudAtlas,
cursor: (f32, f32),
labels: [&Text; 2],
) {
for (line, x, y) in &self.lines {
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
}
for ((bx, by), label) in self.buttons.into_iter().zip(labels) {
let hover = ui::hovered(cursor, bx, by, 150.0, 20.0);
ui::button(batch, atlas, bx, by, 150.0, 20.0, label, true, hover);
}
}
}
+29 -2
View File
@@ -137,6 +137,7 @@ mod scoreboard;
mod screens;
mod sculk;
mod sculk_fixture;
mod server_packs;
mod server_travel;
mod shield;
mod sign_edit;
@@ -1126,6 +1127,8 @@ struct Game<'a> {
pending_entry: Option<PendingWorldEntry>,
world_loader: Option<world_loading::WorldLoader>,
pending_pack_reload: bool,
/// A server's resource packs (game/server_packs.rs).
server_packs: server_packs::ServerPackState,
world_renderer_ready: bool,
collision: &'a BlockCollisionRegistry<'a>,
motion: &'a MotionResources,
@@ -4771,7 +4774,14 @@ impl Game<'_> {
hud_layout::paint(batch, &self.gui.atlas, &draws);
}
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = self.hud_layers(size);
// The pack prompt replaces the connecting screen (setScreen), but
// in game it opens over the world.
let mut batch = if self.server_packs.prompt.is_some() && self.player.is_none() {
HudBatch::new(size)
} else {
self.hud_layers(size)
};
self.draw_pack_prompt(&mut batch);
// Gui.extractRenderState: the debug overlay comes after the screen
// and the toasts, so it is over everything, menus included.
self.draw_debug_overlay(&mut batch, size);
@@ -10995,6 +11005,13 @@ impl ApplicationHandler for Game<'_> {
self.advancements_scroll(scaled(raw_x) as f32, d);
}
}
WindowEvent::MouseInput { state, button, .. }
if self.server_packs.prompt.is_some() =>
{
if state == ElementState::Pressed && button == MouseButton::Left {
self.pack_prompt_click()?;
}
}
WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {}
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
if self.options_waiting_for_key() && state == ElementState::Pressed {
@@ -11194,6 +11211,14 @@ impl ApplicationHandler for Game<'_> {
_ => {}
}
}
// ConfirmScreen.keyPressed: Escape answers no.
WindowEvent::KeyboardInput { event, .. } if self.server_packs.prompt.is_some() => {
if event.state == ElementState::Pressed
&& event.physical_key == PhysicalKey::Code(KeyCode::Escape)
{
self.answer_pack_prompt(false)?;
}
}
WindowEvent::KeyboardInput { event, .. }
if self.screen == Screen::Chat && self.title.is_none() =>
{
@@ -11572,6 +11597,7 @@ impl ApplicationHandler for Game<'_> {
event_loop.exit();
return;
}
self.tick_server_packs();
self.poll_control(event_loop);
if self.pending_save.is_some() {
return;
@@ -11666,6 +11692,7 @@ impl<'a> Game<'a> {
pending_entry: None,
world_loader: None,
pending_pack_reload: false,
server_packs: Default::default(),
world_renderer_ready: false,
collision: res.collision(),
motion: res.motion(),
@@ -13254,7 +13281,7 @@ pub fn run() -> Result<()> {
return run_loading(options, early_settings, vanilla_root, None, started);
}
let mut pack_error = None;
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs)
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs, &[])
.unwrap_or_else(|e| {
log::warn!("Horizon: resource packs not applied: {e}");
pack_error = Some(e.to_string());
+9 -3
View File
@@ -82,8 +82,10 @@ impl Game<'_> {
}
return true;
}
// Screens with a text box take every key press first
// (EditBox.keyPressed); releases still reach KeyboardHandler.
// Vanilla types into a focused EditBox through charTyped, which no
// debug key can swallow. Here the character comes with the key press,
// so a screen with a focused text box takes every press first;
// releases still reach KeyboardHandler.
let typing = matches!(
self.screen,
Screen::Chat | Screen::Options | Screen::WorldOptions | Screen::CommandBlock
@@ -91,7 +93,11 @@ impl Game<'_> {
|| self.book.is_some()
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
|| self.recipe_search_focused()
|| self.station_typing();
|| self.station_typing()
|| self
.title
.as_mut()
.is_some_and(|t| t.focused_field().is_some());
// Container screens use Escape, the inventory key and the hotbar and
// drop keys first; any other screen closes on Escape.
let screen_key = match self.screen {
@@ -3,6 +3,7 @@
//! box each, and Done sending the changed ones (ServerboundSetGameRulePacket).
//! Leaving with changes asks first (ConfirmScreen).
use horizon_client::{
confirm_screen::Confirm,
font::Font,
gamerules::{self, GameRules, RULES, Rule, Value},
hud::{HudAtlas, HudBatch},
@@ -66,9 +67,6 @@ fn parse(r: &Rule, s: &str) -> Option<i32> {
.flatten()
.filter(|v| (r.min..=r.max).contains(v))
}
fn widest(font: &Font, lines: &[Text]) -> f32 {
lines.iter().map(|l| font.width_text(l)).fold(0.0, f32::max)
}
fn lines(font: &Font, t: &Text, width: f32) -> Vec<Text> {
font.split_lines(t, width)
.into_iter()
@@ -95,38 +93,11 @@ fn yellow() -> u32 {
named_color("yellow").unwrap_or(0xFFFF55)
}
/// ConfirmScreen: the title, the message (at most `width - 50` wide), and
/// Yes / No 16 below, 4 apart, all centred.
struct Confirm {
lines: Vec<(Text, f32, f32)>,
buttons: [(f32, f32); 2],
}
impl Confirm {
fn new(font: &Font, (w, h): (f32, f32)) -> Self {
let title = Text::translate("editGamerule.inGame.discardChanges.title", &[]);
let message = Text::translate("editGamerule.inGame.discardChanges.message", &[]);
let message: Vec<Text> = lines(font, &message, w - 50.0)
.into_iter()
.take(15)
.collect();
let (tw, mw) = (font.width_text(&title), widest(font, &message));
let mh = 9.0 * message.len() as f32;
let col = tw.max(mw).max(304.0);
let total = 9.0 + 8.0 + mh + 8.0 + 36.0;
let (lx, ly) = (((w - col) / 2.0).trunc(), ((h - total) / 2.0).trunc());
let cell = |cw: f32| lx + ((col - cw) / 2.0).trunc();
let mid = cell(mw) + (mw / 2.0).trunc();
let mut out = vec![(title, cell(tw), ly)];
for (i, line) in message.into_iter().enumerate() {
let x = mid - (font.width_text(&line) / 2.0).trunc();
out.push((line, x, ly + 17.0 + 9.0 * i as f32));
}
let (bx, by) = (cell(304.0), ly + 9.0 + 8.0 + mh + 8.0 + 16.0);
Self {
lines: out,
buttons: [(bx, by), (bx + 154.0, by)],
}
}
/// ConfirmScreen "Game Rule Changes".
fn confirm(font: &Font, size: (f32, f32)) -> Confirm {
let title = Text::translate("editGamerule.inGame.discardChanges.title", &[]);
let message = Text::translate("editGamerule.inGame.discardChanges.message", &[]);
Confirm::new(font, size, &title, &message)
}
impl RulesScreen {
@@ -301,13 +272,10 @@ impl RulesScreen {
let (w, h) = size;
let on = |x: f32, y: f32, bw: f32, bh: f32| ui::hovered(cursor, x, y, bw, bh);
if self.confirm {
let c = Confirm::new(&atlas.font, size);
let [(yx, yy), (nx, ny)] = c.buttons;
if on(yx, yy, 150.0, 20.0) {
return Some(Exit::Discard);
}
if on(nx, ny, 150.0, 20.0) {
self.confirm = false;
match confirm(&atlas.font, size).answer_at(cursor) {
Some(true) => return Some(Exit::Discard),
Some(false) => self.confirm = false,
None => {}
}
return None;
}
@@ -367,7 +335,7 @@ impl RulesScreen {
let (w, h) = size;
let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0);
if self.confirm {
return Confirm::new(&atlas.font, size).buttons.into_iter().any(on);
return confirm(&atlas.font, size).answer_at(cursor).is_some();
}
let [done, cancel] = footer(w, h);
if (on(done) && !self.invalid()) || on(cancel) {
@@ -384,15 +352,11 @@ impl RulesScreen {
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
if self.confirm {
let c = Confirm::new(&atlas.font, (w, h));
for (line, x, y) in &c.lines {
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
}
for ((bx, by), key) in c.buttons.into_iter().zip(["gui.yes", "gui.no"]) {
let hover = ui::hovered(cursor, bx, by, 150.0, 20.0);
let label = Text::translate(key, &[]);
ui::button(batch, atlas, bx, by, 150.0, 20.0, &label, true, hover);
}
let labels = [
Text::translate("gui.yes", &[]),
Text::translate("gui.no", &[]),
];
confirm(&atlas.font, (w, h)).draw(batch, atlas, cursor, [&labels[0], &labels[1]]);
return;
}
let rows = self.rows();
+30 -17
View File
@@ -4,7 +4,7 @@ use super::Game;
use horizon_client::{
hud::HudAtlas,
lang,
pack_screen::{Compat, PackInfo, Source as PackSource},
pack_screen::{self, Compat, PackInfo, Source as PackSource},
packs::{self, Pack, Position},
text::{Style, Text},
};
@@ -34,10 +34,16 @@ pub fn open_folder(dir: &Path) {
log::warn!("Horizon: could not open {}: {e}", dir.display());
}
}
/// The resource root to load from, given the vanilla root and the selection.
pub fn startup_root(vanilla: &Path, selected: &[String]) -> std::io::Result<PathBuf> {
/// The resource root to load from, given the vanilla root, the selection and
/// a server's packs, which go on top (`Pack.Position.TOP`, fixed).
pub fn startup_root(
vanilla: &Path,
selected: &[String],
server: &[Pack],
) -> std::io::Result<PathBuf> {
let all = packs::discover(vanilla, &packs_dir());
let enabled = packs::enabled(&all, selected);
let mut enabled = packs::enabled(&all, selected);
enabled.extend_from_slice(server);
packs::resource_root(vanilla, &enabled, &cache_dir())
}
fn info(p: &Pack) -> PackInfo {
@@ -53,14 +59,15 @@ fn info(p: &Pack) -> PackInfo {
PackSource::Default
},
compat: p.compatibility,
icon: p.icon,
icon: p.icon_png().as_deref().and_then(pack_screen::load_icon),
required: false,
position: Position::Top,
fixed: false,
}
}
/// The vanilla pack: required, at the bottom (`BuiltInPackSource`).
fn vanilla_info() -> PackInfo {
/// The vanilla pack: required, at the bottom (`BuiltInPackSource`), with the
/// client JAR's `pack.png` that the prepared resources hold.
fn vanilla_info(vanilla: &Path) -> PackInfo {
PackInfo {
id: "vanilla".into(),
title: Text::translate("resourcePack.vanilla.name", &[]),
@@ -68,7 +75,10 @@ fn vanilla_info() -> PackInfo {
description_style: Style::default(),
source: PackSource::BuiltIn,
compat: Compat::Compatible,
icon: true,
icon: std::fs::read(vanilla.join("pack.png"))
.ok()
.as_deref()
.and_then(pack_screen::load_icon),
required: true,
position: Position::Bottom,
fixed: false,
@@ -80,7 +90,7 @@ pub(super) fn pack_infos(vanilla: &Path) -> Vec<PackInfo> {
.iter()
.map(info)
.collect();
infos.push(vanilla_info());
infos.push(vanilla_info(vanilla));
infos
}
impl Game<'_> {
@@ -113,14 +123,7 @@ impl Game<'_> {
self.pending_pack_reload = true;
return;
}
let vanilla = self.vanilla_root();
if self.ui.vanilla_root.as_os_str().is_empty() {
self.ui.vanilla_root = vanilla.clone();
}
let result = startup_root(&vanilla, &self.settings.resource_packs)
.map_err(Into::into)
.and_then(|root| self.reload_resources(&root));
if let Err(e) = result {
if let Err(e) = self.reload_selected_packs() {
log::warn!("Horizon: resource reload failed: {e}");
if self.screen != super::Screen::Options {
self.open_options_at(
@@ -131,6 +134,16 @@ impl Game<'_> {
self.ui.options.resource_error = Some(e.to_string());
}
}
/// Reload from the selected packs and the server's.
pub(super) fn reload_selected_packs(&mut self) -> horizon_client::Result<()> {
let vanilla = self.vanilla_root();
if self.ui.vanilla_root.as_os_str().is_empty() {
self.ui.vanilla_root = vanilla.clone();
}
let server = &self.server_packs.active;
let root = startup_root(&vanilla, &self.settings.resource_packs, server)?;
self.reload_resources(&root)
}
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
let render = std::sync::Arc::new(self.pack.assets.reload(root)?);
let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?;
+13
View File
@@ -305,6 +305,16 @@ impl Game<'_> {
// A signed-in account always plays under its own name.
let auth = horizon_client::auth::current();
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
let user = auth.as_ref().map_or_else(
|| {
(
name.to_owned(),
horizon_protocol::crypto::offline_uuid(name),
)
},
|a| (a.name.clone(), a.uuid),
);
self.server_packs_connect(local.is_none().then_some(address), user);
let session = match local {
Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()),
None => {
@@ -453,6 +463,7 @@ impl Game<'_> {
if let Some(mut r) = self.remote.take() {
r.session.disconnect();
}
self.server_packs_disconnect();
// Single player's server thread saves the world before the title shows.
let single_player = match self.integrated.take() {
Some(server) => {
@@ -827,6 +838,8 @@ impl Game<'_> {
}
}
Event::Reconfigured(registries) => self.set_registries(registries),
Event::PackPush(p) => self.handle_pack_push(p),
Event::PackPop(id) => self.handle_pack_pop(id),
Event::DecodeError(e) => {
if let Some(r) = self.remote.as_mut() {
r.decode_errors += 1;
@@ -0,0 +1,316 @@
//! A server's resource packs bound to the game (`ClientCommonPacketListenerImpl.
//! handleResourcePackPush` and `handleResourcePackPop`, its `PackConfirmScreen`,
//! and `DownloadedPackSource` as `Minecraft` drives it): the prompt, the
//! server list's setting, downloads into `downloads/`, and a resource reload
//! with the server's packs on top of the player's own.
use super::Game;
use horizon_client::{
Result,
confirm_screen::Confirm,
hud::{HudAtlas, HudBatch},
multiplayer, packs,
scoreboard::{comp_text, tag_to_json},
server_packs::{Prompt, ServerPacks, action, download, parse_sha1, valid_url},
text::{Text, named_color},
ui,
};
use horizon_protocol::{packets::configuration::ResourcePackPush, servers};
use std::path::PathBuf;
/// `ClientCommonPacketListenerImpl.PackConfirmScreen`: the packs it asks
/// about, whether the last one is required, and the server's message.
pub(super) struct PackPrompt {
requests: Vec<(u128, String, String)>,
required: bool,
prompt: Option<Text>,
}
impl PackPrompt {
fn texts(&self) -> (Text, Text, [Text; 2]) {
let t = |key: &str| Text::translate(key, &[]);
let (title, line2) = if self.required {
let yellow = named_color("yellow").unwrap_or(0xFFFF55);
(
t("multiplayer.requiredTexturePrompt.line1"),
t("multiplayer.requiredTexturePrompt.line2")
.with_color(yellow)
.bold(),
)
} else {
(
t("multiplayer.texturePrompt.line1"),
t("multiplayer.texturePrompt.line2"),
)
};
// preparePackPrompt.
let message = match &self.prompt {
Some(prompt) => Text::translate(
"multiplayer.texturePrompt.serverPrompt",
&[line2, prompt.clone()],
),
None => line2,
};
let buttons = if self.required {
[t("gui.proceed"), t("menu.disconnect")]
} else {
[t("gui.yes"), t("gui.no")]
};
(title, message, buttons)
}
fn layout(&self, atlas: &HudAtlas, size: (f32, f32)) -> Confirm {
let (title, message, _) = self.texts();
Confirm::new(&atlas.font, size, &title, &message)
}
}
/// The game's `DownloadedPackSource`.
#[derive(Default)]
pub(super) struct ServerPackState {
packs: ServerPacks,
/// `downloads/` in the game folder, opened at the first download.
queue: Option<download::Queue>,
pub(super) prompt: Option<PackPrompt>,
/// The server list entry the setting is saved to (none: a direct join).
address: Option<String>,
/// The account the downloads are made for (the download headers).
user: (String, u128),
/// The packs loaded on top of the player's own, bottom first.
pub(super) active: Vec<packs::Pack>,
}
fn saves() -> PathBuf {
std::env::current_dir().unwrap_or_default().join("saves")
}
impl Game<'_> {
/// `ConnectScreen`: the server's setting decides what its packs do
/// (`configureForServerControl`); single player's own server takes them
/// all, quietly (`configureForLocalWorld`).
pub(super) fn server_packs_connect(&mut self, address: Option<&str>, user: (String, u128)) {
let state = &mut self.server_packs;
state.user = user;
state.prompt = None;
let Some(address) = address else {
state.address = None;
state.packs.local_world();
return;
};
let file = multiplayer::servers_file(&saves());
let entry = servers::load(&file).into_iter().find(|s| s.ip == address);
let setting = entry.as_ref().and_then(|e| e.accept_textures);
state.address = entry.map(|e| e.ip);
state.packs.connect(Prompt::for_server(setting));
}
/// `Minecraft.clearDownloadedResourcePacks`: every server pack goes at once.
pub(super) fn server_packs_disconnect(&mut self) {
self.server_packs.prompt = None;
self.server_packs.packs.disconnect();
self.tick_server_packs();
}
/// `handleResourcePackPush`.
pub(super) fn handle_pack_push(&mut self, p: ResourcePackPush) {
if !valid_url(&p.url) {
self.send_pack_status(p.id, action::INVALID_URL);
return;
}
let setting = self.server_setting();
let prompt = Prompt::for_server(setting);
if prompt != Prompt::Pending && (!p.required || prompt != Prompt::Declined) {
self.server_packs
.packs
.push(p.id, &p.url, parse_sha1(&p.hash));
return;
}
// addOrUpdatePackPrompt: one prompt for every pack pushed before it is answered.
let text = p.prompt.as_ref().map(|t| comp_text(&tag_to_json(t)));
let state = &mut self.server_packs;
let open = state.prompt.get_or_insert(PackPrompt {
requests: Vec::new(),
required: p.required,
prompt: None,
});
open.requests.push((p.id, p.url, p.hash));
open.required = p.required;
open.prompt = text;
self.capture(false);
}
/// `handleResourcePackPop`: one pack, or all of them.
pub(super) fn handle_pack_pop(&mut self, id: Option<u128>) {
match id {
Some(id) => self.server_packs.packs.pop(id),
None => self.server_packs.packs.pop_all(),
}
}
/// The joined server's entry in the server list: its `acceptTextures`.
fn server_setting(&self) -> Option<bool> {
let address = self.server_packs.address.as_deref()?;
servers::load(&multiplayer::servers_file(&saves()))
.into_iter()
.find(|s| s.ip == address)?
.accept_textures
}
fn send_pack_status(&self, id: u128, status: i32) {
if let Some(r) = &self.remote {
r.session.send_pack_status(id, status);
}
}
/// The prompt's answer (`PackConfirmScreen`'s callback): the server's
/// setting follows it, declining a required pack disconnects, and every
/// pack it asked about is pushed.
pub(super) fn answer_pack_prompt(&mut self, yes: bool) -> Result<()> {
let Some(prompt) = self.server_packs.prompt.take() else {
return Ok(());
};
if self.player.is_some() && self.screen == super::Screen::Playing {
self.capture(true);
}
let setting = if yes {
self.server_packs.packs.allow();
Some(true)
} else {
self.server_packs.packs.reject();
if prompt.required {
let reason = Text::translate("multiplayer.requiredTexturePrompt.disconnect", &[]);
return self.leave_server(Some(reason.plain()));
}
Some(false)
};
for (id, url, hash) in prompt.requests {
self.server_packs.packs.push(id, &url, parse_sha1(&hash));
}
// ServerList.saveSingleServer.
if let Some(address) = &self.server_packs.address {
let file = multiplayer::servers_file(&saves());
let mut list = servers::load(&file);
for entry in list.iter_mut().filter(|s| &s.ip == address) {
entry.accept_textures = setting;
}
if let Err(e) = servers::save(&file, &list) {
log::warn!("Horizon: could not save {}: {e}", file.display());
}
}
Ok(())
}
/// Runs what the packs need (`createUpdateScheduler`): the downloads
/// that finished, the ones to start, a resource reload when the active
/// packs change, and the statuses for the server.
pub(super) fn tick_server_packs(&mut self) {
// A reload waits for the world's resources (`reload_packs`).
if self.rest_loader.is_some() || self.world_loader.is_some() {
return;
}
let finished = self
.server_packs
.queue
.as_ref()
.map(download::Queue::finished)
.unwrap_or_default();
for batch in finished {
self.server_packs.packs.downloaded(batch);
}
while self.server_packs.packs.wants_tick() {
let tick = self.server_packs.packs.tick();
if !tick.download.is_empty() {
self.start_pack_downloads(tick.download);
}
if let Some(mut load) = tick.reload {
while let Some(recovery) = {
let ok = self.reload_server_packs(&load);
self.server_packs.packs.reloaded(ok)
} {
load = recovery;
}
}
}
for (id, status) in self.server_packs.packs.take_replies() {
self.send_pack_status(id, status);
}
}
fn start_pack_downloads(&mut self, requests: Vec<horizon_client::server_packs::Request>) {
let state = &mut self.server_packs;
if state.queue.is_none() {
let dir = std::env::current_dir()
.unwrap_or_default()
.join("downloads");
match download::Queue::open(dir) {
Ok(queue) => state.queue = Some(queue),
Err(e) => {
log::error!("Horizon: failed to open the download queue: {e}");
let failed = requests.iter().map(|r| r.id).collect();
state.packs.downloaded(horizon_client::server_packs::Batch {
downloaded: Vec::new(),
failed,
});
return;
}
}
}
let headers = download::headers(&state.user.0, state.user.1);
if let Some(queue) = &state.queue {
queue.download(requests, headers);
}
}
/// `DownloadedPackSource.startReload`: the packs on top of the player's
/// own, then `Minecraft.reloadResourcePacks`. False when a pack has no
/// readable `pack.mcmeta` or the reload failed.
fn reload_server_packs(&mut self, load: &[(u128, PathBuf)]) -> bool {
let packs: Option<Vec<_>> = load
.iter()
.map(|(id, path)| packs::server_pack(*id, path))
.collect();
let Some(packs) = packs else {
log::warn!("Horizon: invalid pack metadata in a server pack, ignoring all");
return false;
};
self.server_packs.active = packs;
match self.reload_selected_packs() {
Ok(()) => true,
Err(e) => {
log::warn!("Horizon: server resource pack reload failed: {e}");
false
}
}
}
pub(super) fn draw_pack_prompt(&self, batch: &mut HudBatch) {
let Some(prompt) = &self.server_packs.prompt else {
return;
};
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
if self.player.is_none() {
// In place of the connecting screen, on its background.
batch.fill(
atlas,
0.0,
0.0,
w,
h,
horizon_client::hud::rgba(20, 20, 20, 255),
);
}
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
let (_, _, [yes, no]) = prompt.texts();
prompt
.layout(atlas, (w, h))
.draw(batch, atlas, self.cursor, [&yes, &no]);
}
/// A left click on the prompt: its answer when it hit a button.
pub(super) fn pack_prompt_click(&mut self) -> Result<()> {
let Some(prompt) = &self.server_packs.prompt else {
return Ok(());
};
let answer = prompt
.layout(&self.gui.atlas, self.gui_size())
.answer_at(self.cursor);
match answer {
Some(yes) => {
self.audio.play_button_click();
self.answer_pack_prompt(yes)
}
None => Ok(()),
}
}
}
@@ -219,12 +219,11 @@ pub(super) fn spawn_loader(
.name("resource-loader".into())
.spawn(move || {
let mut pack_error = None;
let root = packs::startup_root(&vanilla_root, &settings.resource_packs).unwrap_or_else(
|error| {
let root = packs::startup_root(&vanilla_root, &settings.resource_packs, &[])
.unwrap_or_else(|error| {
pack_error = Some(error.to_string());
vanilla_root.clone()
},
);
});
let root = mods::content_root(&root, &settings.mods.enabled, &dev_mods);
let result = load_resources(
root,
+16 -1
View File
@@ -81,6 +81,12 @@ pub const MINIMAP_SPRITE: &str = "horizon/minimap";
pub const SKIN_SLOTS: usize = 32;
/// Reused by the visible rows of the classic world selector.
pub const WORLD_ICON_SLOTS: usize = 32;
/// Atlas slots for the pack icons on the pack screen, one per icon drawn
/// (`PackSelectionScreen.loadPackIcon` registers a texture per pack): two lists
/// of 36-pixel rows at GUI scale 2 on a 4K screen still fit.
pub const PACK_ICON_SLOTS: usize = 64;
/// A pack icon slot's side: vanilla's own icons are 128x128.
pub const PACK_ICON_SIZE: u32 = 128;
/// Atlas slots for armour trim textures made at run time (`trims`), each the
/// size of the largest trim texture.
pub const TRIM_SLOTS: usize = 32;
@@ -252,7 +258,7 @@ impl HudAtlas {
)
}
/// Empty slots written at run time: map textures (game/maps.rs), the
/// minimap, downloaded skins, world icons and the on-screen keyboard's text.
/// minimap, downloaded skins, world and pack icons and the on-screen keyboard's text.
fn slots(images: &mut Vec<PackedImage>, trim: (u32, u32)) {
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
@@ -284,6 +290,15 @@ impl HudAtlas {
vec![0; 64 * 64 * 4],
));
}
let side = PACK_ICON_SIZE as usize;
for i in 0..PACK_ICON_SLOTS {
images.push((
format!("horizon/pack-icon{i}"),
PACK_ICON_SIZE,
PACK_ICON_SIZE,
vec![0; side * side * 4],
));
}
// The on-screen keyboard's text and corner masks (ui_theme), rasterized at run time.
images.push((
"horizon/ui-text".into(),
+2
View File
@@ -41,6 +41,7 @@ pub mod command;
pub mod command_block;
pub mod command_storage;
pub mod component;
pub mod confirm_screen;
pub mod container_screen;
pub mod containers;
pub mod control;
@@ -157,6 +158,7 @@ pub mod screen_effects;
pub mod screen_layout;
pub mod sculk;
pub use horizon_server_files as server;
pub mod server_packs;
pub mod settings;
pub mod shadows;
pub mod signs;
+94 -2
View File
@@ -67,6 +67,9 @@ pub enum Screen {
name: String,
address: String,
focus: u8,
/// Server Resource Packs (`acceptTextures`): Enabled, Disabled, or
/// none for Prompt.
packs: Option<bool>,
},
Direct {
address: String,
@@ -224,6 +227,19 @@ fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option
}
}
/// The Server Resource Packs button's label: `CommonComponents.optionNameValue`.
fn pack_setting_label(packs: Option<bool>) -> String {
let (key, fallback) = match packs {
Some(true) => ("manageServer.resourcePack.enabled", "Enabled"),
Some(false) => ("manageServer.resourcePack.disabled", "Disabled"),
None => ("manageServer.resourcePack.prompt", "Prompt"),
};
let name = crate::lang::get_or("manageServer.resourcePack", "Server Resource Packs");
crate::lang::get_or("options.generic_value", "%s: %s")
.replacen("%s", &name, 1)
.replacen("%s", &crate::lang::get_or(key, fallback), 1)
}
/// JoinMultiplayerScreen's `HeaderAndFooterLayout(33, 60)`.
const HEADER: f32 = 33.0;
const FOOTER: f32 = 60.0;
@@ -461,7 +477,16 @@ impl Screen {
),
]
}
Self::Edit { address, .. } => vec![
Self::Edit { address, packs, .. } => vec![
// ManageServerScreen's CycleButton, above Done.
b(
w / 2.0 - 100.0,
h / 4.0 + 72.0,
200.0,
&pack_setting_label(*packs),
true,
60,
),
b(
w / 2.0 - 100.0,
h / 4.0 + 96.0 + 18.0,
@@ -847,6 +872,7 @@ impl Screen {
name,
address,
focus,
..
} => {
centered(
batch,
@@ -996,6 +1022,7 @@ impl Screen {
name: "Minecraft Server".into(),
address: String::new(),
focus: 1,
packs: None,
}
}
(
@@ -1011,6 +1038,7 @@ impl Screen {
name: s.name,
address: s.ip,
focus: 0,
packs: s.accept_textures,
};
}
}
@@ -1125,21 +1153,32 @@ impl Screen {
*selected = Some(index);
}
}
// CycleButton: Enabled, Disabled, Prompt, and round again.
(Self::Edit { packs, .. }, Some(60)) => {
*packs = match *packs {
Some(true) => Some(false),
Some(false) => None,
None => Some(true),
}
}
(
Self::Edit {
index,
name,
address,
packs,
..
},
Some(50),
) => {
let mut list = servers::load(&servers_file(saves));
let entry = ServerEntry::new(name.trim(), address.trim());
let mut entry = ServerEntry::new(name.trim(), address.trim());
entry.accept_textures = *packs;
match index.and_then(|i| list.get_mut(i)) {
Some(e) => {
e.name = entry.name;
e.ip = entry.ip;
e.accept_textures = entry.accept_textures;
}
None => list.push(entry),
}
@@ -1637,4 +1676,57 @@ mod tests {
assert_eq!(names(), ["Keep"]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn edit_cycles_and_saves_the_server_resource_pack_setting() {
let dir = std::env::temp_dir().join(format!("horizon-mp-packs-{}", std::process::id()));
let saves = dir.join("saves");
std::fs::create_dir_all(&saves).unwrap();
let file = servers_file(&saves);
let mut entry = ServerEntry::new("Packs", "127.0.0.1:4");
entry.accept_textures = Some(false);
servers::save(&file, &[entry]).unwrap();
let size = (427.0, 240.0);
let mut screen = Screen::list(&saves);
if let Screen::List { selected, .. } = &mut screen {
*selected = Some(0);
}
screen.click(Some(43), 0.0, 0.0, size, &saves);
let cycle = |screen: &Screen| {
screen
.buttons(size.0, size.1)
.into_iter()
.find(|b| b.5 == 60)
.map(|b| (b.0, b.1, b.2, b.3))
};
// ManageServerScreen: 200 wide at height / 4 + 72, the saved value first.
assert_eq!(
cycle(&screen),
Some((
113.5,
132.0,
200.0,
"Server Resource Packs: Disabled".into()
))
);
// Disabled, Prompt, Enabled: Cancel keeps what was saved.
screen.click(Some(60), 0.0, 0.0, size, &saves);
assert_eq!(cycle(&screen).unwrap().3, "Server Resource Packs: Prompt");
screen.click(Some(51), 0.0, 0.0, size, &saves);
assert_eq!(servers::load(&file)[0].accept_textures, Some(false));
// Done saves it.
if let Screen::List { selected, .. } = &mut screen {
*selected = Some(0);
}
screen.click(Some(43), 0.0, 0.0, size, &saves);
screen.click(Some(60), 0.0, 0.0, size, &saves);
screen.click(Some(60), 0.0, 0.0, size, &saves);
assert_eq!(cycle(&screen).unwrap().3, "Server Resource Packs: Enabled");
screen.click(Some(50), 0.0, 0.0, size, &saves);
assert_eq!(servers::load(&file)[0].accept_textures, Some(true));
// A new server asks.
screen.click(Some(42), 0.0, 0.0, size, &saves);
assert_eq!(cycle(&screen).unwrap().3, "Server Resource Packs: Prompt");
let _ = std::fs::remove_dir_all(&dir);
}
}
+58 -15
View File
@@ -20,6 +20,7 @@ use horizon_protocol::{
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
mpsc::{Receiver, Sender, channel},
},
thread::JoinHandle,
@@ -43,6 +44,10 @@ pub enum Event {
DecodeError(String),
/// The server sent us back to configuration and finished it again.
Reconfigured(Arc<Dynamic>),
/// ClientboundResourcePackPushPacket, in configuration or in play.
PackPush(cfg::ResourcePackPush),
/// ClientboundResourcePackPopPacket: one pack, or every pack.
PackPop(Option<u128>),
/// The connection ended. `from_server`: the server gave the reason (or
/// the connection was refused for good), rather than the connection
/// failing (auto-reconnect retries only failures and shutdowns).
@@ -55,6 +60,9 @@ pub enum Event {
pub struct Session {
events: Receiver<Event>,
writer: Arc<Mutex<Option<ConnWriter>>>,
/// The connection is in configuration (else in play). Changed only
/// with `writer` locked, as the packet that switches is sent.
configuring: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
pub address: String,
pub name: String,
@@ -92,8 +100,10 @@ impl Session {
) -> Self {
let (send, events) = channel();
let writer = Arc::new(Mutex::new(None));
let configuring = Arc::new(AtomicBool::new(true));
let counters = Arc::new(Mutex::new(None));
let (thread_writer, thread_counters) = (writer.clone(), counters.clone());
let thread_configuring = configuring.clone();
let (address_owned, name_owned) = (address.to_owned(), name.to_owned());
let thread = std::thread::Builder::new()
.name("horizon-net".into())
@@ -107,6 +117,7 @@ impl Session {
&lang,
&send,
&thread_writer,
&thread_configuring,
&thread_counters,
);
let from_server = result.is_ok();
@@ -124,6 +135,7 @@ impl Session {
Self {
events,
writer,
configuring,
thread,
address: address.to_owned(),
name: name.to_owned(),
@@ -153,6 +165,21 @@ impl Session {
w.shutdown();
}
}
/// ServerboundResourcePackPacket, in whichever phase the connection is.
pub fn send_pack_status(&self, id: u128, action: i32) {
let status = cfg::ResourcePackResponse { id, action };
let mut writer = self.writer.lock().unwrap();
let body = if self.configuring.load(Ordering::Relaxed) {
cfg::Serverbound::ResourcePack(status).encode()
} else {
play::Serverbound::ResourcePack(status).encode()
};
if let Some(w) = writer.as_mut()
&& w.send(&body).is_err()
{
w.shutdown();
}
}
pub fn disconnect(&mut self) {
if let Some(w) = self.writer.lock().unwrap().take() {
w.shutdown();
@@ -253,6 +280,7 @@ fn run(
lang: &Language,
send: &Sender<Event>,
shared_writer: &Mutex<Option<ConnWriter>>,
configuring: &AtomicBool,
shared_counters: &Mutex<Option<Arc<Counters>>>,
) -> Result<String, String> {
let (host, port, mut c) = if let Some(pipe) = local {
@@ -377,18 +405,19 @@ fn run(
.map_err(e)?;
let (mut reader, writer) = c.split();
*shared_writer.lock().unwrap() = Some(writer);
let registries = configure(&mut reader, shared_writer, lang, send)?;
let registries = configure(&mut reader, shared_writer, configuring, lang, send)?;
let _ = send.send(Event::Joined {
registries: Arc::new(registries),
uuid: profile.uuid,
name: profile.name,
});
receive_play(&mut reader, shared_writer, lang, send)
receive_play(&mut reader, shared_writer, configuring, lang, send)
}
fn receive_play(
reader: &mut ConnReader,
shared_writer: &Mutex<Option<ConnWriter>>,
configuring: &AtomicBool,
lang: &Language,
send: &Sender<Event>,
) -> Result<String, String> {
@@ -416,15 +445,17 @@ fn receive_play(
play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)),
play::Clientbound::BundleDelimiter(_) => {}
play::Clientbound::ResourcePackPush(p) => {
// Declined: Horizon has no server resource packs.
reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse {
id: p.id,
action: 1,
}));
let _ = send.send(Event::PackPush(p));
}
play::Clientbound::ResourcePackPop(p) => {
let _ = send.send(Event::PackPop(p.id));
}
play::Clientbound::StartConfiguration(_) => {
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
let registries = configure(reader, shared_writer, lang, send)?;
if let Some(w) = shared_writer.lock().unwrap().as_mut() {
let _ = w.send(&play::Serverbound::ConfigurationAcknowledged(Empty).encode());
configuring.store(true, Ordering::Relaxed);
}
let registries = configure(reader, shared_writer, configuring, lang, send)?;
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
}
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
@@ -445,6 +476,7 @@ fn receive_play(
fn configure(
reader: &mut ConnReader,
writer: &Mutex<Option<ConnWriter>>,
configuring: &AtomicBool,
lang: &Language,
send: &Sender<Event>,
) -> Result<Dynamic, String> {
@@ -471,11 +503,12 @@ fn configure(
cfg::Clientbound::CodeOfConduct(_) => {
reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))?
}
// The game answers: it may prompt the player first.
cfg::Clientbound::ResourcePackPush(p) => {
reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse {
id: p.id,
action: 1,
}))?
let _ = send.send(Event::PackPush(p));
}
cfg::Clientbound::ResourcePackPop(p) => {
let _ = send.send(Event::PackPop(p.id));
}
cfg::Clientbound::CookieRequest(q) => {
reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse {
@@ -485,7 +518,11 @@ fn configure(
}
cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)),
cfg::Clientbound::FinishConfiguration(_) => {
reply(cfg::Serverbound::FinishConfiguration(Empty))?;
let mut w = writer.lock().unwrap();
let w = w.as_mut().ok_or("Disconnected")?;
w.send(&cfg::Serverbound::FinishConfiguration(Empty).encode())
.map_err(|e| e.to_string())?;
configuring.store(false, Ordering::Relaxed);
return Ok(registries);
}
_ => {}
@@ -602,7 +639,13 @@ mod tests {
let (send, events) = channel();
let thread_writer = writer.clone();
let thread = std::thread::spawn(move || {
receive_play(&mut reader, &thread_writer, &Language::new(), &send)
receive_play(
&mut reader,
&thread_writer,
&AtomicBool::new(false),
&Language::new(),
&send,
)
});
let mut server = Connection::local(server);
let teleport = play::Clientbound::PlayerPosition(play::PlayerPosition {
+3 -1
View File
@@ -2079,7 +2079,9 @@ impl OptionsUi {
let blink = self.pack_focus.elapsed().as_millis() as u64;
let m = crate::screen_draw::Measure(&atlas.font);
let mouse = (cursor.0.floor() as i32, cursor.1.floor() as i32);
let draws = self.packs(atlas, (w, h)).draw(&m, mouse, blink);
let packs = self.packs(atlas, (w, h));
let mut draws = packs.draw(&m, mouse, blink);
packs.bind_icons(&mut draws, atlas, &mut batch.patches);
crate::screen_draw::paint(batch, atlas, &draws);
return;
}
+163 -3
View File
@@ -6,10 +6,13 @@
//! [`PackScreen::draw`] gives the screen's GUI calls. The game shows it;
//! tools/test_pack_screen_parity.py compares it with vanilla.
use crate::{
font::Patch,
hud::{HudAtlas, PACK_ICON_SIZE, PACK_ICON_SLOTS},
packs::{Position, Selectable, SelectionModel},
screen_draw::{self as d, Draw, Measure, TextField},
text::{Style, Text},
};
use std::{collections::HashMap, sync::Arc};
/// `PackCompatibility`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -50,8 +53,8 @@ pub struct PackInfo {
pub description_style: Style,
pub source: Source,
pub compat: Compat,
/// Whether the pack has a `pack.png`.
pub icon: bool,
/// The pack's `pack.png` ([`load_icon`]); none draws `unknown_pack`.
pub icon: Option<Arc<[u8]>>,
pub required: bool,
pub position: Position,
pub fixed: bool,
@@ -90,6 +93,27 @@ impl PackInfo {
(t, Style::color(d::GRAY))
}
}
/// A `pack.png` as the pack screen draws it: RGBA, stretched to a
/// `PACK_ICON_SIZE` square by nearest texels, as vanilla's icon texture is
/// sampled into its 32x32 square. None when it does not decode, where
/// `loadPackIcon` falls back to `unknown_pack`.
pub fn load_icon(png: &[u8]) -> Option<Arc<[u8]>> {
let (w, h, rgba) = crate::hud::decode_bytes(png).ok()?;
if w == 0 || h == 0 {
return None;
}
let size = u64::from(PACK_ICON_SIZE);
let mut out = Vec::with_capacity((size * size * 4) as usize);
for y in 0..size {
let sy = ((2 * y + 1) * u64::from(h) / (2 * size)) as usize;
for x in 0..size {
let sx = ((2 * x + 1) * u64::from(w) / (2 * size)) as usize;
let at = (sy * w as usize + sx) * 4;
out.extend_from_slice(&rgba[at..at + 4]);
}
}
Some(out.into())
}
/// `PackSelectionScreen.loadPackIcon`'s texture for a pack with an icon.
pub fn icon_texture(id: &str) -> String {
let sanitized: String = id
@@ -306,6 +330,8 @@ pub struct PackScreen {
confirm: Option<Confirm>,
/// The selection changed since the screen opened.
pub changed: bool,
/// The packs' icons by their [`icon_texture`].
icons: HashMap<String, Arc<[u8]>>,
}
fn tr(key: &str) -> Text {
@@ -329,11 +355,16 @@ impl PackScreen {
italic: Some(true),
..Style::default()
}));
let icons = packs
.iter()
.filter_map(|p| Some((icon_texture(&p.id), p.icon.clone()?)))
.collect();
let mut s = Self {
width,
height,
in_world,
packs,
icons,
model,
search,
focus: Focus::None,
@@ -760,6 +791,35 @@ impl PackScreen {
pub fn commit(&self) -> Vec<String> {
self.model.commit()
}
/// Points the icon blits of `draws` at the atlas's pack icon slots and
/// writes the icons into them, one slot per icon drawn (vanilla registers a
/// texture per pack). Icons past the last slot keep `unknown_pack`.
pub fn bind_icons(&self, draws: &mut [Draw], atlas: &HudAtlas, patches: &mut Vec<Patch>) {
let mut slots = 0..PACK_ICON_SLOTS;
for draw in draws {
let Draw::Blit { texture, .. } = draw else {
continue;
};
let Some(icon) = self.icons.get(texture.as_str()) else {
continue;
};
let Some(slot) = slots.next() else {
return;
};
let sprite = format!("horizon/pack-icon{slot}");
let Some(rect) = atlas.sprites.get(&sprite) else {
return;
};
patches.push(Patch {
x: (rect.u0 * atlas.width as f32).round() as u32,
y: (rect.v0 * atlas.height as f32).round() as u32,
width: PACK_ICON_SIZE,
height: PACK_ICON_SIZE,
rgba: icon.to_vec(),
});
*texture = sprite;
}
}
/// The shown screen's calls (`Screen.extractRenderState`); `blink_ms`
/// is the time since the search box took the focus.
@@ -891,7 +951,7 @@ impl PackScreen {
-8978432,
);
}
let icon = if p.icon {
let icon = if p.icon.is_some() {
icon_texture(id)
} else {
"textures/misc/unknown_pack.png".into()
@@ -979,6 +1039,106 @@ impl PackScreen {
}
}
#[cfg(test)]
mod icon_tests {
use super::*;
fn png(w: u32, h: u32, rgba: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, w, h);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(rgba)
.unwrap();
out
}
fn pack(id: &str, icon: Option<Arc<[u8]>>) -> PackInfo {
PackInfo {
id: id.into(),
title: Text::literal(id),
description: Text::literal(""),
description_style: Style::default(),
source: Source::BuiltIn,
compat: Compat::Compatible,
icon,
required: false,
position: Position::Top,
fixed: false,
}
}
/// Any size stretches over the whole square, nearest texels, as the
/// icon texture is sampled into its 32x32 blit.
#[test]
fn icons_stretch_to_the_slot_by_nearest_texels() {
let (red, blue) = ([255, 0, 0, 255], [0, 0, 255, 128]);
let icon = load_icon(&png(2, 1, &[red, blue].concat())).unwrap();
let side = PACK_ICON_SIZE as usize;
assert_eq!(icon.len(), side * side * 4);
let at = |x: usize, y: usize| &icon[(y * side + x) * 4..][..4];
assert_eq!((at(0, 0), at(side / 2 - 1, side - 1)), (&red[..], &red[..]));
assert_eq!(
(at(side / 2, 0), at(side - 1, side - 1)),
(&blue[..], &blue[..])
);
assert!(load_icon(b"not a png").is_none());
}
/// Programmer Art and High Contrast draw their own `pack.png`; a pack
/// without one keeps `unknown_pack`.
#[test]
fn drawn_icons_take_atlas_slots() {
let atlas =
crate::hud::HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets"))
.unwrap();
let m = Measure(&atlas.font);
let dirt = load_icon(&png(1, 1, &[134, 96, 67, 255])).unwrap();
let contrast = load_icon(&png(1, 1, &[0, 0, 0, 255])).unwrap();
let packs = vec![
pack("programmer_art", Some(dirt.clone())),
pack("high_contrast", Some(contrast.clone())),
pack("file/Iconless", None),
];
let screen = PackScreen::new(&m, 480, 320, false, packs, &[]);
let mut draws = screen.draw(&m, (0, 0), 0);
let mut patches = Vec::new();
screen.bind_icons(&mut draws, &atlas, &mut patches);
let icons: Vec<&str> = draws
.iter()
.filter_map(|d| match d {
Draw::Blit { texture, .. } if texture.contains("pack") => Some(texture.as_str()),
_ => None,
})
.collect();
// The list shows them sorted by id.
assert_eq!(
icons,
[
"textures/misc/unknown_pack.png",
"horizon/pack-icon0",
"horizon/pack-icon1"
]
);
assert_eq!(patches.len(), 2);
for (i, (patch, icon)) in patches.iter().zip([&contrast, &dirt]).enumerate() {
let rect = atlas.sprites[&format!("horizon/pack-icon{i}")];
assert_eq!(
(patch.x, patch.y, patch.width, patch.height),
(
(rect.u0 * atlas.width as f32).round() as u32,
(rect.v0 * atlas.height as f32).round() as u32,
PACK_ICON_SIZE,
PACK_ICON_SIZE
)
);
assert_eq!(&patch.rgba[..], &icon[..]);
}
}
}
#[cfg(test)]
mod click_sound_tests {
use super::*;
+59 -7
View File
@@ -34,8 +34,6 @@ pub struct Pack {
pub description_style: Style,
pub compatible: bool,
pub compatibility: crate::pack_screen::Compat,
/// The pack has a `pack.png`.
pub icon: bool,
/// Overlay directories active for this game version, in `pack.mcmeta` order.
pub overlays: Vec<String>,
/// `filter.block` entries (namespace and path patterns) hiding resources
@@ -260,6 +258,15 @@ fn filter_of(meta: &serde_json::Value) -> Vec<Filter> {
})
.collect()
}
impl Pack {
/// The pack's `pack.png` (`PackResources.getRootResource`), for its icon.
pub fn icon_png(&self) -> Option<Vec<u8>> {
match &self.source {
Source::Dir(d) => fs::read(d.join("pack.png")).ok(),
Source::Zip(z) => Zip::open(z).ok()?.read("pack.png").ok(),
}
}
}
fn read_meta(source: &Source) -> Option<serde_json::Value> {
let bytes = match source {
Source::Dir(d) => fs::read(d.join("pack.mcmeta")).ok()?,
@@ -270,10 +277,6 @@ fn read_meta(source: &Source) -> Option<serde_json::Value> {
fn pack(id: String, title: Text, source: Source) -> Option<Pack> {
let meta = read_meta(&source)?;
let (raw_description, description_style) = component_root(&meta["pack"]["description"]);
let icon = match &source {
Source::Dir(d) => d.join("pack.png").is_file(),
Source::Zip(z) => Zip::open(z).is_ok_and(|z| z.read("pack.png").is_ok()),
};
Some(Pack {
id,
title,
@@ -282,7 +285,6 @@ fn pack(id: String, title: Text, source: Source) -> Option<Pack> {
description_style,
compatible: compatible(&meta),
compatibility: compatibility(&meta),
icon,
overlays: overlays_of(&meta),
filter: filter_of(&meta),
source,
@@ -629,6 +631,17 @@ fn merge(kind: Merge, layers: &[Vec<u8>]) -> Option<Vec<u8>> {
};
serde_json::to_vec(&out).ok()
}
/// `DownloadedPackSource.loadRequestedPacks`: a server's downloaded pack,
/// "World Specific Resources"; None when its `pack.mcmeta` can't be read. Its
/// id names the file, which is named after its hash.
pub fn server_pack(id: u128, path: &Path) -> Option<Pack> {
let file = path.file_name()?.to_string_lossy();
pack(
format!("server/{id:032x}/{file}"),
Text::translate("resourcePack.server.name", &[]),
Source::Zip(path.to_path_buf()),
)
}
/// The packs to apply for an options.txt `resourcePacks` list (bottom first).
pub fn enabled(all: &[Pack], ids: &[String]) -> Vec<Pack> {
ids.iter()
@@ -983,6 +996,45 @@ mod tests {
let _ = fs::remove_dir_all(base);
}
#[test]
fn built_in_and_folder_packs_give_their_pack_png() {
use std::io::Write as _;
let base = std::env::temp_dir().join(format!("horizon-pack-icons-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let meta = br#"{"pack":{"description":"d","pack_format":97}}"#;
let built_in = base.join("vanilla/assets/minecraft/resourcepacks");
fs::create_dir_all(&built_in).unwrap();
let mut zip =
zip::ZipWriter::new(fs::File::create(built_in.join("programmer_art.zip")).unwrap());
for (name, data) in [("pack.mcmeta", &meta[..]), ("pack.png", b"dirt")] {
zip.start_file(name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(data).unwrap();
}
zip.finish().unwrap();
for (name, icon) in [("Iconless", None), ("Mine", Some(&b"mine"[..]))] {
let dir = base.join("packs").join(name);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("pack.mcmeta"), meta).unwrap();
if let Some(icon) = icon {
fs::write(dir.join("pack.png"), icon).unwrap();
}
}
let packs = discover(&base.join("vanilla"), &base.join("packs"));
let icons: Vec<_> = packs
.iter()
.map(|p| (p.id.as_str(), p.icon_png()))
.collect();
assert_eq!(
icons,
[
("programmer_art", Some(b"dirt".to_vec())),
("file/Iconless", None),
("file/Mine", Some(b"mine".to_vec())),
]
);
let _ = fs::remove_dir_all(base);
}
#[test]
fn overlays_and_filters() {
let v = |s: &str| serde_json::from_str::<serde_json::Value>(s).unwrap();
let meta = v(r#"{"overlays":{"entries":[
+618
View File
@@ -0,0 +1,618 @@
//! Server resource packs (`ServerPackManager`, `DownloadedPackSource`): the
//! packs a server pushes, the player's answer to its prompt, their downloads,
//! their activation on top of the player's own packs, and the status each one
//! reports back to the server. The game drives it: it shows the prompt,
//! starts the downloads [`ServerPacks::tick`] asks for and reloads the
//! resources with [`ServerPacks::active`] when it asks for a reload.
pub mod download;
use std::path::PathBuf;
/// `ServerboundResourcePackPacket.Action`, by its protocol number.
pub mod action {
pub const SUCCESSFULLY_LOADED: i32 = 0;
pub const DECLINED: i32 = 1;
pub const FAILED_DOWNLOAD: i32 = 2;
pub const ACCEPTED: i32 = 3;
pub const DOWNLOADED: i32 = 4;
pub const INVALID_URL: i32 = 5;
pub const FAILED_RELOAD: i32 = 6;
pub const DISCARDED: i32 = 7;
}
/// `ServerPackManager.PackPromptStatus`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Prompt {
Pending,
Allowed,
Declined,
}
impl Prompt {
/// `ConnectScreen.convertPackStatus`: a server list entry's setting
/// (servers.dat `acceptTextures`; none is Prompt).
pub fn for_server(accept_textures: Option<bool>) -> Self {
match accept_textures {
Some(true) => Self::Allowed,
Some(false) => Self::Declined,
None => Self::Pending,
}
}
}
/// `ClientCommonPacketListenerImpl.parseResourcePackUrl`: only http and https.
pub fn valid_url(url: &str) -> bool {
url.split_once(':').is_some_and(|(scheme, _)| {
scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
})
}
/// `DownloadedPackSource.tryParseSha1Hash`: 40 hex digits, else no check.
pub fn parse_sha1(hash: &str) -> Option<String> {
(hash.len() == 40 && hash.bytes().all(|b| b.is_ascii_hexdigit()))
.then(|| hash.to_ascii_lowercase())
}
/// One pack to download (`DownloadQueue.DownloadRequest`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Request {
pub id: u128,
pub url: String,
pub sha1: Option<String>,
}
/// `DownloadQueue.BatchResult`: the file each downloaded pack is in, and the
/// packs that failed.
#[derive(Debug, Default)]
pub struct Batch {
pub downloaded: Vec<(u128, PathBuf)>,
pub failed: Vec<u128>,
}
/// What the game has to do after a [`ServerPacks::tick`].
#[derive(Debug, Default, PartialEq)]
pub struct Tick {
/// Download these, then hand the result to [`ServerPacks::downloaded`].
pub download: Vec<Request>,
/// Reload the resources with these packs on top, bottom first
/// (`PackReloadConfig.scheduleReload`), then call [`ServerPacks::reloaded`].
pub reload: Option<Vec<(u128, PathBuf)>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Download {
Requested,
Pending,
Done,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Activation {
Inactive,
Pending,
Active,
}
/// `ServerPackManager.RemovalReason`, with the status it reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Removal {
DownloadFailed,
ActivationFailed,
Declined,
Discarded,
ServerRemoved,
ServerReplaced,
}
impl Removal {
fn reply(self) -> Option<i32> {
match self {
Self::DownloadFailed => Some(action::FAILED_DOWNLOAD),
Self::ActivationFailed => Some(action::FAILED_RELOAD),
Self::Declined => Some(action::DECLINED),
Self::Discarded => Some(action::DISCARDED),
Self::ServerRemoved | Self::ServerReplaced => None,
}
}
}
/// `ServerPackManager.ServerPackData`.
#[derive(Debug)]
struct Pack {
id: u128,
url: String,
sha1: Option<String>,
path: Option<PathBuf>,
removal: Option<Removal>,
download: Download,
activation: Activation,
accepted: bool,
}
impl Pack {
fn remove(&mut self, reason: Removal) {
self.removal.get_or_insert(reason);
}
fn removed(&self) -> bool {
self.removal.is_some()
}
}
/// The reload in progress: the packs it loads and unloads (the callbacks
/// `triggerReloadIfNeeded` gives `scheduleReload`).
#[derive(Debug)]
struct Reload {
load: Vec<u128>,
unload: Vec<u128>,
/// It reloads what was active before a failed one (`isRecovery`).
recovery: bool,
}
/// `ServerPackManager` with the feedback `DownloadedPackSource` gives it.
#[derive(Debug)]
pub struct ServerPacks {
packs: Vec<Pack>,
prompt: Prompt,
reload: Option<Reload>,
/// `registerForUpdate`: something changed, [`Self::tick`] again.
update: bool,
/// Report to the server (`configureForServerControl`); otherwise the
/// statuses are only logged, as for a local world.
reporting: bool,
replies: Vec<(u128, i32)>,
}
impl Default for ServerPacks {
fn default() -> Self {
Self {
packs: Vec::new(),
prompt: Prompt::Pending,
reload: None,
update: false,
reporting: false,
replies: Vec::new(),
}
}
}
impl ServerPacks {
fn report(&mut self, id: u128, status: i32) {
log::debug!("Horizon: server pack {id:032x} changed status to {status}");
if self.reporting {
self.replies.push((id, status));
}
}
/// The statuses to send the server, oldest first.
pub fn take_replies(&mut self) -> Vec<(u128, i32)> {
std::mem::take(&mut self.replies)
}
/// Whether [`Self::tick`] has something to do.
pub fn wants_tick(&self) -> bool {
self.update
}
/// `DownloadedPackSource.configureForServerControl`.
pub fn connect(&mut self, prompt: Prompt) {
self.reporting = true;
match prompt {
Prompt::Allowed => self.allow(),
Prompt::Declined => self.reject(),
Prompt::Pending => self.prompt = Prompt::Pending,
}
}
/// `DownloadedPackSource.configureForLocalWorld`: single player's own
/// server; its packs are taken, and nothing is reported.
pub fn local_world(&mut self) {
self.reporting = false;
self.allow();
}
/// `DownloadedPackSource.cleanupAfterDisconnect`: every pack goes, and
/// the next server starts from its own setting.
pub fn disconnect(&mut self) {
self.pop_all();
self.reporting = false;
self.replies.clear();
self.prompt = Prompt::Pending;
}
pub fn push(&mut self, id: u128, url: &str, sha1: Option<String>) {
if self.prompt == Prompt::Declined {
self.report(id, action::DECLINED);
return;
}
for pack in self.packs.iter_mut().filter(|p| p.id == id) {
pack.remove(Removal::ServerReplaced);
}
self.packs.push(Pack {
id,
url: url.to_owned(),
sha1,
path: None,
removal: None,
download: Download::Requested,
activation: Activation::Inactive,
accepted: false,
});
if self.prompt == Prompt::Allowed {
self.accept(self.packs.len() - 1);
}
self.update = true;
}
fn accept(&mut self, i: usize) {
self.packs[i].accepted = true;
let id = self.packs[i].id;
self.report(id, action::ACCEPTED);
}
pub fn pop(&mut self, id: u128) {
if let Some(pack) = self.packs.iter_mut().find(|p| !p.removed() && p.id == id) {
pack.remove(Removal::ServerRemoved);
self.update = true;
}
}
pub fn pop_all(&mut self) {
for pack in &mut self.packs {
pack.remove(Removal::ServerRemoved);
}
self.update = true;
}
/// `allowServerPacks`: the prompt said yes (or the server is Enabled).
pub fn allow(&mut self) {
self.prompt = Prompt::Allowed;
for i in 0..self.packs.len() {
if !self.packs[i].accepted && !self.packs[i].removed() {
self.accept(i);
}
}
self.update = true;
}
/// `rejectServerPacks`: the prompt said no (or the server is Disabled).
pub fn reject(&mut self) {
self.prompt = Prompt::Declined;
for pack in self.packs.iter_mut().filter(|p| !p.accepted) {
pack.remove(Removal::Declined);
}
self.update = true;
}
/// `ServerPackManager.tick`: start the downloads the accepted packs
/// need; once none is left, reload if the active packs should change;
/// then forget the packs that are gone, reporting why.
pub fn tick(&mut self) -> Tick {
self.update = false;
let mut out = Tick::default();
let mut downloading = false;
for pack in self.packs.iter_mut().filter(|p| !p.removed() && p.accepted) {
downloading |= pack.download != Download::Done;
if pack.download == Download::Requested {
pack.download = Download::Pending;
out.download.push(Request {
id: pack.id,
url: pack.url.clone(),
sha1: pack.sha1.clone(),
});
}
}
if !downloading {
out.reload = self.reload_if_needed();
}
let mut gone = Vec::new();
self.packs.retain(|p| {
let keep = p.activation != Activation::Inactive || p.removal.is_none();
if !keep && let Some(reply) = p.removal.and_then(Removal::reply) {
gone.push((p.id, reply));
}
keep
});
for (id, reply) in gone {
self.report(id, reply);
}
out
}
fn reload_if_needed(&mut self) -> Option<Vec<(u128, PathBuf)>> {
if self.reload.is_some()
|| self
.packs
.iter()
.any(|p| p.activation == Activation::Pending)
{
return None;
}
let mut changed = false;
let (mut load, mut unload) = (Vec::new(), Vec::new());
for pack in &self.packs {
let wanted = pack.accepted && pack.download == Download::Done && !pack.removed();
match pack.activation {
Activation::Inactive if wanted => {
load.push(pack.id);
changed = true;
}
Activation::Active if wanted => load.push(pack.id),
Activation::Active => {
unload.push(pack.id);
changed = true;
}
_ => {}
}
}
if !changed {
return None;
}
for pack in &mut self.packs {
let loading = load.contains(&pack.id) && pack.activation != Activation::Active;
if loading || unload.contains(&pack.id) {
pack.activation = Activation::Pending;
}
}
let paths = self.paths(&load);
self.reload = Some(Reload {
load,
unload,
recovery: false,
});
Some(paths)
}
/// The packs to load (`PackReloadConfig.Callbacks.packsToLoad`), bottom first.
fn paths(&self, ids: &[u128]) -> Vec<(u128, PathBuf)> {
ids.iter()
.filter_map(|id| {
let pack = self
.packs
.iter()
.find(|p| p.id == *id && p.path.is_some())?;
Some((*id, pack.path.clone()?))
})
.collect()
}
/// `ServerPackManager.onDownload`.
pub fn downloaded(&mut self, batch: Batch) {
if !batch.failed.is_empty() {
for pack in self
.packs
.iter_mut()
.filter(|p| p.activation != Activation::Active)
{
pack.remove(if batch.failed.contains(&pack.id) {
Removal::DownloadFailed
} else {
Removal::Discarded
});
}
}
let mut done = Vec::new();
for (id, path) in batch.downloaded {
if let Some(pack) = self
.packs
.iter_mut()
.find(|p| p.id == id && p.download == Download::Pending)
{
pack.download = Download::Done;
pack.path = Some(path);
if !pack.removed() {
done.push(id);
}
}
}
for id in done {
self.report(id, action::DOWNLOADED);
}
self.update = true;
}
/// The reload [`Tick::reload`] asked for finished (`Callbacks.onSuccess`),
/// or its packs could not be loaded (`onFailure`). After a first failure
/// the packs that were active are loaded again: the packs to reload with
/// are returned, and this is called again with that reload's outcome.
pub fn reloaded(&mut self, ok: bool) -> Option<Vec<(u128, PathBuf)>> {
let mut reload = self.reload.take()?;
self.update = true;
if ok {
let mut applied = Vec::new();
for pack in &mut self.packs {
if reload.load.contains(&pack.id) {
pack.activation = Activation::Active;
if pack.removal.is_none() {
applied.push(pack.id);
}
} else if reload.unload.contains(&pack.id) {
pack.activation = Activation::Inactive;
}
}
for id in applied {
self.report(id, action::SUCCESSFULLY_LOADED);
}
return None;
}
if reload.recovery {
// onFailure(true): nothing of the server's is loaded.
for pack in &mut self.packs {
if pack.activation == Activation::Pending {
pack.activation = Activation::Inactive;
}
}
return None;
}
reload.load.clear();
for pack in &mut self.packs {
match pack.activation {
Activation::Inactive => pack.remove(Removal::Discarded),
Activation::Pending => {
pack.activation = Activation::Inactive;
pack.remove(Removal::ActivationFailed);
}
Activation::Active => reload.load.push(pack.id),
}
}
reload.recovery = true;
let paths = self.paths(&reload.load);
self.reload = Some(reload);
Some(paths)
}
}
#[cfg(test)]
mod tests {
use super::*;
use action::*;
fn ok(id: u128) -> Batch {
Batch {
downloaded: vec![(id, PathBuf::from(format!("/p/{id}")))],
failed: vec![],
}
}
/// Runs the updates as `createUpdateScheduler` does, downloading and
/// reloading with `download` and `reload` as the game would.
fn settle(
sp: &mut ServerPacks,
download: &mut dyn FnMut(&[Request]) -> Batch,
reload: &mut dyn FnMut(&[(u128, PathBuf)]) -> bool,
) {
let mut rounds = 0;
while sp.wants_tick() {
rounds += 1;
assert!(rounds < 50);
let t = sp.tick();
if !t.download.is_empty() {
let batch = download(&t.download);
sp.downloaded(batch);
}
if let Some(mut packs) = t.reload {
while let Some(back) = sp.reloaded(reload(&packs)) {
packs = back;
}
}
}
}
#[test]
fn an_enabled_server_s_pack_is_accepted_downloaded_and_loaded() {
let mut sp = ServerPacks::default();
sp.connect(Prompt::Allowed);
sp.push(1, "http://a/p.zip", None);
let mut loaded = Vec::new();
settle(&mut sp, &mut |r| ok(r[0].id), &mut |p| {
loaded = p.to_vec();
true
});
assert_eq!(
sp.take_replies(),
[(1, ACCEPTED), (1, DOWNLOADED), (1, SUCCESSFULLY_LOADED)]
);
assert_eq!(loaded, [(1, PathBuf::from("/p/1"))]);
}
#[test]
fn the_prompt_holds_packs_until_answered() {
let mut sp = ServerPacks::default();
sp.connect(Prompt::Pending);
sp.push(1, "http://a/p.zip", None);
settle(&mut sp, &mut |_| unreachable!(), &mut |_| unreachable!());
assert!(sp.take_replies().is_empty());
sp.reject();
settle(&mut sp, &mut |_| unreachable!(), &mut |_| unreachable!());
assert_eq!(sp.take_replies(), [(1, DECLINED)]);
// Declined: later pushes are declined at once.
sp.push(2, "http://a/q.zip", None);
assert_eq!(sp.take_replies(), [(2, DECLINED)]);
}
#[test]
fn a_failed_download_discards_the_rest_of_the_batch() {
let mut sp = ServerPacks::default();
sp.connect(Prompt::Allowed);
sp.push(1, "http://a/p.zip", None);
sp.push(2, "http://a/dead.zip", None);
settle(
&mut sp,
&mut |_| Batch {
downloaded: vec![(1, PathBuf::from("/p/1"))],
failed: vec![2],
},
&mut |_| unreachable!(),
);
assert_eq!(
sp.take_replies(),
[
(1, ACCEPTED),
(2, ACCEPTED),
(1, DISCARDED),
(2, FAILED_DOWNLOAD)
]
);
}
#[test]
fn a_pack_that_does_not_load_fails_its_reload() {
let mut sp = ServerPacks::default();
sp.connect(Prompt::Allowed);
sp.push(1, "http://a/p.zip", None);
let mut reloads = Vec::new();
settle(&mut sp, &mut |r| ok(r[0].id), &mut |p| {
reloads.push(p.to_vec());
reloads.len() > 1
});
assert_eq!(
sp.take_replies(),
[(1, ACCEPTED), (1, DOWNLOADED), (1, FAILED_RELOAD)]
);
// The recovery reload has none of the server's packs.
assert_eq!(reloads[1], []);
}
#[test]
fn popping_and_disconnecting_unload_the_packs() {
let mut sp = ServerPacks::default();
sp.connect(Prompt::Allowed);
sp.push(1, "http://a/p.zip", None);
sp.push(2, "http://a/q.zip", None);
let last = std::cell::RefCell::new(Vec::new());
let mut reload = |p: &[(u128, PathBuf)]| {
*last.borrow_mut() = p.to_vec();
true
};
settle(
&mut sp,
&mut |r| Batch {
downloaded: r
.iter()
.map(|q| (q.id, PathBuf::from(format!("/p/{}", q.id))))
.collect(),
failed: vec![],
},
&mut reload,
);
sp.take_replies();
sp.pop(1);
settle(&mut sp, &mut |_| unreachable!(), &mut reload);
// Callbacks.onSuccess reports every pack the reload loaded, again.
assert_eq!(sp.take_replies(), [(2, SUCCESSFULLY_LOADED)]);
assert_eq!(*last.borrow(), [(2, PathBuf::from("/p/2"))]);
sp.disconnect();
settle(&mut sp, &mut |_| unreachable!(), &mut reload);
assert!(last.borrow().is_empty());
assert!(sp.packs.is_empty());
}
#[test]
fn a_pushed_id_replaces_its_pack() {
let mut sp = ServerPacks::default();
sp.connect(Prompt::Allowed);
sp.push(1, "http://a/old.zip", None);
sp.push(1, "http://a/new.zip", None);
let mut urls = Vec::new();
settle(
&mut sp,
&mut |r| {
urls.extend(r.iter().map(|q| q.url.clone()));
ok(1)
},
&mut |_| true,
);
assert_eq!(urls, ["http://a/new.zip"]);
}
#[test]
fn urls_and_hashes_are_read_as_vanilla_reads_them() {
assert!(valid_url("https://example.com/p.zip"));
assert!(valid_url("HTTP://example.com/p.zip"));
assert!(!valid_url("ftp://example.com/p.zip"));
assert!(!valid_url("example.com/p.zip"));
let sha1 = "0123456789ABCDEF0123456789abcdef01234567";
assert_eq!(parse_sha1(sha1), Some(sha1.to_ascii_lowercase()));
assert_eq!(parse_sha1("abc"), None);
}
}
@@ -0,0 +1,482 @@
//! Server pack downloads into the game directory's `downloads/` cache, as
//! vanilla keeps it (`DownloadQueue`, `HttpUtil.downloadFile`,
//! `DownloadCacheCleaner`): `downloads/<pack id>/<SHA-1 of the file>`, one
//! batch at a time on a thread of its own, every download logged in
//! `downloads/log.json`, and the cache cut to its 20 newest files on start.
use super::{Batch, Request};
use sha1::{Digest, Sha1};
use std::{
fs,
io::{self, Read, Write},
path::{Path, PathBuf},
sync::mpsc::{Receiver, Sender, channel},
time::SystemTime,
};
/// `DownloadedPackSource`'s MAX_PACK_SIZE_BYTES (250 MiB).
pub const MAX_SIZE: u64 = 262_144_000;
/// `DownloadQueue.MAX_KEPT_PACKS`.
const MAX_KEPT: usize = 20;
/// `createDownloadHeaders`: who is downloading, with which game.
pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> {
use horizon_core::version::{RESOURCE_PACK_FORMAT, VANILLA_VERSION, VERSION_ID};
vec![
("X-Minecraft-Username", name.to_owned()),
("X-Minecraft-UUID", format!("{uuid:032x}")),
("X-Minecraft-Version", VANILLA_VERSION.to_owned()),
("X-Minecraft-Version-ID", VERSION_ID.to_owned()),
(
"X-Minecraft-Pack-Format",
format!("{}.{}", RESOURCE_PACK_FORMAT.0, RESOURCE_PACK_FORMAT.1),
),
("User-Agent", format!("Minecraft Java/{VANILLA_VERSION}")),
]
}
type Job = (Vec<Request>, Vec<(&'static str, String)>);
/// `DownloadQueue`: batches download in order, on one thread.
pub struct Queue {
jobs: Sender<Job>,
done: Receiver<Batch>,
}
impl Queue {
pub fn open(dir: PathBuf) -> io::Result<Self> {
fs::create_dir_all(&dir)?;
vacuum(&dir, MAX_KEPT);
let (jobs, todo) = channel::<Job>();
let (finished, done) = channel();
std::thread::Builder::new()
.name("download-queue".into())
.spawn(move || {
for (requests, headers) in todo {
if finished.send(run(&dir, &requests, &headers)).is_err() {
break;
}
}
})?;
Ok(Self { jobs, done })
}
pub fn download(&self, requests: Vec<Request>, headers: Vec<(&'static str, String)>) {
let _ = self.jobs.send((requests, headers));
}
/// The batches finished since the last call.
pub fn finished(&self) -> Vec<Batch> {
self.done.try_iter().collect()
}
}
/// `DownloadQueue.runDownload`: each pack into `<dir>/<id>/`, logged.
fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Batch {
let mut batch = Batch::default();
for request in requests {
let id = horizon_protocol::crypto::uuid_string(request.id);
let result = download_file(&dir.join(&id), request, headers, MAX_SIZE);
// DownloadQueue.LogEntry, its fields in the codec's order.
let mut entry = vec![
("id", serde_json::Value::from(id)),
("url", request.url.as_str().into()),
(
"time",
chrono::Utc::now()
.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)
.into(),
),
];
if let Some(sha1) = &request.sha1 {
entry.push(("hash", sha1.as_str().into()));
}
entry.push(match &result {
Ok(path) => match fs::metadata(path) {
Ok(meta) => {
let name = path.strip_prefix(dir).unwrap_or(path);
let name = name.to_string_lossy().replace('\\', "/");
(
"file",
serde_json::json!({"name": name, "size": meta.len()}),
)
}
Err(_) => ("error", "no_access".into()),
},
Err(e) => {
log::error!("Horizon: failed to download {}: {e}", request.url);
("error", "download_failed".into())
}
});
if let Err(e) = append_log(&dir.join("log.json"), &entry) {
log::error!("Horizon: failed to log download of {}: {e}", request.url);
}
match result {
Ok(path) => batch.downloaded.push((request.id, path)),
Err(_) => batch.failed.push(request.id),
}
}
batch
}
/// `JsonEventLog.write`: one JSON object a line, as Gson writes it (with
/// its HTML escaping).
fn append_log(path: &Path, entry: &[(&str, serde_json::Value)]) -> io::Result<()> {
let fields: Vec<String> = entry
.iter()
.map(|(k, v)| format!("{}:{v}", serde_json::Value::from(*k)))
.collect();
let mut line = String::new();
for c in format!("{{{}}}", fields.join(",")).chars() {
match c {
'<' | '>' | '&' | '=' | '\'' => line.push_str(&format!("\\u{:04x}", c as u32)),
c => line.push(c),
}
}
line.push('\n');
fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?
.write_all(line.as_bytes())
}
fn sha1_of(path: &Path) -> io::Result<String> {
let mut hasher = Sha1::new();
io::copy(&mut fs::File::open(path)?, &mut hasher)?;
Ok(hex(&hasher.finalize()))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// `checkExistingFile`: the file is there with that hash.
fn matches(path: &Path, sha1: &str) -> bool {
path.exists() && sha1_of(path).is_ok_and(|actual| actual == sha1)
}
/// `updateModificationTime`: used now, so the cleaner keeps it longest.
fn touch(path: &Path) {
let _ = fs::File::options()
.append(true)
.open(path)
.and_then(|f| f.set_modified(SystemTime::now()));
}
/// `HttpUtil.downloadFile`: into `<dir>/<SHA-1>`. With a hash the cached file
/// is used when it matches, and a download that does not is an error;
/// without one the file is named after the hash of what came.
pub fn download_file(
dir: &Path,
request: &Request,
headers: &[(&'static str, String)],
max_size: u64,
) -> Result<PathBuf, String> {
let target = request.sha1.as_ref().map(|sha1| dir.join(sha1));
if let (Some(target), Some(sha1)) = (&target, &request.sha1) {
if matches(target, sha1) {
log::info!("Horizon: returning cached file since actual hash matches requested");
touch(target);
return Ok(target.clone());
}
if target.exists() {
log::warn!(
"Horizon: existing file {} not found or had mismatched hash",
target.display()
);
}
fs::remove_file(target)
.or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})
.map_err(|e| format!("Failed to remove existing file {}: {e}", target.display()))?;
}
let mut call = ureq::AgentBuilder::new().build().get(&request.url);
for (name, value) in headers {
call = call.set(name, value);
}
let response = call.call().map_err(|e| e.to_string())?;
let size = response
.header("Content-Length")
.and_then(|v| v.trim().parse::<u64>().ok());
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
if let Some(size) = size
&& size > max_size
{
return Err(format!(
"Filesize is bigger than maximum allowed (file is {size}, limit is {max_size})"
));
}
let mut input = response.into_reader();
match (&target, &request.sha1) {
(Some(target), Some(sha1)) => {
let actual = save_hashed(&mut input, target, max_size).map_err(|e| e.to_string())?;
if &actual != sha1 {
return Err(format!(
"Hash of downloaded file ({actual}) did not match requested ({sha1})"
));
}
Ok(target.clone())
}
_ => {
let tmp = dir.join(format!("download{:016x}.tmp", rand_suffix()));
let result = save_hashed(&mut input, &tmp, max_size).and_then(|actual| {
let path = dir.join(&actual);
if matches(&path, &actual) {
touch(&path);
} else {
fs::rename(&tmp, &path)?;
}
Ok(path)
});
let _ = fs::remove_file(&tmp);
result.map_err(|e| e.to_string())
}
}
}
fn rand_suffix() -> u64 {
use std::hash::{BuildHasher, RandomState};
RandomState::new().hash_one(std::time::Instant::now())
}
/// `downloadAndHash`: write what comes, at most `max_size` bytes.
fn save_hashed(input: &mut dyn Read, path: &Path, max_size: u64) -> io::Result<String> {
let mut out = fs::File::create(path)?;
let mut hasher = Sha1::new();
let mut buffer = [0u8; 8196];
let mut read_so_far = 0u64;
loop {
let n = input.read(&mut buffer)?;
if n == 0 {
break;
}
read_so_far += n as u64;
if read_so_far > max_size {
return Err(io::Error::other(format!(
"Filesize was bigger than maximum allowed (got >= {read_so_far}, limit was {max_size})"
)));
}
out.write_all(&buffer[..n])?;
hasher.update(&buffer[..n]);
}
Ok(hex(&hasher.finalize()))
}
/// `DownloadCacheCleaner.vacuumCacheDir`: keep the `max_files` files most
/// worth keeping (in the pack folders: the newest, and one per pack before a
/// second of any), then drop the folders left empty.
pub fn vacuum(dir: &Path, max_files: usize) {
let mut files = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(entries) = fs::read_dir(&d) else {
continue;
};
for e in entries.flatten() {
let path = e.path();
let Ok(meta) = e.metadata() else { continue };
if meta.is_dir() {
stack.push(path);
} else if meta.is_file() && path.parent() != Some(dir) {
let time = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
files.push((path, time));
}
}
}
let Some(remove) = files.len().checked_sub(max_files).filter(|n| *n > 0) else {
return;
};
// Newest first, then each file's rank in its folder (0 for a folder's
// newest), reversed, and stably sorted by rank, highest first.
files.sort_by_key(|f| std::cmp::Reverse(f.1));
let mut counts = std::collections::HashMap::<PathBuf, usize>::new();
let mut ranked: Vec<(PathBuf, usize)> = files
.into_iter()
.map(|(path, _)| {
let count = counts
.entry(path.parent().unwrap_or(dir).to_path_buf())
.or_default();
let rank = *count;
*count += 1;
(path, rank)
})
.collect();
ranked.reverse();
ranked.sort_by_key(|f| std::cmp::Reverse(f.1));
let mut emptied = std::collections::HashSet::new();
for (path, rank) in ranked.into_iter().take(remove) {
match fs::remove_file(&path) {
Ok(()) if rank == 0 => {
emptied.insert(path.parent().unwrap_or(dir).to_path_buf());
}
Ok(()) => {}
Err(e) => log::warn!(
"Horizon: failed to delete cache file {}: {e}",
path.display()
),
}
}
emptied.remove(dir);
for d in emptied {
let _ = fs::remove_dir(d);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
/// A one-shot HTTP server answering `status` with `body`; the request it got.
fn serve(status: &str, body: Vec<u8>) -> (String, std::thread::JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/pack.zip", listener.local_addr().unwrap());
let status = status.to_owned();
let handle = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut request = Vec::new();
let mut buf = [0u8; 1024];
while !request.ends_with(b"\r\n\r\n") {
let n = stream.read(&mut buf).unwrap();
request.extend_from_slice(&buf[..n]);
}
let head = format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
stream.write_all(head.as_bytes()).unwrap();
stream.write_all(&body).unwrap();
String::from_utf8_lossy(&request).into_owned()
});
(url, handle)
}
fn sha1(bytes: &[u8]) -> String {
hex(&Sha1::digest(bytes))
}
fn scratch() -> PathBuf {
let dir = std::env::temp_dir().join(format!("horizon-packs-{:016x}", rand_suffix()));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn a_pack_lands_under_its_hash_and_is_reused_from_the_cache() {
let dir = scratch();
let body = b"PK pack".to_vec();
let (url, server) = serve("200 OK", body.clone());
let request = Request {
id: 7,
url,
sha1: Some(sha1(&body)),
};
let path = download_file(&dir, &request, &headers("Alex", 0xab), MAX_SIZE).unwrap();
assert_eq!(path, dir.join(sha1(&body)));
assert_eq!(fs::read(&path).unwrap(), body);
let sent = server.join().unwrap();
assert!(sent.contains("X-Minecraft-Username: Alex"), "{sent}");
assert!(sent.contains("X-Minecraft-Pack-Format: 97.1"), "{sent}");
// Cached: no server this time.
let cached = Request {
url: "http://127.0.0.1:9/gone.zip".into(),
..request
};
assert_eq!(download_file(&dir, &cached, &[], MAX_SIZE).unwrap(), path);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_wrong_hash_a_dead_url_and_a_large_pack_fail() {
let dir = scratch();
let (url, server) = serve("200 OK", b"other bytes".to_vec());
let wrong = Request {
id: 1,
url,
sha1: Some("0".repeat(40)),
};
let err = download_file(&dir, &wrong, &[], MAX_SIZE).unwrap_err();
assert!(err.contains("did not match requested"), "{err}");
server.join().unwrap();
let dead = Request {
id: 2,
url: "http://127.0.0.1:9/pack.zip".into(),
sha1: None,
};
assert!(download_file(&dir.join("dead"), &dead, &[], MAX_SIZE).is_err());
assert!(!dir.join("dead").exists());
let (url, server) = serve("200 OK", vec![0; 100]);
let large = Request {
id: 3,
url,
sha1: None,
};
let err = download_file(&dir, &large, &[], 10).unwrap_err();
assert!(err.contains("bigger than maximum"), "{err}");
let _ = server.join();
let (url, server) = serve("404 Not Found", Vec::new());
let missing = Request {
id: 4,
url,
sha1: None,
};
assert!(download_file(&dir, &missing, &[], MAX_SIZE).is_err());
server.join().unwrap();
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_queue_logs_each_download() {
let dir = scratch();
let (url, server) = serve("200 OK", b"zip".to_vec());
let queue = Queue::open(dir.clone()).unwrap();
let id = 0x5b2c_7a4e_1f3d_4c8b_9a6e_2d4f_8b1c_3e5a;
queue.download(
vec![Request {
id,
url,
sha1: None,
}],
Vec::new(),
);
let batch = loop {
if let Some(b) = queue.finished().pop() {
break b;
}
std::thread::sleep(std::time::Duration::from_millis(10));
};
server.join().unwrap();
let file = dir
.join("5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a")
.join(sha1(b"zip"));
assert_eq!(batch.downloaded, [(id, file)]);
let log = fs::read_to_string(dir.join("log.json")).unwrap();
let entry: serde_json::Value = serde_json::from_str(log.trim()).unwrap();
assert_eq!(entry["id"], "5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a");
assert_eq!(entry["file"]["size"], 3);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_cleaner_keeps_the_newest_file_of_each_pack_longest() {
let dir = scratch();
let at = |secs| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs);
for (pack, file, time) in [
("a", "1", 10),
("a", "2", 20),
("a", "3", 30),
("b", "1", 5),
] {
fs::create_dir_all(dir.join(pack)).unwrap();
let path = dir.join(pack).join(file);
fs::write(&path, b"x").unwrap();
fs::File::options()
.append(true)
.open(&path)
.unwrap()
.set_modified(at(time))
.unwrap();
}
fs::write(dir.join("log.json"), b"").unwrap();
vacuum(&dir, 2);
assert!(dir.join("a/3").exists() && dir.join("b/1").exists());
assert!(!dir.join("a/1").exists() && !dir.join("a/2").exists());
assert!(dir.join("log.json").exists());
fs::remove_dir_all(dir).unwrap();
}
}
+12
View File
@@ -14,19 +14,24 @@ interface log {
warn,
error,
}
/// One line in the game's log as `[mod <id>] message`, at that level.
write: func(level: level, message: string);
}
/// Capability `game-read`: the local player and the world clock.
interface game {
record player {
/// Feet position, in blocks.
x: f64,
y: f64,
z: f64,
/// Degrees, as F3 shows them.
yaw: f32,
/// Degrees: -90 looks straight up, 90 straight down.
pitch: f32,
/// Hit points as vanilla counts them: 20 is full health without effects.
health: f32,
/// 0 to 20, as the hunger bar.
food: u32,
/// `minecraft:overworld`, `minecraft:the_nether`, ...
dimension: string,
@@ -39,6 +44,7 @@ interface game {
}
/// None on the title screen.
get-player: func() -> option<player>;
/// None on the title screen.
get-clock: func() -> option<clock>;
}
@@ -58,11 +64,14 @@ interface hud {
bottom-right,
}
record line {
/// Plain text, up to 256 characters.
text: string,
/// 0xRRGGBB.
color: u32,
}
/// Replaces the mod's panel: up to 16 lines in that corner of the screen.
set-panel: func(corner: corner, lines: list<line>);
/// Removes the mod's panel.
clear: func();
}
@@ -92,10 +101,13 @@ interface events {
}
/// Once, after loading. An error keeps the mod off and is shown.
init: func() -> result<registration, string>;
/// Each game tick while in a world, with the game's tick counter.
tick: func(tick: u64);
/// Each rendered frame, with the seconds since the last one.
frame: func(seconds: f32);
/// `/name args`: ok(some(text)) is shown as feedback, err(text) in red.
command: func(name: string, args: string) -> result<option<string>, string>;
/// Each chat line the player receives, as plain text.
chat: func(text: string);
}
+5
View File
@@ -30,5 +30,10 @@ pack = ["dep:wit-component", "dep:wit-parser"]
name = "sandbox"
required-features = ["runtime", "pack"]
# docs/api/mods-reference.md from the WIT contract (HORIZON_WRITE_DOCS=1 rewrites it).
[[test]]
name = "api_reference"
required-features = ["pack"]
[lints]
workspace = true
+304
View File
@@ -0,0 +1,304 @@
//! docs/api/mods-reference.md, generated from the WIT contract and the manifest's capabilities, and a test that
//! fails when it is out of date. Update it with:
//! `HORIZON_WRITE_DOCS=1 cargo test -p horizon-mods --features pack --test api_reference`.
use horizon_mods::manifest::{APIS, Capability};
use std::{fmt::Write, path::Path};
use wit_parser::{Docs, Function, Handle, Resolve, Type, TypeDefKind, WorldItem};
const WIT: &str = "crates/horizon-mod-sdk/wit/horizon.wit";
const DOC: &str = "docs/api/mods-reference.md";
fn root() -> &'static Path {
Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
}
/// A doc comment on one line, for a table cell.
fn cell(docs: &Docs) -> String {
let text = docs.contents.as_deref().unwrap_or("").trim();
text.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.replace('|', "\\|")
}
/// A type as WIT spells it.
fn ty(resolve: &Resolve, t: &Type) -> String {
let id = match t {
Type::Bool => return "bool".into(),
Type::U8 => return "u8".into(),
Type::U16 => return "u16".into(),
Type::U32 => return "u32".into(),
Type::U64 => return "u64".into(),
Type::S8 => return "s8".into(),
Type::S16 => return "s16".into(),
Type::S32 => return "s32".into(),
Type::S64 => return "s64".into(),
Type::F32 => return "f32".into(),
Type::F64 => return "f64".into(),
Type::Char => return "char".into(),
Type::String => return "string".into(),
Type::ErrorContext => return "error-context".into(),
Type::Id(id) => *id,
};
match &resolve.types[id].name {
Some(name) => name.clone(),
None => definition(resolve, &resolve.types[id].kind),
}
}
/// What an anonymous type, or the right-hand side of a `type` alias, spells.
fn definition(resolve: &Resolve, kind: &TypeDefKind) -> String {
let of = |t: &Option<Type>| t.as_ref().map_or("_".into(), |t| ty(resolve, t));
match kind {
TypeDefKind::Option(t) => format!("option<{}>", ty(resolve, t)),
TypeDefKind::List(t) => format!("list<{}>", ty(resolve, t)),
TypeDefKind::FixedSizeList(t, n) => format!("list<{}, {n}>", ty(resolve, t)),
TypeDefKind::Result(r) => match (&r.ok, &r.err) {
(None, None) => "result".into(),
(ok, None) => format!("result<{}>", of(ok)),
(ok, err) => format!("result<{}, {}>", of(ok), of(err)),
},
TypeDefKind::Tuple(t) => {
let items: Vec<_> = t.types.iter().map(|t| ty(resolve, t)).collect();
format!("tuple<{}>", items.join(", "))
}
TypeDefKind::Future(t) => t
.as_ref()
.map_or("future".into(), |t| format!("future<{}>", ty(resolve, t))),
TypeDefKind::Stream(t) => t
.as_ref()
.map_or("stream".into(), |t| format!("stream<{}>", ty(resolve, t))),
TypeDefKind::Handle(Handle::Own(t)) => ty(resolve, &Type::Id(*t)),
TypeDefKind::Handle(Handle::Borrow(t)) => format!("borrow<{}>", ty(resolve, &Type::Id(*t))),
TypeDefKind::Type(t) => ty(resolve, t),
other => panic!(
"{WIT}: an anonymous {} the reference can't spell",
other.as_str()
),
}
}
fn signature(resolve: &Resolve, f: &Function) -> String {
let params: Vec<_> = f
.params
.iter()
.map(|(name, t)| format!("{name}: {}", ty(resolve, t)))
.collect();
let result = f
.result
.as_ref()
.map_or(String::new(), |t| format!(" -> {}", ty(resolve, t)));
format!("func({}){result}", params.join(", "))
}
/// Who may use an interface: the capability that grants it, or what it is.
fn access(interface: &str, exported: bool) -> String {
if exported {
return "exported by the mod: the game calls it".into();
}
if interface == "log" {
return "always granted".into();
}
match Capability::ALL.iter().find(|c| c.interface() == interface) {
Some(c) => format!("capability `{c}`"),
None => "not granted by any capability".into(),
}
}
fn markdown() -> String {
let mut resolve = Resolve::new();
let package = resolve
.push_file(root().join(WIT))
.expect("the WIT contract parses");
let package = &resolve.packages[package];
let name = &package.name;
let mut out = String::new();
let w = &mut out;
writeln!(w, "<!-- Generated from {WIT} and the manifest's capabilities by crates/horizon-mods/tests/api_reference.rs; a test fails when this file is out of date. Update it with: HORIZON_WRITE_DOCS=1 cargo test -p horizon-mods --features pack --test api_reference -->").unwrap();
writeln!(w, "# Mod API reference\n").unwrap();
writeln!(
w,
"The contract between Horizon and its mods: the WIT package `{name}`, every interface, type, function and hook in it, \
and the capabilities a manifest may list. The guide is [mods.md](../mods.md); stability and versions: \
[stability.md](stability.md). Manifest `api` lines this game serves: {}.\n",
APIS.map(|a| format!("`{a}`")).join(", ")
)
.unwrap();
writeln!(w, "## Capabilities\n").unwrap();
writeln!(
w,
"| In `capabilities` | Grants | The player reads \"May …\" |\n| --- | --- | --- |"
)
.unwrap();
for c in Capability::ALL {
let grants = if package.interfaces.contains_key(c.interface()) {
format!("[`{0}`](#{0})", c.interface())
} else {
"data files (`assets/`, `data/`), no interface".into()
};
writeln!(w, "| `{c}` | {grants} | {} |", c.describe()).unwrap();
}
let mut exported = Vec::new();
for (world_name, &world) in &package.worlds {
let world = &resolve.worlds[world];
let prefix = format!("{}:{}/", name.namespace, name.name);
let names = |keys: Vec<&wit_parser::WorldKey>| {
keys.into_iter()
.map(|key| {
let full = resolve.name_world_key(key);
let short = full.trim_start_matches(&prefix);
format!("`{}`", short.split('@').next().unwrap_or(short))
})
.collect::<Vec<_>>()
.join(", ")
};
writeln!(w, "\n## World `{world_name}`\n").unwrap();
if world.docs.contents.is_some() {
writeln!(w, "{}\n", cell(&world.docs)).unwrap();
}
writeln!(
w,
"- Imports (what the game offers): {}",
names(world.imports.keys().collect())
)
.unwrap();
writeln!(
w,
"- Exports (what the mod provides): {}",
names(world.exports.keys().collect())
)
.unwrap();
for item in world.exports.values() {
if let WorldItem::Interface { id, .. } = item {
exported.push(*id);
}
}
}
for (interface_name, &id) in &package.interfaces {
let interface = &resolve.interfaces[id];
writeln!(w, "\n## `{interface_name}`\n").unwrap();
writeln!(
w,
"Access: {}.\n",
access(interface_name, exported.contains(&id))
)
.unwrap();
if interface.docs.contents.is_some() {
writeln!(w, "{}\n", cell(&interface.docs)).unwrap();
}
for (type_name, &type_id) in &interface.types {
let def = &resolve.types[type_id];
writeln!(w, "### {} `{type_name}`\n", def.kind.as_str()).unwrap();
if def.docs.contents.is_some() {
writeln!(w, "{}\n", cell(&def.docs)).unwrap();
}
match &def.kind {
TypeDefKind::Record(r) => {
writeln!(w, "| Field | Type | |\n| --- | --- | --- |").unwrap();
for f in &r.fields {
writeln!(
w,
"| `{}` | `{}` | {} |",
f.name,
ty(&resolve, &f.ty),
cell(&f.docs)
)
.unwrap();
}
}
TypeDefKind::Enum(e) => {
writeln!(w, "| Case | |\n| --- | --- |").unwrap();
for c in &e.cases {
writeln!(w, "| `{}` | {} |", c.name, cell(&c.docs)).unwrap();
}
}
TypeDefKind::Variant(v) => {
writeln!(w, "| Case | Payload | |\n| --- | --- | --- |").unwrap();
for c in &v.cases {
let payload =
c.ty.as_ref()
.map_or(String::new(), |t| format!("`{}`", ty(&resolve, t)));
writeln!(w, "| `{}` | {payload} | {} |", c.name, cell(&c.docs)).unwrap();
}
}
TypeDefKind::Flags(f) => {
writeln!(w, "| Flag | |\n| --- | --- |").unwrap();
for flag in &f.flags {
writeln!(w, "| `{}` | {} |", flag.name, cell(&flag.docs)).unwrap();
}
}
TypeDefKind::Resource => {
writeln!(w, "A resource: the game owns it, the mod holds a handle.").unwrap()
}
kind => writeln!(w, "`type {type_name} = {}`", definition(&resolve, kind)).unwrap(),
}
writeln!(w).unwrap();
}
if !interface.functions.is_empty() {
writeln!(
w,
"| Function | Signature | What it does |\n| --- | --- | --- |"
)
.unwrap();
for (fn_name, f) in &interface.functions {
writeln!(
w,
"| `{fn_name}` | `{}` | {} |",
signature(&resolve, f),
cell(&f.docs)
)
.unwrap();
}
}
}
out
}
#[test]
fn the_mod_api_reference_is_up_to_date() {
let path = root().join(DOC);
let want = markdown();
if std::env::var_os("HORIZON_WRITE_DOCS").is_some() {
std::fs::write(&path, &want).unwrap();
}
let have = std::fs::read_to_string(&path)
.unwrap_or_default()
.replace("\r\n", "\n");
assert!(
have == want,
"{DOC} is out of date: HORIZON_WRITE_DOCS=1 cargo test -p horizon-mods --features pack --test api_reference"
);
}
#[test]
fn every_function_is_documented() {
let mut resolve = Resolve::new();
resolve.push_file(root().join(WIT)).unwrap();
for (_, interface) in resolve.interfaces.iter() {
for (name, f) in &interface.functions {
assert!(
f.docs.contents.is_some(),
"{WIT}: `{name}` needs a doc comment: the reference shows it to mod authors"
);
}
}
}
#[test]
fn every_capability_with_an_interface_is_in_the_contract() {
let mut resolve = Resolve::new();
let package = resolve.push_file(root().join(WIT)).unwrap();
let interfaces = &resolve.packages[package].interfaces;
for c in Capability::ALL {
if c != Capability::Registries {
assert!(
interfaces.contains_key(c.interface()),
"capability {c} grants `{}`, missing from {WIT}",
c.interface()
);
}
}
}
+19 -4
View File
@@ -1,6 +1,7 @@
//! The JDK that compiles and runs the vanilla exporters. They call Mojang's own code, so they
//! stay Java; everything around them is here.
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
@@ -13,6 +14,20 @@ pub struct Jdk {
const TIMEOUT: Duration = Duration::from_secs(3600);
/// Exporters and JDK probes write to pipes or log files: on Windows they open no terminal.
fn command(program: impl AsRef<OsStr>) -> Command {
let command = Command::new(program);
#[cfg(windows)]
let command = {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let mut command = command;
command.creation_flags(CREATE_NO_WINDOW);
command
};
command
}
fn executable(dir: &Path, name: &str) -> PathBuf {
dir.join(if cfg!(windows) {
format!("{name}.exe")
@@ -29,7 +44,7 @@ fn on_path(name: &str) -> Option<PathBuf> {
/// The major version `javac -version` reports ("javac 25.0.1" → 25; "javac 1.8.0" → 8).
fn javac_major(javac: &Path) -> Result<u32, String> {
let output = Command::new(javac)
let output = command(javac)
.arg("-version")
.stdin(Stdio::null())
.output()
@@ -183,7 +198,7 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
candidates.push((javac, java, "PATH"));
}
if cfg!(target_os = "macos") {
if let Ok(out) = Command::new("/usr/libexec/java_home")
if let Ok(out) = command("/usr/libexec/java_home")
.args(["-v", &major.to_string()])
.stderr(Stdio::null())
.output()
@@ -260,7 +275,7 @@ impl Jdk {
/// `javac --release <major> -proc:none` with Python's `subprocess.run(..., check=True,
/// stdout=log, stderr=STDOUT, timeout=3600)`.
pub fn javac(&self, major: i64, args: &[String], log: &fs::File) -> Result<(), String> {
let mut command = Command::new(&self.javac);
let mut command = command(&self.javac);
command
.args(["--release", &major.to_string(), "-proc:none"])
.args(args);
@@ -268,7 +283,7 @@ impl Jdk {
}
pub fn java(&self, args: &[String], cwd: Option<&Path>, log: &fs::File) -> Result<(), String> {
let mut command = Command::new(&self.java);
let mut command = command(&self.java);
command.args(args);
if let Some(dir) = cwd {
command.current_dir(dir);
+4 -2
View File
@@ -676,13 +676,15 @@ fn steps(
}
// The playable client needs every client asset (textures, models, fonts, GUI)
// and every data-pack resource (worldgen, recipes, loot tables, tags).
// and every data-pack resource (worldgen, recipes, loot tables, tags), and
// the vanilla pack's icon (`pack.png`) for the pack screen.
(run.log)("Copying the client's assets and data");
let mut count = 0usize;
let mut client = open_zip(&run.client)?;
let version = pyjson::loads(&zip_text(&mut client, "version.json")?)?;
for name in zip_names(&client) {
if !(name.starts_with("assets/") || name.starts_with("data/")) || name.ends_with('/') {
let wanted = name.starts_with("assets/") || name.starts_with("data/") || name == "pack.png";
if !wanted || name.ends_with('/') {
continue;
}
let relative = member_path(&name, "Invalid resource path")?;
+3 -2
View File
@@ -13,8 +13,8 @@ use crate::{
packets::{
Empty,
configuration::{
ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPush,
ResourcePackResponse, UpdateTags,
ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop,
ResourcePackPush, ResourcePackResponse, UpdateTags,
},
login::Property,
},
@@ -1640,6 +1640,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
RemoveEntities(RemoveEntities) = REMOVE_ENTITIES,
RemoveMobEffect(RemoveMobEffect) = REMOVE_MOB_EFFECT,
ResetScore(ResetScore) = RESET_SCORE,
ResourcePackPop(ResourcePackPop) = RESOURCE_PACK_POP,
ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH,
Respawn(Respawn) = RESPAWN,
RotateHead(RotateHead) = ROTATE_HEAD,
+4 -2
View File
@@ -68,7 +68,8 @@ pub fn program_in(
/// system can't load the program, as on a Linux without the ALSA and udev libraries the full game links
/// (the server build doesn't). The reason, with what to install.
pub fn check_starts(program: &Path) -> Result<(), String> {
let output = Command::new(program)
let mut command = crate::process::command(program);
let output = command
.arg("--help")
.stdin(Stdio::null())
.stdout(Stdio::null())
@@ -176,7 +177,8 @@ pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result<Ch
#[cfg(windows)]
std::os::windows::process::CommandExt::creation_flags(
&mut command,
windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP,
windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP
| windows_sys::Win32::System::Threading::CREATE_NO_WINDOW,
);
command.spawn()
}
+1
View File
@@ -10,6 +10,7 @@ mod http;
mod init;
mod lists;
mod panel;
mod process;
#[cfg(test)]
mod reference;
mod service;
+20
View File
@@ -0,0 +1,20 @@
//! The programs the server runs. Started by the launcher, the server has no console, and each
//! console program it started would open a terminal window on Windows: those open none. Run from
//! a terminal, they share it, so what they print still reaches it.
use std::{ffi::OsStr, process::Command};
pub fn command(program: impl AsRef<OsStr>) -> Command {
let command = Command::new(program);
#[cfg(windows)]
let command = {
use std::os::windows::process::CommandExt;
use windows_sys::Win32::System::{Console::GetConsoleWindow, Threading::CREATE_NO_WINDOW};
let mut command = command;
// SAFETY: no arguments; it returns this process's console window or null.
if unsafe { GetConsoleWindow() }.is_null() {
command.creation_flags(CREATE_NO_WINDOW);
}
command
};
command
}
+2 -2
View File
@@ -178,7 +178,7 @@ fn systemd_path(service: &str, system: bool) -> Result<PathBuf, String> {
}
fn run(program: &str, args: &[&str]) -> Result<(), String> {
let status = Command::new(program)
let status = crate::process::command(program)
.args(args)
.status()
.map_err(|e| format!("{program}: {e}"))?;
@@ -191,7 +191,7 @@ fn run(program: &str, args: &[&str]) -> Result<(), String> {
/// A step that may fail harmlessly (stopping what isn't running): its output would only alarm.
fn quiet(program: &str, args: &[&str]) {
let _ = Command::new(program)
let _ = crate::process::command(program)
.args(args)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
+3 -4
View File
@@ -10,7 +10,6 @@ use serde_json::{Value, json};
use std::{
io::Read,
path::{Path, PathBuf},
process::Command,
time::{Duration, Instant},
};
@@ -206,7 +205,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> {
if link.exists() || link.symlink_metadata().is_ok() {
std::fs::remove_dir(link)?;
}
let status = Command::new("cmd")
let status = crate::process::command("cmd")
.arg("/C")
.arg("mklink")
.arg("/J")
@@ -474,7 +473,7 @@ pub fn unpack(install: &Install, archive: &Path, tag: &str) -> Result<PathBuf, S
// tar is on every Linux and macOS, and on Windows 10 and later. The files are the
// user's, not the archive's owners: as root in a user namespace (an unprivileged LXC
// or rootless container) taking those fails, and as plain root they'd be strangers'.
let status = Command::new("tar")
let status = crate::process::command("tar")
.arg("--no-same-owner")
.arg("-xzf")
.arg(archive)
@@ -1058,7 +1057,7 @@ mod tests {
std::fs::write(inner.join("horizon-server"), "v2").unwrap();
std::fs::write(inner.join("horizon-engine"), "engine").unwrap();
let archive = source.join("horizon-server-linux-x86_64.tar.gz");
let status = Command::new("tar")
let status = std::process::Command::new("tar")
.arg("-czf")
.arg(&archive)
.arg("-C")
+13 -5
View File
@@ -9,11 +9,19 @@ use std::sync::OnceLock;
use crate::payload::System;
fn command_output(program: &str, args: &[&str]) -> Option<String> {
let out = std::process::Command::new(program)
.args(args)
.output()
.ok()?;
/// What `program args` prints, trimmed, when it succeeds and prints something. On Windows the
/// program opens no console window: a GUI launcher or a game started without one would flash a
/// terminal for every probe.
pub fn command_output(program: &str, args: &[&str]) -> Option<String> {
let mut command = std::process::Command::new(program);
command.args(args);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
let out = command.output().ok()?;
let text = String::from_utf8_lossy(&out.stdout).trim().to_owned();
(out.status.success() && !text.is_empty()).then_some(text)
}
+141
View File
@@ -0,0 +1,141 @@
<!-- Generated from crates/horizon-mod-sdk/wit/horizon.wit and the manifest's capabilities by crates/horizon-mods/tests/api_reference.rs; a test fails when this file is out of date. Update it with: HORIZON_WRITE_DOCS=1 cargo test -p horizon-mods --features pack --test api_reference -->
# Mod API reference
The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, every interface, type, function and hook in it, and the capabilities a manifest may list. The guide is [mods.md](../mods.md); stability and versions: [stability.md](stability.md). Manifest `api` lines this game serves: `0.1`, `0.2`.
## Capabilities
| In `capabilities` | Grants | The player reads "May …" |
| --- | --- | --- |
| `game-read` | [`game`](#game) | see your position, health and the time |
| `chat` | [`chat`](#chat) | show you chat messages |
| `hud` | [`hud`](#hud) | draw text on your screen |
| `storage` | [`storage`](#storage) | save its own settings to disk |
| `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds |
## World `horizon-mod`
- Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage`
- Exports (what the mod provides): `events`
## `log`
Access: always granted.
The mod's log, in the game's log under the mod's id. Always granted.
### enum `level`
| Case | |
| --- | --- |
| `debug` | |
| `info` | |
| `warn` | |
| `error` | |
| Function | Signature | What it does |
| --- | --- | --- |
| `write` | `func(level: level, message: string)` | One line in the game's log as `[mod <id>] message`, at that level. |
## `game`
Access: capability `game-read`.
Capability `game-read`: the local player and the world clock.
### record `player`
| Field | Type | |
| --- | --- | --- |
| `x` | `f64` | Feet position, in blocks. |
| `y` | `f64` | |
| `z` | `f64` | |
| `yaw` | `f32` | Degrees, as F3 shows them. |
| `pitch` | `f32` | Degrees: -90 looks straight up, 90 straight down. |
| `health` | `f32` | Hit points as vanilla counts them: 20 is full health without effects. |
| `food` | `u32` | 0 to 20, as the hunger bar. |
| `dimension` | `string` | `minecraft:overworld`, `minecraft:the_nether`, ... |
### record `clock`
| Field | Type | |
| --- | --- | --- |
| `game-time` | `u64` | Ticks since the world was created. |
| `day-time` | `u64` | 24000 ticks per day; 0 is 6:00 on the first day. |
| Function | Signature | What it does |
| --- | --- | --- |
| `get-player` | `func() -> option<player>` | None on the title screen. |
| `get-clock` | `func() -> option<clock>` | None on the title screen. |
## `chat`
Access: capability `chat`.
Capability `chat`: messages only the local player sees.
| Function | Signature | What it does |
| --- | --- | --- |
| `show` | `func(text: string)` | Shown in chat after the mod's name, like a system message. |
## `hud`
Access: capability `hud`.
Capability `hud`: one panel of text lines per mod, drawn by the game every frame until the mod changes or clears it (no call per frame).
### enum `corner`
| Case | |
| --- | --- |
| `top-left` | |
| `top-right` | |
| `bottom-left` | |
| `bottom-right` | |
### record `line`
| Field | Type | |
| --- | --- | --- |
| `text` | `string` | Plain text, up to 256 characters. |
| `color` | `u32` | 0xRRGGBB. |
| Function | Signature | What it does |
| --- | --- | --- |
| `set-panel` | `func(corner: corner, lines: list<line>)` | Replaces the mod's panel: up to 16 lines in that corner of the screen. |
| `clear` | `func()` | Removes the mod's panel. |
## `storage`
Access: capability `storage`.
Capability `storage`: a per-mod folder of small key/value files, quota'd (docs/mods.md). Keys are `[a-z0-9_.-]{1,64}`, one path segment.
| Function | Signature | What it does |
| --- | --- | --- |
| `get` | `func(key: string) -> option<list<u8>>` | None if `key` has never been `set`, or the key is not well-formed. |
| `set` | `func(key: string, value: list<u8>) -> result<_, string>` | Errs on a malformed key or over quota (bytes for the whole mod). |
| `delete` | `func(key: string)` | No error if `key` was already absent. |
## `events`
Access: exported by the mod: the game calls it.
What the game calls. Only the hooks `init` asks for are ever called.
### record `registration`
| Field | Type | |
| --- | --- | --- |
| `commands` | `list<string>` | Chat commands, without the slash. A name vanilla already uses is refused (vanilla's command runs). |
| `tick` | `bool` | Call `tick` every game tick (20 per second while playing). |
| `frame` | `bool` | Call `frame` every rendered frame. Budget: 0.1 ms. |
| `chat` | `bool` | Call `chat` for each chat line the player receives. |
| Function | Signature | What it does |
| --- | --- | --- |
| `init` | `func() -> result<registration, string>` | Once, after loading. An error keeps the mod off and is shown. |
| `tick` | `func(tick: u64)` | Each game tick while in a world, with the game's tick counter. |
| `frame` | `func(seconds: f32)` | Each rendered frame, with the seconds since the last one. |
| `command` | `func(name: string, args: string) -> result<option<string>, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. |
| `chat` | `func(text: string)` | Each chat line the player receives, as plain text. |
+3 -1
View File
@@ -33,6 +33,7 @@ harness named checks that loader against vanilla).
| Overlays per format | `pack.mcmeta` `overlays` | works | `test_resource_pack_parity` (an overlay for 26.3 applied, an older one not) |
| Filters | `pack.mcmeta` `filter` | works | `test_resource_pack_parity` (`packs/pattern.rs` regex subset) |
| Folder and zip packs, order, built-in packs | `resourcepacks/` | works | `test_resource_pack_parity`, `test_pack_selection_parity` |
| Server resource packs: the prompt, the server list's Server Resource Packs setting, download (250 MiB, SHA-1, `downloads/` keeps 20), applied on top of the player's packs, removed on leaving | the server's `resource_pack_push`/`_pop` | works, no download toasts | `tools/server_pack_e2e.py` (against vanilla's server and Horizon's), unit tests in `server_packs.rs`; `test_server_resource_pack_parity` for Horizon's server |
| Other namespaces | `assets/<namespace>/` | works | `test_resource_pack_parity` |
| Block states: variants, multipart, weights, rotations, uvlock | `blockstates/` | works | `test_blockstate_model_parity`, `test_model_choice_parity`, `test_blockstate_transform_parity` |
| Block models: parents, elements, rotations, faces, cullface, tint, shade, light emission, ambient occlusion | `models/block/` | works | `test_model_resolution_parity`, `test_model_baking_parity`, `test_section_mesh_parity` |
@@ -74,7 +75,7 @@ harness named checks that loader against vanilla).
| Core shaders | `shaders/core/`, `shaders/include/` | **no** | Horizon draws with WGSL; a pack's GLSL core shaders aren't run |
| GPU warn list, regional compliance | `gpu_warnlist.json`, `regional_compliancies.json` | n/a | OpenGL driver warnings and play-time notices for some regions; not used |
Summary: 44 rows; 31 work, 3 partly, 8 don't (interpolated animation, TrueType fonts, credits and end poem,
Summary: 45 rows; 32 work, 3 partly, 8 don't (interpolated animation, TrueType fonts, credits and end poem,
villager hats, trims on worn armour, locator bar styles, post effects, core shaders), 2 don't apply. Except the
shaders, the missing pieces are missing vanilla features too, and each vanilla parity fix covers the pack case as well.
@@ -83,6 +84,7 @@ shaders, the missing pieces are missing vanilla features too, and each vanilla p
| Gap | Size | Where |
| --- | --- | --- |
| Animation `interpolate` | small | fix PR (`gfx.rs` `animate_sprites`) |
| Server pack download toasts (`download.pack.*`) | small | `game/server_packs.rs` |
| GUI scaling `width`/`height`, `stretch_inner`, `tile`, `stretch` | small | next fix PR (`ui.rs`) |
| Villager hats | small | [#334](https://github.com/ludovic111/horizon/issues/334) |
| `blur`/`clamp` from packs | small | [#335](https://github.com/ludovic111/horizon/issues/335) |
+18 -3
View File
@@ -97,6 +97,10 @@ page `servers.json` (the list), `servers/<name>/` (the servers created there) an
Long pages, dialogs, the server console and data previews have a visible scrollbar when
their content overflows. Drag the thumb or click the track to navigate without a mouse wheel.
Pages and Home's landscape fill the window as it resizes. Windows uses a matching title
bar with native dragging, resizing, Snap,
minimize, maximize/restore and close; macOS and Linux keep their system title bars.
## Updates
The launcher looks for a newer Horizon release when it starts and every 30 minutes while it
@@ -127,7 +131,12 @@ and `horizon-launcher-windows-x64.zip`, never marked latest. The version is buil
## Command line
The same binary is a command-line tool; without a subcommand it opens the window.
The same binary is a command-line tool; without a subcommand it opens the window. On Windows it
is a windowed program, so a desktop start opens no terminal; a subcommand writes to the terminal
it was typed in, or to the pipes and files it was given (MCP keeps its stdio). Interactive `cmd`
and PowerShell don't wait for a windowed program: they show the prompt again before its output
and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code use
`start /wait horizon-launcher …` or `Start-Process -Wait`, or read its output through a pipe.
horizon-launcher versions [--installed] releases on GitHub, or what is installed (* = selected)
horizon-launcher install <tag|latest>
@@ -250,14 +259,20 @@ Each session writes its own measurements to `benchmarks/launcher-<time>-session.
launcher's data folder, in the [benchmark report format](../docs/benchmark-report.md): start to the
first frame, the release list fetch, installs and updates (download and unpack), preparing, Play to
the game's first frame, memory, UI frame times and the binary's size, with the machine's CPU, RAM
and OS. Attach it to an issue about the launcher being slow. `horizon-launcher benchmark` measures
on purpose: it starts the launcher `--repeats` times (5; the first start is the cold one, as far
and OS (read on a thread after the first frame: on Windows those queries take seconds). Attach it
to an issue about the launcher being slow. `horizon-launcher benchmark` measures on purpose: it starts the launcher `--repeats` times (5; the first start is the cold one, as far
as the OS's file cache allows), switches pages for a few seconds in each, rests 3 seconds to
measure idle CPU, fetches the release list 3 times, and writes one report there with means and
95% confidence intervals. Its window has to be on a screen that is awake. Session logs stay on
your machine; a `benchmark` report is uploaded, dated to the day, only if you allowed benchmark
uploads ([data collection](../docs/telemetry.md)).
Long lists on Mods (results, installed entries, coverage reports and project versions), Versions
and Patch notes build only nearby rows, including on their first frame. Variable row heights
are measured as they enter view; hidden ranges share spacers in the existing page scrollbar.
On Windows, `cargo test --bin horizon-launcher desktop_list_renders_the_viewport_after_scrollbar_jumps
-- --ignored` checks 10,000 rows of different heights in a real GPUI window (requires an awake desktop/GPU).
## Building
cargo build --release
+2 -2
View File
@@ -122,8 +122,8 @@ pub fn locate(program: &str) -> std::path::PathBuf {
/// Settings page's "Test the connection".
pub fn self_test(exe: &Path) -> Result<usize, String> {
use std::io::Write;
use std::process::{Command, Stdio};
let mut child = Command::new(exe)
use std::process::Stdio;
let mut child = crate::process::command(exe)
.arg("mcp")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
+1 -1
View File
@@ -207,7 +207,7 @@ impl Launcher {
/// Runs a client's add command; (went well, what it said).
fn run_add(program: &str, args: &[String]) -> (bool, String) {
match std::process::Command::new(agents::locate(program))
match horizon_launcher::process::command(agents::locate(program))
.args(args)
.output()
{
+104 -50
View File
@@ -2,39 +2,36 @@
//! and the landscape behind Home (the vanilla grass block is `browser::images::grass_block`).
//! GPUI samples images smoothly, so every image is baked at the window's scale with each texel a
//! whole block of device pixels, and drawn at exactly its size: the edges stay sharp. Each image
//! is made once per appearance and scale, then reused.
use gpui::RenderImage;
//! is made once per appearance and scale, then reused; Home's landscape is made again only when
//! the window grows wider than it.
use gpui::{RenderImage, Window};
use horizon_theme as tokens;
use std::collections::HashMap;
use std::sync::Arc;
/// What an image is, to find it again.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Key {
Stone { dark: bool, scale: u32 },
Scene { dark: bool, scale: u32 },
}
#[derive(Default)]
pub struct Art {
made: HashMap<Key, Arc<RenderImage>>,
/// The stone texture for each appearance and scale.
stones: HashMap<(bool, u32), Arc<RenderImage>>,
/// Home's landscape: its appearance and scale, and its width in texels.
scene: Option<((bool, u32), usize, Arc<RenderImage>)>,
/// Landscapes replaced since the last frame, still in the window's sprite atlas.
replaced: Vec<Arc<RenderImage>>,
}
/// The stone texture comes in squares of this many logical pixels (4 by 4 tiles).
pub const STONE: f32 = tokens::TILE_TEXEL * (tokens::TILE_TEXELS * 4) as f32;
/// Home's landscape: texels of this many logical pixels, and its size in texels.
/// Home's landscape: texels of this many logical pixels, and its height in texels. Its width
/// grows in steps of `SCENE_STEP` texels, so resizing a window rarely makes another.
pub const SCENE_TEXEL: f32 = 6.;
pub const SCENE_SIZE: (usize, usize) = (220, 56);
pub const SCENE_HEIGHT: usize = 56;
const SCENE_STEP: usize = 64;
impl Art {
/// The page's stone texture, for a window at `scale`.
pub fn stone(&mut self, page: u32, dark: bool, scale: f32) -> Arc<RenderImage> {
let key = Key::Stone {
dark,
scale: scale_key(scale),
};
self.made
.entry(key)
self.stones
.entry((dark, scale_key(scale)))
.or_insert_with(|| {
let n = tokens::TILE_TEXELS * 4;
bake(&opaque(&stone(page, n)), n, n, tokens::TILE_TEXEL, scale)
@@ -42,20 +39,30 @@ impl Art {
.clone()
}
/// Home's landscape: a sunset in the dark appearance, a dawn in the light one.
pub fn scene(&mut self, dark: bool, scale: f32) -> Arc<RenderImage> {
let key = Key::Scene {
dark,
scale: scale_key(scale),
};
self.made
.entry(key)
.or_insert_with(|| {
let (w, h) = SCENE_SIZE;
let palette = if dark { &SUNSET } else { &DAWN };
bake(&opaque(&scene(palette, 3, w, h)), w, h, SCENE_TEXEL, scale)
})
.clone()
/// Home's landscape, at least `width` logical pixels wide (the banner clips the rest), and
/// its width: a sunset in the dark appearance, a dawn in the light one.
pub fn scene(&mut self, dark: bool, scale: f32, width: f32) -> (Arc<RenderImage>, f32) {
let key = (dark, scale_key(scale));
let texels = (width / SCENE_TEXEL).ceil().max(1.) as usize;
if !matches!(&self.scene, Some((k, w, _)) if *k == key && *w >= texels) {
let w = texels.next_multiple_of(SCENE_STEP);
let palette = if dark { &SUNSET } else { &DAWN };
let texels = opaque(&scene(palette, 3, w, SCENE_HEIGHT));
let image = bake(&texels, w, SCENE_HEIGHT, SCENE_TEXEL, scale);
if let Some((_, _, old)) = self.scene.replace((key, w, image)) {
self.replaced.push(old);
}
}
let (_, w, image) = self.scene.as_ref().expect("made above");
(image.clone(), *w as f32 * SCENE_TEXEL)
}
/// Frees the landscapes replaced since the last frame: GPUI keeps an image in the window's
/// sprite atlas until it is dropped there.
pub fn free_replaced(&mut self, window: &mut Window) {
for image in self.replaced.drain(..) {
let _ = window.drop_image(image);
}
}
}
@@ -199,8 +206,14 @@ pub const DAWN: Palette = Palette {
/// A blocky landscape, `w` by `h` texels: banded sky, a sun half set behind the far hills and cut
/// into slices like Horizon's mark, flat clouds, three ridges of hills and a few square trees.
/// Each part draws from its own generator from left to right, so a wider landscape only adds
/// columns: the first `w` are the same at every width, and a resized window keeps its view.
pub fn scene(p: &Palette, seed: u32, w: usize, h: usize) -> Vec<u32> {
let mut rng = Rng(seed.wrapping_mul(0x2545_f491) | 1);
let mut seeds = Rng(seed.wrapping_mul(0x2545_f491) | 1);
let mut rng = || {
seeds.next();
Rng(seeds.0)
};
let mut out = vec![0; w * h];
let horizon = h * 62 / 100;
let band = horizon as f32 / p.sky.len() as f32;
@@ -223,20 +236,23 @@ pub fn scene(p: &Palette, seed: u32, w: usize, h: usize) -> Vec<u32> {
}
}
};
for _ in 0..4 {
let cx = (rng.next() * w as f32) as isize;
let cy = (horizon as f32 * (0.12 + rng.next() * 0.4)) as isize;
let cw = 10 + (rng.next() * 14.) as usize;
let under = p.sky[((cy as f32 / band) as usize + 1).min(p.sky.len() - 1)];
let c = mix(under, 0xffffff, 0.12);
rect(&mut out, cx, cy, cw, 2, c);
rect(&mut out, cx + 3, cy - 2, cw.saturating_sub(6), 2, c);
// Four clouds in every stretch of `CLOUDS` texels.
const CLOUDS: usize = 220;
let mut clouds = rng();
for stretch in 0..w.div_ceil(CLOUDS) {
for _ in 0..4 {
let cx = (stretch * CLOUDS) as isize + (clouds.next() * CLOUDS as f32) as isize;
let cy = (horizon as f32 * (0.12 + clouds.next() * 0.4)) as isize;
let cw = 10 + (clouds.next() * 14.) as usize;
let under = p.sky[((cy as f32 / band) as usize + 1).min(p.sky.len() - 1)];
let c = mix(under, 0xffffff, 0.12);
rect(&mut out, cx, cy, cw, 2, c);
rect(&mut out, cx + 3, cy - 2, cw.saturating_sub(6), 2, c);
}
}
// The sun, where it was when the landscape had one width (two thirds of 220 texels).
let r = (h as f32 * 0.2) as isize;
let (cx, cy) = (
(w as f32 * 0.68) as isize,
horizon as isize - (h as f32 * 0.11) as isize,
);
let (cx, cy) = (149, horizon as isize - (h as f32 * 0.11) as isize);
for dy in -r..=0 {
let half = ((r * r - dy * dy) as f32).sqrt().round() as isize;
let t = (dy + r) as f32 / r as f32;
@@ -251,7 +267,7 @@ pub fn scene(p: &Palette, seed: u32, w: usize, h: usize) -> Vec<u32> {
rect(&mut out, cx - half, cy + dy, (half * 2) as usize, 1, c);
}
}
let ridge = |rng: &mut Rng, base: f32, amp: f32, rough: f32| -> Vec<usize> {
let ridge = |mut rng: Rng, base: f32, amp: f32, rough: f32| -> Vec<usize> {
let (mut y, mut v) = (base, 0.);
(0..w)
.map(|x| {
@@ -277,7 +293,7 @@ pub fn scene(p: &Palette, seed: u32, w: usize, h: usize) -> Vec<u32> {
];
let mut near = Vec::new();
for (c, base, amp, rough, top) in layers {
let hs = ridge(&mut rng, base, amp, rough);
let hs = ridge(rng(), base, amp, rough);
for (x, &y) in hs.iter().enumerate() {
for yy in y.min(h)..h {
out[yy * w + x] = c;
@@ -288,9 +304,12 @@ pub fn scene(p: &Palette, seed: u32, w: usize, h: usize) -> Vec<u32> {
}
near = hs;
}
for _ in 0..w / 26 {
let tx = 4 + (rng.next() * (w - 10) as f32) as isize;
let ty = near[tx as usize] as isize;
// A tree somewhere in every 26 texels of the near hills.
let mut trees = rng();
for cell in 0..w.div_ceil(26) {
let tx = cell * 26 + 2 + (trees.next() * 22.) as usize;
let Some(&ty) = near.get(tx) else { break };
let (tx, ty) = (tx as isize, ty as isize);
rect(&mut out, tx - 2, ty - 8, 5, 5, p.trees);
rect(&mut out, tx - 1, ty - 10, 3, 2, p.trees);
rect(&mut out, tx, ty - 3, 1, 3, p.trees);
@@ -320,4 +339,39 @@ mod tests {
let size = image.size(0);
assert_eq!((size.width.0, size.height.0), (16, 16));
}
#[test]
fn the_landscape_covers_the_banner_and_is_made_again_only_when_it_grows() {
let mut art = Art::default();
let stone = art.stone(0x0f0d17, true, 2.);
let (first, drawn) = art.scene(true, 2., 700.);
assert!(drawn >= 700.);
assert_eq!(first.size(0).width.0, (drawn * 2.) as i32);
assert_eq!(
first.size(0).height.0,
(SCENE_HEIGHT as f32 * SCENE_TEXEL * 2.) as i32
);
// A step wide: a few pixels more or a narrower window keep it.
for width in [drawn, 400.] {
assert!(Arc::ptr_eq(&first, &art.scene(true, 2., width).0));
}
let (wider, wider_drawn) = art.scene(true, 2., 1900.);
assert!(!Arc::ptr_eq(&first, &wider) && wider_drawn >= 1900.);
assert!(Arc::ptr_eq(&art.replaced[0], &first));
assert!(Arc::ptr_eq(&stone, &art.stone(0x0f0d17, true, 2.)));
}
#[test]
fn a_wider_landscape_only_adds_columns() {
let (h, narrow, wide) = (SCENE_HEIGHT, 150, 400);
let a = scene(&SUNSET, 3, narrow, h);
let b = scene(&SUNSET, 3, wide, h);
for y in 0..h {
assert_eq!(
a[y * narrow..(y + 1) * narrow],
b[y * wide..y * wide + narrow],
"row {y}"
);
}
}
}
+5 -10
View File
@@ -943,7 +943,7 @@ pub fn default_minecraft_dir() -> Option<PathBuf> {
}
fn found(program: &str, arg: &str) -> bool {
Command::new(program)
crate::process::command(program)
.arg(arg)
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -1239,14 +1239,14 @@ pub fn sounds(tag: &str, minecraft: &Path, log: &dyn Fn(String)) {
let own = horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref()
== Some(horizon_prepare::SOURCES_SHA256);
let binary = preparer_binary(&dir).filter(|binary| {
!own && Command::new(binary)
!own && crate::process::command(binary)
.arg("--help")
.output()
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("horizon-prepare sounds"))
});
log("Copying the sounds from your Minecraft install".into());
let result = match binary {
Some(binary) => Command::new(binary)
Some(binary) => crate::process::command(binary)
.current_dir(&dir)
.arg("sounds")
.arg("--root")
@@ -1877,16 +1877,10 @@ fn parse_version_output(out: &str) -> Option<&str> {
/// The version of the launcher binary now at `path`, which is not this process's once another
/// update (the command line, another window) has replaced the file.
fn installed_launcher_version(path: &Path) -> Option<String> {
let mut cmd = Command::new(path);
let mut cmd = crate::process::command(path);
cmd.arg("--version")
.stdin(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
let out = cmd.output().ok()?;
parse_version_output(&String::from_utf8_lossy(&out.stdout)).map(String::from)
}
@@ -2220,6 +2214,7 @@ impl Running {
}
pub fn spawn(job: Job, mut cmd: Command, tx: Sender<Msg>) -> Result<Running, String> {
crate::process::hide_console(&mut cmd);
let mut child = cmd
.stdin(Stdio::piped())
.stdout(Stdio::piped())
+1 -1
View File
@@ -210,7 +210,7 @@ impl Tool {
pub fn call(&self, args: &Value) -> Result<String, String> {
let words = self.argv(args)?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe)
let out = horizon_launcher::process::command(exe)
.arg("--json")
.args(&words)
.stdin(std::process::Stdio::null())
+48
View File
@@ -0,0 +1,48 @@
//! A desktop launch has no console; CLI commands can use the invoking terminal or pipes.
#[cfg(windows)]
pub fn attach_for_cli() -> std::io::Result<()> {
use std::ffi::c_void;
const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
const STD_INPUT_HANDLE: u32 = -10_i32 as u32;
const STD_OUTPUT_HANDLE: u32 = -11_i32 as u32;
const STD_ERROR_HANDLE: u32 = -12_i32 as u32;
const INVALID_HANDLE_VALUE: isize = -1;
#[link(name = "kernel32")]
extern "system" {
fn AttachConsole(process_id: u32) -> i32;
fn GetStdHandle(kind: u32) -> *mut c_void;
fn SetStdHandle(kind: u32, handle: *mut c_void) -> i32;
}
if std::env::args_os().nth(1).is_none() {
return Ok(());
}
// Attaching can replace the standard handles. Keep inherited pipes/files intact for
// JSON output, MCP and redirected logs, while filling missing handles from the terminal.
// SAFETY: These APIs take numeric constants and opaque handles returned by Windows.
// No handles are closed or dereferenced, and this runs before any worker starts.
unsafe {
let handles = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE]
.map(|kind| (kind, GetStdHandle(kind)));
if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
// No parent console (for example, an MCP client), or already attached.
return Ok(());
}
for (kind, handle) in handles {
if handle.is_null() || handle as isize == INVALID_HANDLE_VALUE {
continue;
}
if SetStdHandle(kind, handle) == 0 {
return Err(std::io::Error::last_os_error());
}
}
}
Ok(())
}
#[cfg(not(windows))]
pub fn attach_for_cli() -> std::io::Result<()> {
Ok(())
}
+310 -72
View File
@@ -1,25 +1,40 @@
//! Long lists in the page's scroll area (the hundred releases on Versions and Patch notes) draw
//! only the rows near what is on screen. A row far off screen becomes an empty block as tall as
//! it was the last time it was drawn, so the page keeps its length and the scrollbar its place.
use gpui::{div, px, Bounds, Div, IntoElement, ParentElement, Pixels, ScrollHandle, Styled};
//! Variable-height lists in the page's scroll area. Only nearby rows build elements;
//! unseen rows use estimated heights and consecutive hidden rows share one spacer.
use gpui::{
div, point, px, size, Bounds, Div, IntoElement, ParentElement, Pixels, ScrollHandle, Styled,
};
use std::{cell::RefCell, rc::Rc};
const ESTIMATED_HEIGHT: f32 = 96.;
/// Until the enclosing scroll area completes its first layout.
const INITIAL_VIEW_HEIGHT: f32 = 800.;
#[derive(Clone, Default)]
pub struct Cull(Rc<RefCell<Drawn>>);
/// Where each row was in the last frame, and the scroll offset and the viewport's width then
/// (a narrower window wraps text, and the heights no longer hold).
#[derive(Default)]
struct Drawn {
rows: Vec<Bounds<Pixels>>,
heights: Vec<Pixels>,
top: Pixels,
offset: Pixels,
width: Pixels,
}
#[derive(Debug)]
enum Span {
Row(usize),
/// Hidden rows, this tall together.
Space(Pixels),
}
impl Cull {
/// A column for `rows` rows that remembers where they were drawn. Rows come from `row(i)`, or
/// an empty block when row `i` was more than a screen away from the viewport last frame and
/// `keep(i)` is false (a row being installed or showing an error is always drawn).
/// Invalidate measurements when filtering, ordering or collection identity changes.
pub fn reset(&self) {
*self.0.borrow_mut() = Drawn::default();
}
/// Render nearby rows plus those retained by `keep` (such as active confirmations).
/// `gap` is the bottom margin already supplied by each row.
pub fn column<E: IntoElement>(
&self,
handle: &ScrollHandle,
@@ -28,92 +43,315 @@ impl Cull {
keep: impl Fn(usize) -> bool,
mut row: impl FnMut(usize) -> E,
) -> Div {
let far = self.far(handle, rows);
let skipped: Vec<Option<Pixels>> = (0..rows).map(|i| far(i).filter(|_| !keep(i))).collect();
let gaps = skipped.iter().any(Option::is_some);
let max = handle.max_offset().height;
if max > px(0.)
&& handle.offset().y <= -max + px(0.5)
&& self.0.borrow().heights.len() == rows
{
// Measuring taller rows at the end must keep the final row in view. Appending
// results deliberately leaves the current viewport in place instead.
handle.scroll_to_bottom();
}
let spans = self
.0
.borrow_mut()
.plan(handle.bounds(), handle.offset().y, rows, gap, keep);
let children = spans
.iter()
.map(|span| match span {
// The wrapper includes the row's margin in its measured height.
Span::Row(index) => div().flex().flex_col().flex_none().child(row(*index)),
Span::Space(height) => div().flex_none().h(*height),
})
.collect::<Vec<_>>();
let state = self.0.clone();
let scroll = handle.clone();
div()
.flex()
.flex_col()
.children(skipped.iter().enumerate().map(|(i, skip)| match skip {
Some(height) => div().flex_none().h(*height).mb(px(gap)).into_any_element(),
None => row(i).into_any_element(),
}))
.children(children)
.on_children_prepainted(move |bounds, window, _| {
let view = scroll.bounds();
// A jump of more than a screen (the scrollbar dragged) can bring an empty block
// into view: draw again, with the rows where they are now.
if gaps
&& bounds
.iter()
.zip(&skipped)
.any(|(b, skip)| skip.is_some() && !away(*b, px(0.), view))
if state
.borrow_mut()
.record(&spans, &bounds, scroll.bounds(), scroll.offset().y)
{
window.refresh();
}
let mut drawn = state.borrow_mut();
drawn.rows = bounds;
drawn.offset = scroll.offset().y;
drawn.width = view.size.width;
})
}
/// For row `i`: its height when it was more than a screen away from the viewport.
fn far(&self, handle: &ScrollHandle, rows: usize) -> impl Fn(usize) -> Option<Pixels> {
let drawn = self.0.borrow();
let view = handle.bounds();
// The rows moved by however far the page scrolled since they were drawn.
let moved = handle.offset().y - drawn.offset;
let known =
drawn.rows.len() == rows && view.size.height > px(0.) && drawn.width == view.size.width;
let rows = if known {
drawn.rows.clone()
} else {
Vec::new()
};
move |i| {
let b = *rows.get(i)?;
away(b, moved, view).then_some(b.size.height)
}
}
}
/// Whether a row drawn at `row`, since moved down by `moved`, is more than a screen above or
/// below `view`.
fn away(row: Bounds<Pixels>, moved: Pixels, view: Bounds<Pixels>) -> bool {
row.bottom() + moved < view.top() - view.size.height
|| row.top() + moved > view.bottom() + view.size.height
impl Drawn {
fn plan(
&mut self,
mut view: Bounds<Pixels>,
offset: Pixels,
rows: usize,
gap: f32,
keep: impl Fn(usize) -> bool,
) -> Vec<Span> {
let estimate = px(ESTIMATED_HEIGHT + gap);
if self.width != view.size.width {
// A resize changes wrapping, including in rows currently off screen.
self.heights.fill(estimate);
}
self.heights.resize(rows, estimate);
if view.size.height <= px(0.) {
view.size.height = px(INITIAL_VIEW_HEIGHT);
}
let mut top = self.top + offset - self.offset;
let mut spans = Vec::new();
for (index, height) in self.heights.iter().copied().enumerate() {
let bounds = Bounds::new(point(view.left(), top), size(view.size.width, height));
if !away(bounds, view) || keep(index) {
spans.push(Span::Row(index));
} else if let Some(Span::Space(total)) = spans.last_mut() {
*total += height;
} else {
spans.push(Span::Space(height));
}
top += height;
}
spans
}
/// A moved header or scrollbar jump can expose a spacer: request another frame when
/// measurements or the estimated visible range need correcting.
fn record(
&mut self,
spans: &[Span],
bounds: &[Bounds<Pixels>],
view: Bounds<Pixels>,
offset: Pixels,
) -> bool {
let mut changed = false;
for (span, bounds) in spans.iter().zip(bounds) {
match span {
Span::Row(index) => {
let height = &mut self.heights[*index];
changed |= (*height - bounds.size.height).abs() > px(0.5);
*height = bounds.size.height;
}
Span::Space(_) => changed |= !away(*bounds, view),
}
}
self.top = bounds.first().map_or(view.top(), Bounds::top);
self.offset = offset;
self.width = view.size.width;
changed
}
}
/// One viewport of overdraw above and below the visible area.
fn away(row: Bounds<Pixels>, view: Bounds<Pixels>) -> bool {
row.bottom() < view.top() - view.size.height || row.top() > view.bottom() + view.size.height
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::{point, size};
fn at(y: f32, h: f32) -> Bounds<Pixels> {
Bounds::new(point(px(0.), px(y)), size(px(10.), px(h)))
fn at(top: f32, height: f32, width: f32) -> Bounds<Pixels> {
Bounds::new(point(px(0.), px(top)), size(px(width), px(height)))
}
fn rendered(spans: &[Span]) -> Vec<usize> {
spans
.iter()
.filter_map(|span| match span {
Span::Row(index) => Some(*index),
Span::Space(_) => None,
})
.collect()
}
#[test]
fn only_rows_more_than_a_screen_away_are_skipped() {
let view = at(100., 500.);
assert!(!away(at(100., 100.), px(0.), view));
assert!(!away(at(1000., 100.), px(0.), view));
assert!(away(at(1200., 100.), px(0.), view));
assert!(away(at(-600., 100.), px(0.), view));
// Scrolled 700 px down since: the row that was far below is now on screen.
assert!(!away(at(1200., 100.), px(-700.), view));
fn ten_thousand_rows_build_only_nearby_elements_on_the_first_frame() {
let list = Cull::default();
let mut count = 0;
list.column(
&ScrollHandle::new(),
10_000,
8.,
|_| false,
|_| {
count += 1;
div().h(px(96.)).mb(px(8.))
},
);
assert!(count <= 17, "built {count} rows before the first layout");
let spans = list
.0
.borrow_mut()
.plan(at(0., 800., 600.), px(0.), 10_000, 8., |_| false);
assert!(spans.len() <= count + 1, "hidden rows share one spacer");
}
#[test]
fn nothing_is_skipped_before_the_rows_are_known() {
let cull = Cull::default();
cull.0.borrow_mut().rows = (0..10).map(|i| at(i as f32 * 2000., 100.)).collect();
// No viewport yet (the first frame), or another number of rows: every row is drawn.
let far = cull.far(&ScrollHandle::new(), 10);
assert!((0..10).all(|i| far(i).is_none()));
let far = cull.far(&ScrollHandle::new(), 11);
assert!((0..11).all(|i| far(i).is_none()));
fn large_scroll_jumps_reach_the_last_rows_and_return_to_the_first() {
let mut state = Drawn::default();
let view = at(0., 500., 600.);
state.plan(view, px(0.), 10_000, 8., |_| false);
state.width = view.size.width;
let end = state.plan(view, px(-1_039_500.), 10_000, 8., |_| false);
assert!(rendered(&end).contains(&9_999));
assert!(rendered(&end).len() < 20);
assert_eq!(
rendered(&state.plan(view, px(0.), 10_000, 8., |_| false))[0],
0
);
}
#[test]
fn resizing_and_appending_keep_render_work_bounded_and_retained_rows_available() {
let mut state = Drawn::default();
let view = at(0., 500., 600.);
state.plan(view, px(0.), 5_000, 8., |_| false);
state.width = view.size.width;
state.heights[100] = px(900.);
let spans = state.plan(at(0., 500., 300.), px(0.), 10_000, 8., |index| {
index == 9_000
});
assert_eq!(state.heights[100], px(104.));
assert!(rendered(&spans).contains(&9_000));
assert!(spans.len() < 20);
assert_eq!(state.heights.len(), 10_000);
}
#[test]
fn measurements_include_wrapping_and_reveal_spacers_after_headers_move() {
let mut state = Drawn::default();
let view = at(0., 500., 600.);
state.plan(view, px(0.), 100, 8., |_| false);
let spans = vec![Span::Row(0), Span::Space(px(10_296.))];
assert!(state.record(
&spans,
&[at(0., 240., 600.), at(240., 10_296., 600.)],
view,
px(0.)
));
assert_eq!(state.heights[0], px(240.));
assert!(rendered(&state.plan(view, px(0.), 100, 8., |_| false)).contains(&1));
let list = Cull::default();
list.0.borrow_mut().heights = vec![px(400.); 100];
list.reset();
assert!(list.0.borrow().heights.is_empty());
}
}
#[cfg(all(test, target_os = "windows"))]
mod desktop_tests {
use super::*;
use gpui::{
prelude::*, AppContext, Application, Context, Render, Window, WindowBounds, WindowOptions,
};
use std::time::Duration;
struct ListWindow {
list: Cull,
scroll: ScrollHandle,
rendered: Vec<usize>,
}
impl Render for ListWindow {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.rendered.clear();
let rows = self.list.column(
&self.scroll,
10_000,
8.,
|_| false,
|index| {
self.rendered.push(index);
div()
.h(px(if index % 2 == 0 { 72. } else { 180. }))
.mb(px(8.))
.child(format!("Row {index}"))
},
);
div()
.id("viewport")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.scroll)
.child(div().pt(px(320.)).child(rows))
}
}
#[test]
#[ignore = "requires an interactive desktop and graphics adapter"]
fn desktop_list_renders_the_viewport_after_scrollbar_jumps() {
Application::new().run(|cx| {
let window = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.), px(0.)),
size(px(600.), px(500.)),
))),
..WindowOptions::default()
},
|_, cx| {
cx.new(|_| ListWindow {
list: Cull::default(),
scroll: ScrollHandle::new(),
rendered: Vec::new(),
})
},
)
.unwrap();
cx.spawn(async move |cx| {
for step in 0..3 {
cx.background_executor()
.timer(Duration::from_millis(300))
.await;
window
.update(cx, |view, _, cx| {
assert!(
view.rendered.len() < 40,
"rendered {} rows",
view.rendered.len()
);
let wanted = if step == 1 { 9_999 } else { 0 };
assert!(
view.rendered.contains(&wanted),
"row {wanted} missing: {:?}",
view.rendered
);
let measured = view.list.0.borrow();
let mut top = measured.top;
for (index, height) in measured.heights.iter().enumerate() {
if top < view.scroll.bounds().bottom()
&& top + *height > view.scroll.bounds().top()
{
assert!(
view.rendered.contains(&index),
"visible row {index} was a spacer"
);
}
top += *height;
}
if step == 1 {
assert!(
top <= view.scroll.bounds().bottom() + px(1.),
"the last row stayed below the viewport by {:?}",
top - view.scroll.bounds().bottom()
);
}
drop(measured);
let offset = if step == 0 {
-view.scroll.max_offset().height
} else {
px(0.)
};
view.scroll.set_offset(point(px(0.), offset));
cx.notify();
})
.unwrap();
}
cx.update(|cx| cx.quit()).unwrap();
})
.detach();
});
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ use horizon_launcher::backend;
use serde_json::{json, Value};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::process::{Child, ChildStdin, ChildStdout, Stdio};
pub const PREFIX: &str = "game_";
@@ -61,7 +61,7 @@ impl GameTools {
if !ctl.exists() {
return Err(format!("{tag} has no {CTL}"));
}
let mut child = Command::new(&ctl)
let mut child = horizon_launcher::process::command(&ctl)
.arg("--socket")
.arg(socket_path())
.arg("mcp")
+1
View File
@@ -9,6 +9,7 @@ pub mod game_app;
pub mod heads;
pub mod modpacks;
pub mod mojang;
pub mod process;
pub mod servers;
pub mod signed;
pub mod sources;
+60 -36
View File
@@ -1,12 +1,15 @@
//! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft,
//! and starts the client or a dedicated server.
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
mod agents_page;
mod art;
mod blocks;
mod cli;
mod cli_tools;
mod collection;
mod console;
mod cull;
mod game_tools;
mod internet;
@@ -19,12 +22,13 @@ mod perf;
mod scrollbar;
mod servers_page;
mod theme;
mod titlebar;
use gpui::{
actions, div, ease_out_quint, prelude::*, px, relative, size, Animation, AnimationExt,
AnyElement, App, Application, Bounds, ClickEvent, Context, Div, ElementId, FocusHandle,
FontWeight, Hsla, KeyBinding, KeyDownEvent, Menu, MenuItem, PathPromptOptions, SharedString,
Stateful, Subscription, TitlebarOptions, Window, WindowBounds, WindowOptions,
Stateful, Subscription, Window, WindowBounds, WindowOptions,
};
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates};
@@ -366,6 +370,9 @@ impl Launcher {
self.switches += 1;
self.content_scroll = Scrollbar::default();
self.long_list = cull::Cull::default();
if page == Page::Mods {
self.mods.reset_lists();
}
}
self.picker_open = false;
}
@@ -1313,11 +1320,11 @@ fn megabytes(bytes: u64) -> String {
// ----- Pages -------------------------------------------------------------------------------------
impl Launcher {
/// The top bar: the mark and the name over the sidebar, the pages with their icons, then
/// the account playing and the Settings button.
/// The top bar: the mark and the name over the sidebar (in the title bar on Windows), the
/// pages with their icons, then the account playing and the Settings button.
fn topbar(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let mut nav = div().flex().h_full().gap(px(2.));
let mut nav = div().flex().flex_none().h_full().gap(px(2.));
for (page, label, icon) in Page::ALL {
if page == Page::Settings {
continue;
@@ -1372,6 +1379,8 @@ impl Launcher {
let account = keyboard(div().id("account"), &t)
.relative()
.flex()
.min_w_0()
.max_w(px(180.))
.items_center()
.gap(px(10.))
.h(px(40.))
@@ -1395,8 +1404,10 @@ impl Launcher {
div()
.flex()
.flex_col()
.min_w_0()
.child(
blocks::pixel(14., FontWeight::MEDIUM)
.truncate()
.text_color(t.ink)
.child(name),
)
@@ -1448,25 +1459,29 @@ impl Launcher {
.bg(t.side)
.border_b_2()
.border_color(t.outline)
.child(
div()
.flex()
.flex_none()
.items_center()
.gap(px(10.))
.w(px(theme::SIDEBAR - 18.))
.child(mark(24., &t))
.child(
blocks::pixel(20., FontWeight::SEMIBOLD)
.text_color(t.ink)
.child("HORIZON"),
),
)
// Where the title bar is drawn here (Windows), it carries the mark and the name.
.when(!titlebar::DRAWN, |bar| {
bar.child(
div()
.flex()
.flex_none()
.items_center()
.gap(px(10.))
.w(px(theme::SIDEBAR - 18.))
.child(mark(24., &t))
.child(
blocks::pixel(20., FontWeight::SEMIBOLD)
.text_color(t.ink)
.child("HORIZON"),
),
)
})
.child(nav)
.child(
div()
.ml_auto()
.flex()
.flex_none()
.items_center()
.gap(px(8.))
.child(account)
@@ -1835,7 +1850,7 @@ impl Launcher {
wrap
}
fn play_page(&mut self, cx: &mut Context<Self>) -> Div {
fn play_page(&mut self, banner_width: f32, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let Some(tag) = self.selected().cloned() else {
// No hero without a version: the page starts below the top bar like the others.
@@ -1994,7 +2009,7 @@ impl Launcher {
// The banner: Horizon's landscape (`art.rs`) under a veil of the page colour, the hero and
// the Play row over it. It reaches the content's edges and the top bar.
let scene = self.art.scene(t.dark, self.scale);
let (scene, scene_width) = self.art.scene(t.dark, self.scale, banner_width);
let veil = |angle: f32, from: f32, to: f32, at: f32| {
div()
.absolute()
@@ -2007,15 +2022,14 @@ impl Launcher {
gpui::linear_color_stop(t.page.opacity(to), at),
))
};
let (w, h) = art::SCENE_SIZE;
let banner = div()
.relative()
.flex()
.flex_col()
.justify_end()
.min_h(px(340.))
.mx(px(-32.))
.px(px(32.))
.mx(px(-theme::PAGE_GUTTER))
.px(px(theme::PAGE_GUTTER))
.pb(px(28.))
.gap(px(24.))
.overflow_hidden()
@@ -2027,8 +2041,8 @@ impl Launcher {
.absolute()
.bottom_0()
.left_0()
.w(px(w as f32 * art::SCENE_TEXEL))
.h(px(h as f32 * art::SCENE_TEXEL)),
.w(px(scene_width))
.h(px(art::SCENE_HEIGHT as f32 * art::SCENE_TEXEL)),
)
.child(veil(90., 0.82, 0., 0.62))
.child(veil(180., 0., 0.75, 1.))
@@ -2901,7 +2915,7 @@ impl Launcher {
))
}
Load::Ready(r) if r.is_empty() => return page.child(centered("No releases yet.", &t)),
Load::Ready(r) => r.clone(),
Load::Ready(r) => r,
};
// A hundred releases: only the rows near the screen are drawn.
let keep = |i: usize| {
@@ -3138,7 +3152,7 @@ impl Launcher {
),
)
}
Load::Ready(r) => r.clone(),
Load::Ready(r) => r,
};
let list = self.long_list.clone().column(
&self.content_scroll.handle,
@@ -3251,21 +3265,23 @@ impl Render for Launcher {
self.friend_focused = self.friend_focus.is_focused(window);
self.mods.note_focus(window);
self.args_focused = self.args_focus.is_focused(window);
let size = window.viewport_size();
let banner_width = f32::from(size.width) - theme::SIDEBAR - scrollbar::GUTTER;
let content = match self.page {
Page::Play => self.play_page(cx),
Page::Play => self.play_page(banner_width, cx),
Page::Versions => self.versions_page(cx),
Page::Mods => self.mods_page(cx),
Page::Servers => self.servers_page(cx),
Page::Notes => self.notes_page(cx),
Page::Settings => self.settings_page(cx),
};
self.art.free_replaced(window);
// The new page fades in and rises a few pixels.
let content = div()
.relative()
.w_full()
// Let the page shrink inside the padded flex row so long notices can wrap.
.min_w_0()
.max_w(px(1152.))
.child(content)
.with_animation(
ElementId::named_usize("page", self.switches),
@@ -3277,7 +3293,6 @@ impl Render for Launcher {
if self.opening.is_none() && window.focused(cx).is_none() {
window.focus(&self.root_focus);
}
let size = window.viewport_size();
let stone = self.art.stone(t.page_rgb, t.dark, window.scale_factor());
let topbar = self.topbar(cx);
let sidebar = self.sidebar(cx);
@@ -3333,7 +3348,9 @@ impl Render for Launcher {
.child(
div()
.flex()
.px(px(32.))
.w_full()
.min_w_0()
.px(px(theme::PAGE_GUTTER))
.pt(px(if self.page == Page::Play {
0.
} else {
@@ -3411,7 +3428,13 @@ impl Render for Launcher {
}),
);
}
root
div()
.flex()
.flex_col()
.size_full()
.bg(t.side)
.children(titlebar::render(&t, window))
.child(root.flex_1().min_h_0())
}
}
@@ -3497,6 +3520,10 @@ fn menus() -> Vec<Menu> {
}
fn main() {
if let Err(error) = console::attach_for_cli() {
eprintln!("Could not restore the launcher's terminal streams: {error}");
std::process::exit(1);
}
perf::process_started();
backend::exe_path();
if let Some(code) = cli::run() {
@@ -3533,10 +3560,7 @@ fn main() {
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_min_size: Some(size(px(960.), px(600.))),
titlebar: Some(TitlebarOptions {
title: Some("Horizon".into()),
..Default::default()
}),
titlebar: Some(titlebar::options()),
app_id: Some("horizon-launcher".into()),
..Default::default()
},
+17 -5
View File
@@ -50,6 +50,7 @@ impl Launcher {
self.pack_busy = false;
match result {
Ok(pack) => {
self.mods.report_list.reset();
self.pack_open = Some(pack.slug.clone());
self.packs.retain(|p| p.slug != pack.slug);
self.packs.push(*pack);
@@ -127,6 +128,7 @@ impl Launcher {
/// Reads the imported packs, once (the sidebar and the Modpacks tab both show them).
pub(super) fn load_packs(&mut self) {
if self.packs_loaded.is_none() {
self.mods.report_list.reset();
self.packs = modpacks::list();
if self.pack_open.is_none() {
self.pack_open = self.packs.first().map(|p| p.slug.clone());
@@ -193,6 +195,7 @@ impl Launcher {
button(format!("open-{slug}"), "Open", Kind::Ghost, &t)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.pack_open = Some(slug.clone());
this.mods.report_list.reset();
cx.notify();
}))
.into_any_element()
@@ -317,6 +320,7 @@ impl Launcher {
Ok(()) => {
this.packs.retain(|p| p.slug != slug);
this.pack_open = this.packs.first().map(|p| p.slug.clone());
this.mods.report_list.reset();
}
Err(e) => this.pack_error = Some(e),
}
@@ -354,12 +358,13 @@ impl Launcher {
move |value, _, cx| {
let _ = this.update(cx, |this, cx| {
this.pack_filter = value;
this.mods.report_list.reset();
cx.notify();
});
}
});
let mut list = div().flex().flex_col();
for (i, r) in rows.iter().enumerate() {
let row = |i: usize| {
let r = rows[i];
let color = match r.status {
Status::Ported => t.success,
Status::Partial => t.accent,
@@ -372,7 +377,7 @@ impl Launcher {
format!("{} ({})", r.name, r.key)
};
let detail = format!("{} · {} · {}: {}", r.class, r.tier, r.license, r.reason);
list = list.child(index_row(
index_row(
i + 1,
name,
Some(detail.into_any_element()),
@@ -383,8 +388,15 @@ impl Launcher {
.into_any_element(),
),
&t,
));
}
)
};
let list = self.mods.report_list.column(
&self.content_scroll.handle,
rows.len(),
8.,
|_| false,
row,
);
Some(
div()
.flex()
+56 -17
View File
@@ -54,6 +54,9 @@ pub(super) struct Mods {
searching: bool,
searched: bool,
results: Vec<Project>,
results_list: cull::Cull,
installed_list: cull::Cull,
pub(super) report_list: cull::Cull,
more: bool,
error: Option<String>,
installed: Vec<installed::Entry>,
@@ -72,6 +75,12 @@ pub(super) struct Mods {
}
impl Mods {
pub(super) fn reset_lists(&self) {
self.results_list.reset();
self.installed_list.reset();
self.report_list.reset();
}
/// Whether the Modpacks tab is open (the sidebar marks the pack shown there).
pub(super) fn on_modpacks(&self) -> bool {
self.kind == PackKind::Modpack
@@ -94,6 +103,9 @@ impl Mods {
searching: false,
searched: false,
results: Vec::new(),
results_list: cull::Cull::default(),
installed_list: cull::Cull::default(),
report_list: cull::Cull::default(),
more: false,
error: None,
installed: Vec::new(),
@@ -158,6 +170,7 @@ impl Launcher {
self.go(Page::Mods);
if slug.is_some() {
self.pack_open = slug;
self.mods.report_list.reset();
}
if self.mods.kind != PackKind::Modpack {
self.mods.kind = PackKind::Modpack;
@@ -203,6 +216,7 @@ impl Launcher {
m.busy = None;
m.message = Some(result);
m.installed = installed::Installed::load(&backend::game_home()).entries;
m.installed_list.reset();
if modpack {
// The Modpacks page reads its list again.
self.packs_loaded = None;
@@ -249,6 +263,8 @@ impl Launcher {
if offset == 0 {
m.results.clear();
m.more = false;
m.results_list.reset();
m.installed_list.reset();
}
let query = Query {
everything: m.everything,
@@ -295,8 +311,18 @@ impl Launcher {
.ok_or_else(|| format!("{} isn't set up.", p.source.label()))
.and_then(|source| {
java::check_project(&home, &*source, &p, everything, &|_| {})
})
.map(|(_, c)| Box::new(c));
});
// The project's page, if open, shows the verdict beside its version.
if let Ok((version, check)) = &result {
let key = (p.source, p.id.clone());
let _ =
tx.send(Event::Loaded(super::mods_project::Loaded::Checked(
key,
version.id.clone(),
check.verdict,
)));
}
let result = result.map(|(_, check)| Box::new(check));
let _ = tx.send(Event::Checked((p.source, p.id), result));
}
});
@@ -608,8 +634,8 @@ impl Launcher {
return None;
}
let busy = self.mods.busy.is_some();
let mut list = div().flex().flex_col();
for (i, e) in entries.into_iter().enumerate() {
let row = |i: usize| {
let e = entries[i];
let key = (e.source, e.project.clone());
let mut right = div().flex().items_center().gap(px(8.));
if let Some(number) = self.mods.updates.get(&key) {
@@ -654,6 +680,7 @@ impl Launcher {
installed::remove(&home, &id).map(|e| format!("Removed {}.", e.title)),
);
this.mods.installed = installed::Installed::load(&home).entries;
this.mods.installed_list.reset();
this.mods.confirm_remove = None;
} else {
this.mods.confirm_remove = Some(id.clone());
@@ -689,14 +716,21 @@ impl Launcher {
.font_family(theme::MONO)
.child(format!("checked: {}", short_sum(&e.checksum))),
);
list = list.child(index_row(
index_row(
i + 1,
e.title.clone(),
Some(detail.into_any_element()),
Some(right.into_any_element()),
&t,
));
}
)
};
let list = self.mods.installed_list.column(
&self.content_scroll.handle,
entries.len(),
8.,
|index| self.mods.confirm_remove.as_ref() == Some(&entries[index].project),
row,
);
Some(
div()
.flex()
@@ -709,8 +743,6 @@ impl Launcher {
fn mods_results(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let found = self.mods.results.clone();
let icons: Vec<AnyElement> = found.iter().map(|p| self.mods_icon(p, 56.)).collect();
let m = &self.mods;
if let Some(e) = &m.error {
return div().child(notice(e.clone(), &t));
@@ -725,10 +757,15 @@ impl Launcher {
};
return centered(line, &t);
}
let busy = m.busy.as_ref().map(|b| b.0.as_str());
let mut icons = icons.into_iter();
let mut list = div().flex().flex_col();
for (i, p) in m.results.iter().enumerate() {
let result_count = m.results.len();
let rows = m.results_list.clone();
let scroll = self.content_scroll.handle.clone();
let row = |i: usize| {
let project = self.mods.results[i].clone();
let icon = self.mods_icon(&project, 56.);
let p = &project;
let m = &self.mods;
let busy = m.busy.as_ref().map(|b| b.0.as_str());
let support = m.support(p);
let checking = p.kind == PackKind::Mod
&& matches!(
@@ -813,21 +850,23 @@ impl Launcher {
.items_center()
.gap(px(12.))
.cursor_pointer()
.child(icons.next().expect("one icon per result"))
.child(icon)
.child(div().hover(|s| s.underline()).child(p.title.clone()))
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.mods_open(open.clone());
cx.notify();
}));
list = list.child(index_row(
index_row(
i + 1,
name,
Some(detail.into_any_element()),
Some(right.into_any_element()),
&t,
));
}
)
};
let list = rows.column(&scroll, result_count, 8., |_| false, row);
let mut out = div().flex().flex_col().child(list);
let m = &self.mods;
if m.more {
let mut more = button("mods-more", "More", Kind::Ghost, &t);
if m.searching {
+73 -23
View File
@@ -19,6 +19,7 @@ use horizon_launcher::browser::{
};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
/// A project page's tabs.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -38,8 +39,17 @@ const TABS: [(Tab, &str); 3] = [
pub(super) struct Opened {
pub(super) project: Project,
tab: Tab,
details: Option<Result<Details, String>>,
versions: Option<Result<Vec<Version>, String>>,
details: Option<Result<Arc<Details>, String>>,
versions: Option<Result<Arc<[ProjectVersion]>, String>>,
version_list: cull::Cull,
checked_versions: HashMap<String, horizon_port_pack::check::Verdict>,
}
/// Cached verdicts are read with the version request, never while drawing a frame.
#[derive(Clone)]
pub(super) struct ProjectVersion {
version: Version,
verdict: Option<horizon_port_pack::check::Verdict>,
}
/// The project page, filters and images' share of the Mods page's state.
@@ -58,7 +68,12 @@ pub(super) struct Browse {
/// What the background sends this module.
pub(super) enum Loaded {
Details((SourceId, String), Result<Details, String>),
Versions((SourceId, String), Result<Vec<Version>, String>),
Versions((SourceId, String), Result<Vec<ProjectVersion>, String>),
Checked(
(SourceId, String),
String,
horizon_port_pack::check::Verdict,
),
Image((String, u32), Option<PathBuf>),
Tags((SourceId, PackKind), Result<Tags, String>),
}
@@ -77,12 +92,20 @@ impl Launcher {
match loaded {
Loaded::Details(key, d) => {
if let Some(o) = open(b, &key) {
o.details = Some(d);
o.details = Some(d.map(Arc::new));
}
}
Loaded::Versions(key, v) => {
if let Some(o) = open(b, &key) {
o.versions = Some(v);
o.versions = Some(v.map(Arc::from));
o.apply_checks();
o.version_list.reset();
}
}
Loaded::Checked(key, version, verdict) => {
if let Some(o) = open(b, &key) {
o.checked_versions.insert(version, verdict);
o.apply_checks();
}
}
Loaded::Image(key, path) => {
@@ -106,7 +129,21 @@ impl Launcher {
};
let d = source.details(&p);
let _ = tx.send(Event::Loaded(Loaded::Details(key.clone(), d)));
let v = source.versions(&p);
let v = source.versions(&p).map(|versions| {
let home = backend::game_home();
versions
.into_iter()
.map(|version| {
let verdict = version.file().and_then(|file| {
(p.kind == PackKind::Mod)
.then(|| java::cached(&home, file))
.flatten()
.map(|check| check.verdict)
});
ProjectVersion { version, verdict }
})
.collect()
});
let _ = tx.send(Event::Loaded(Loaded::Versions(key, v)));
});
self.mods.browse.open = Some(Opened {
@@ -114,6 +151,8 @@ impl Launcher {
tab: Tab::Description,
details: None,
versions: None,
version_list: cull::Cull::default(),
checked_versions: HashMap::new(),
});
}
@@ -361,6 +400,7 @@ impl Launcher {
));
let details = o.details.clone();
let versions = o.versions.clone();
let version_list = o.version_list.clone();
let mut meta = vec![format!("{} downloads", thousands(p.downloads))];
if let Some(Ok(d)) = &details {
meta.push(format!("{} followers", thousands(d.followers)));
@@ -551,9 +591,13 @@ impl Launcher {
Tab::Versions => match &versions {
None => centered("Loading…", &t),
Some(Err(e)) => notice(e.clone(), &t),
Some(Ok(list)) => {
let mut rows = div().flex().flex_col();
for (i, v) in list.iter().take(50).enumerate() {
Some(Ok(list)) => version_list.column(
&self.content_scroll.handle,
list.len().min(50),
8.,
|_| false,
|i| {
let v = &list[i].version;
let file = v.file();
let mut detail = vec![
v.published.get(..10).unwrap_or_default().to_string(),
@@ -570,27 +614,33 @@ impl Launcher {
if let Some(f) = file {
detail.push(format!("{} · {:.1} MB", f.name, f.size as f64 / 1e6));
}
let checked = file.and_then(|f| {
(p.kind == PackKind::Mod)
.then(|| java::cached(&backend::game_home(), f))
.flatten()
});
rows = rows.child(index_row(
index_row(
i + 1,
v.number.clone(),
Some(detail.join(" · ").into_any_element()),
checked.map(|c| {
caps(c.verdict.label())
.text_color(t.muted)
.into_any_element()
list[i].verdict.as_ref().map(|verdict| {
caps(verdict.label()).text_color(t.muted).into_any_element()
}),
&t,
));
}
rows
}
)
},
),
},
};
Some(page.child(body))
}
}
impl Opened {
/// A check can finish before or after the version request; retain either event order.
fn apply_checks(&mut self) {
let Some(Ok(versions)) = &mut self.versions else {
return;
};
for row in Arc::make_mut(versions) {
if let Some(verdict) = self.checked_versions.get(&row.version.id) {
row.verdict = Some(*verdict);
}
}
}
}
+89 -4
View File
@@ -9,10 +9,11 @@
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use horizon_bench::{App, Frames, Kind, Report};
use horizon_bench::{App, Frames, Hardware, Kind, Report};
/// The first thing `main` does; every start time counts from here.
pub fn process_started() -> Instant {
@@ -35,14 +36,36 @@ pub struct Perf {
dirty: bool,
/// Off for the windows `horizon-launcher benchmark` starts: they report to it instead.
log: bool,
/// Machine probes run after the first frame, never while opening the window.
hardware: Option<Receiver<Machine>>,
}
#[derive(Debug)]
struct Machine {
hardware: Hardware,
power: Option<String>,
load_average: Option<f64>,
}
impl Machine {
fn detect() -> Self {
Self {
hardware: Hardware::detect(),
power: horizon_bench::power_source().map(str::to_owned),
load_average: horizon_bench::load_average(),
}
}
}
impl Perf {
pub fn new(scenario: &str) -> Perf {
let mut report = Report::new(Kind::Launcher, app());
let hardware = Hardware {
os: std::env::consts::OS.to_owned(),
arch: std::env::consts::ARCH.to_owned(),
..Hardware::default()
};
let mut report = Report::with_hardware(Kind::Launcher, app(), hardware);
report.conditions.scenario = Some(scenario.to_owned());
report.conditions.power = horizon_bench::power_source().map(str::to_owned);
report.conditions.load_avg_1m = horizon_bench::load_average();
let path = crate::backend::data_dir().join("benchmarks").join(format!(
"launcher-{}-{scenario}.json",
report
@@ -61,6 +84,7 @@ impl Perf {
saved: Instant::now(),
dirty: false,
log: true,
hardware: None,
};
if let Some(bytes) = binary_bytes() {
perf.record("launcher.binary_bytes", bytes);
@@ -89,6 +113,12 @@ impl Perf {
if first {
self.first_frame = Some(now);
self.record_since("launcher.start_ms", process_started());
let (sender, receiver) = mpsc::channel();
self.hardware = Some(receiver);
std::thread::spawn(move || {
// The window may close before the optional report details finish.
let _ = sender.send(Machine::detect());
});
} else if let Some(gap) = self.last_frame.map(|t| now - t).filter(|g| *g < IDLE_GAP) {
self.ui_frames.push(gap.as_secs_f32() * 1000.0);
}
@@ -102,6 +132,7 @@ impl Perf {
/// Samples memory and writes the report when something changed, at most every few seconds.
pub fn tick(&mut self) {
self.poll_hardware();
if self.saved.elapsed() < Duration::from_secs(5) {
return;
}
@@ -118,6 +149,7 @@ impl Perf {
}
pub fn report(&mut self) -> &Report {
self.poll_hardware();
for (name, values) in &self.values {
self.report.metric(name, values);
}
@@ -128,6 +160,24 @@ impl Perf {
&self.report
}
/// Takes the machine's details into the report once their thread has them.
fn poll_hardware(&mut self) {
let Some(receiver) = &self.hardware else {
return;
};
match receiver.try_recv() {
Ok(machine) => {
self.report.hardware = machine.hardware;
self.report.conditions.power = machine.power;
self.report.conditions.load_avg_1m = machine.load_average;
self.hardware = None;
self.dirty = true;
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => self.hardware = None,
}
}
pub fn save(&mut self) {
self.dirty = false;
if !self.log {
@@ -381,6 +431,41 @@ fn binary_bytes() -> Option<f64> {
mod tests {
use super::*;
#[test]
fn performance_tracking_starts_without_hardware_probes() {
let mut perf = Perf::new("test");
perf.keep_local_log(false);
assert!(perf.hardware.is_none());
assert_eq!(perf.report.hardware.os, std::env::consts::OS);
assert!(perf.report.hardware.cpu.is_none());
assert!(perf.report.conditions.power.is_none());
}
#[test]
fn background_hardware_details_preserve_recorded_metrics() {
let mut perf = Perf::new("test");
perf.keep_local_log(false);
perf.record("launcher.start_ms", 125.);
let (sender, receiver) = mpsc::channel();
perf.hardware = Some(receiver);
assert_eq!(perf.report().metrics["launcher.start_ms"].mean, 125.);
sender
.send(Machine {
hardware: Hardware {
cpu: Some("Detected CPU".into()),
..Hardware::default()
},
power: Some("ac".into()),
load_average: Some(0.5),
})
.unwrap();
let report = perf.report();
assert_eq!(report.hardware.cpu.as_deref(), Some("Detected CPU"));
assert_eq!(report.conditions.power.as_deref(), Some("ac"));
assert_eq!(report.metrics["launcher.start_ms"].mean, 125.);
assert!(perf.hardware.is_none());
}
#[test]
fn the_first_frame_is_the_start_and_close_frames_are_ui_frames() {
let mut perf = Perf::new("test");
+21
View File
@@ -0,0 +1,21 @@
//! The programs the launcher runs in the background: on Windows they open no console window
//! (the launcher has none to share), and keep the streams their caller gives them.
use std::ffi::OsStr;
use std::process::Command;
pub fn command(program: impl AsRef<OsStr>) -> Command {
let mut command = Command::new(program);
hide_console(&mut command);
command
}
/// [`command`] for a `Command` made elsewhere.
pub fn hide_console(command: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
command
}
+4 -1
View File
@@ -6,6 +6,9 @@ use gpui::{
};
use std::{cell::Cell, rc::Rc};
/// Space reserved beside scroll content for the track and its padding.
pub const GUTTER: f32 = 16.;
#[derive(Clone, Default)]
pub(crate) struct Scrollbar {
pub handle: ScrollHandle,
@@ -60,7 +63,7 @@ impl Scrollbar {
.child(
content
.track_scroll(&self.handle)
.mr(px(16.))
.mr(px(GUTTER))
// Nested scroll areas must not also move the page behind them.
.on_scroll_wheel(|_, _, cx| cx.stop_propagation()),
)
+3 -5
View File
@@ -245,7 +245,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> {
#[cfg(windows)]
{
let _ = fs::remove_dir(link);
let status = Command::new("cmd")
let status = crate::process::command("cmd")
.args(["/C", "mklink", "/J"])
.arg(link)
.arg(target)
@@ -266,10 +266,8 @@ pub fn command(dir: &Path, args: &[&str]) -> Result<Command, String> {
let program = program().ok_or(
"The server programs aren't set up yet: create a server, or press Prepare on its page.",
)?;
let mut cmd = Command::new(program);
let mut cmd = crate::process::command(program);
cmd.arg("--dir").arg(dir).args(args);
#[cfg(windows)]
std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW
Ok(cmd)
}
@@ -752,7 +750,7 @@ pub fn lan_address() -> Option<std::net::IpAddr> {
pub fn service_installed(dir: &Path) -> bool {
if cfg!(windows) {
let name = format!("horizon-server-{}", service_suffix(dir));
return Command::new("schtasks")
return crate::process::command("schtasks")
.args(["/Query", "/TN", &name])
.stdout(Stdio::null())
.stderr(Stdio::null())
+1 -1
View File
@@ -488,7 +488,7 @@ fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
arg.push("\"");
arg
};
let status = std::process::Command::new("cmd")
let status = crate::process::command("cmd")
.args(["/C", "mklink", "/J"])
.raw_arg(quoted(link))
.raw_arg(quoted(target))
+1 -6
View File
@@ -126,13 +126,8 @@ pub fn status_of(cli: Option<PathBuf>) -> State {
let Some(cli) = cli else {
return State::Missing;
};
let mut command = Command::new(&cli);
let mut command = crate::process::command(&cli);
command.args(["status", "--json"]);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
let out = match command.output() {
Ok(out) => out,
Err(e) => return State::Off(e.to_string()),
+1
View File
@@ -24,6 +24,7 @@ pub const CONTROL: f32 = 34.;
/// The top bar, and the sidebar of instances and servers.
pub const TOPBAR: f32 = 56.;
pub const SIDEBAR: f32 = 248.;
pub const PAGE_GUTTER: f32 = 32.;
/// Motion: short and eased out, never bouncy.
pub const QUICK: Duration = tokens::QUICK.duration();
+156
View File
@@ -0,0 +1,156 @@
//! Custom Windows chrome. Other platforms keep their native window decorations.
use crate::theme::Theme;
use gpui::{Div, TitlebarOptions, Window};
/// Whether the launcher draws its own title bar (`render`) rather than the system.
pub const DRAWN: bool = cfg!(target_os = "windows");
pub fn options() -> TitlebarOptions {
TitlebarOptions {
title: Some("Horizon".into()),
appears_transparent: DRAWN,
..Default::default()
}
}
#[cfg(not(target_os = "windows"))]
pub fn render(_theme: &Theme, _window: &Window) -> Option<Div> {
None
}
#[cfg(target_os = "windows")]
mod windows {
use super::*;
use crate::{blocks, mark};
use gpui::{div, prelude::*, px, FontWeight, Stateful, WindowControlArea};
const HEIGHT: f32 = 32.;
const BUTTON_WIDTH: f32 = 46.;
const RESIZE_INSET: f32 = 5.;
#[derive(Clone, Copy)]
enum Control {
Minimize,
Maximize,
Close,
}
impl Control {
fn area(self) -> WindowControlArea {
match self {
Self::Minimize => WindowControlArea::Min,
Self::Maximize => WindowControlArea::Max,
Self::Close => WindowControlArea::Close,
}
}
fn name(self) -> &'static str {
match self {
Self::Minimize => "window-minimize",
Self::Maximize => "window-maximize",
Self::Close => "window-close",
}
}
}
fn control_icon(control: Control, maximized: bool, theme: &Theme) -> Div {
let square = || {
div()
.absolute()
.size(px(10.))
.border_1()
.border_color(theme.ink_soft)
};
let icon = div().relative().size(px(14.));
match control {
Control::Minimize => icon.child(
div()
.absolute()
.left(px(2.))
.top(px(7.))
.w(px(10.))
.h(px(1.))
.bg(theme.ink_soft),
),
Control::Maximize if maximized => icon
.child(
div()
.absolute()
.left(px(4.))
.top_0()
.size(px(10.))
.border_t_1()
.border_r_1()
.border_color(theme.ink_soft),
)
.child(square().left(px(1.)).top(px(3.))),
Control::Maximize => icon.child(square().left(px(2.)).top(px(2.))),
Control::Close => {
let hover_color = theme.page;
icon.child(
blocks::icon("close", 14., theme.ink_soft)
.group_hover("window-close", move |style| style.text_color(hover_color)),
)
}
}
}
fn control_button(control: Control, theme: &Theme, maximized: bool) -> Stateful<Div> {
let theme = *theme;
div()
.id(control.name())
.group(control.name())
.flex()
.flex_none()
.items_center()
.justify_center()
.w(px(BUTTON_WIDTH))
.h_full()
.text_color(theme.ink_soft)
// GPUI maps these to native non-client hit tests, retaining Snap Layouts,
// Alt+Space and close handling. Click callbacks would run the action twice.
.window_control_area(control.area())
.hover(move |style| match control {
Control::Close => style.bg(theme.danger).text_color(theme.page),
_ => style.bg(theme.raised),
})
.child(control_icon(control, maximized, &theme))
}
pub fn render(theme: &Theme, window: &Window) -> Option<Div> {
let drag = div()
.id("window-drag")
.flex()
.flex_1()
.h_full()
.items_center()
.gap(px(8.))
.px(px(12.))
.window_control_area(WindowControlArea::Drag)
.child(mark(16., theme))
.child(blocks::pixel(13., FontWeight::MEDIUM).child("Horizon"));
Some(
div()
.flex()
.flex_none()
.items_center()
.h(px(HEIGHT))
// Control hit tests run before native edge resizing in GPUI 0.2.2.
.when(!window.is_maximized(), |bar| {
bar.pt(px(RESIZE_INSET)).px(px(RESIZE_INSET))
})
.bg(theme.side)
.text_color(theme.muted)
.border_b_1()
.border_color(theme.outline)
.child(drag)
.children(
[Control::Minimize, Control::Maximize, Control::Close]
.map(|control| control_button(control, theme, window.is_maximized())),
),
)
}
}
#[cfg(target_os = "windows")]
pub use windows::render;
+116
View File
@@ -0,0 +1,116 @@
//! Windows background processes must keep logs, input and exit status without a console.
#![cfg(windows)]
mod support;
use horizon_launcher::{
backend::{self, Job, Msg},
process,
};
use std::{fs, path::Path, sync::mpsc, time::Duration};
use support::console_probe as probe;
fn logged_child(fail: bool) -> (Vec<String>, Result<(), String>) {
let (sender, receiver) = mpsc::channel();
let mut command = std::process::Command::new(probe());
if fail {
command.arg("--fail");
}
let mut child = backend::spawn(Job::Prepare, command, sender).unwrap();
child.send("input reaches the child");
let mut lines = Vec::new();
loop {
match receiver.recv_timeout(Duration::from_secs(10)).unwrap() {
Msg::Line(Job::Prepare, line) => lines.push(line),
Msg::Exit(Job::Prepare, result) => return (lines, result),
_ => panic!("unexpected job message"),
}
}
}
#[test]
fn hidden_children_keep_stdout_stderr_stdin_and_success() {
let (lines, result) = logged_child(false);
assert!(result.is_ok(), "{result:?}");
for expected in [
"console_window_visible=false",
"stdout is captured",
"stderr is captured",
"stdin=input reaches the child",
] {
assert!(
lines.iter().any(|line| line == expected),
"missing {expected}: {lines:?}"
);
}
}
#[test]
fn hidden_children_report_failure_and_keep_their_logs() {
let (lines, result) = logged_child(true);
assert!(result.unwrap_err().contains('7'));
assert!(lines.iter().any(|line| line == "stderr is captured"));
}
#[test]
fn exporters_write_to_their_log_file_without_a_console() {
let root = probe().parent().unwrap();
let path = root.join("exporter.log");
let log = fs::File::create(&path).unwrap();
let jdk = horizon_prepare::java::Jdk {
java: probe().into(),
javac: probe().into(),
};
jdk.java(&[], Some(root), &log).unwrap();
let output = fs::read_to_string(path).unwrap();
for expected in [
"console_window_visible=false",
"stdout is captured",
"stderr is captured",
] {
assert!(output.contains(expected), "missing {expected}: {output}");
}
}
#[test]
fn cli_keeps_redirected_stdout_and_stderr() {
let executable = env!("CARGO_BIN_EXE_horizon-launcher");
let version = process::command(executable)
.arg("--version")
.output()
.unwrap();
assert!(version.status.success());
assert!(String::from_utf8_lossy(&version.stdout).starts_with("horizon-launcher "));
let invalid = process::command(executable)
.arg("--unknown-option")
.output()
.unwrap();
assert!(!invalid.status.success());
assert!(String::from_utf8_lossy(&invalid.stderr).contains("--unknown-option"));
}
#[test]
fn mcp_keeps_its_stdio_transport() {
let executable = Path::new(env!("CARGO_BIN_EXE_horizon-launcher"));
assert!(horizon_launcher::agents::self_test(executable).unwrap() > 0);
}
#[test]
fn desktop_executable_uses_the_windows_gui_subsystem() {
const PE_HEADER_POINTER: usize = 0x3c;
const PE_OPTIONAL_HEADER_OFFSET: usize = 24;
const SUBSYSTEM_OFFSET: usize = 68;
const WINDOWS_GUI_SUBSYSTEM: u16 = 2;
let executable = fs::read(env!("CARGO_BIN_EXE_horizon-launcher")).unwrap();
let header = u32::from_le_bytes(
executable[PE_HEADER_POINTER..PE_HEADER_POINTER + 4]
.try_into()
.unwrap(),
) as usize;
assert_eq!(&executable[header..header + 4], b"PE\0\0");
let subsystem = header + PE_OPTIONAL_HEADER_OFFSET + SUBSYSTEM_OFFSET;
assert_eq!(
u16::from_le_bytes(executable[subsystem..subsystem + 2].try_into().unwrap()),
WINDOWS_GUI_SUBSYSTEM
);
}
+88
View File
@@ -0,0 +1,88 @@
//! Full launcher startup against instrumented Windows hardware probes.
#![cfg(windows)]
mod support;
use std::{
fs,
path::{Path, PathBuf},
process::{Child, Output, Stdio},
time::{Duration, Instant},
};
fn fixture() -> PathBuf {
let root = std::env::temp_dir().join(format!("horizon-startup-{}", std::process::id()));
for folder in ["game/telemetry", "launcher", "data", "config", "probes"] {
fs::create_dir_all(root.join(folder)).unwrap();
}
fs::write(root.join("launcher/settings.json"), r#"{"skip_opening":true,"install_new_versions":false,"desktop_entry":false,"ping_notice_seen":true}"#).unwrap();
let consent = serde_json::json!({"version":horizon_telemetry::CONSENT_VERSION,"choices":{}});
fs::write(
root.join("game/telemetry/consent.json"),
consent.to_string(),
)
.unwrap();
fs::copy(support::console_probe(), root.join("probes/powershell.exe")).unwrap();
root
}
fn launch(root: &Path) -> Child {
let inherited_path = std::env::var_os("PATH").unwrap();
let paths = std::iter::once(root.join("probes")).chain(std::env::split_paths(&inherited_path));
horizon_launcher::process::command(env!("CARGO_BIN_EXE_horizon-launcher"))
.current_dir(root)
.env("PATH", std::env::join_paths(paths).unwrap())
.env("HORIZON_HOME", root.join("game"))
.env("HORIZON_LAUNCHER_HOME", root.join("launcher"))
.env("XDG_DATA_HOME", root.join("data"))
.env("XDG_CONFIG_HOME", root.join("config"))
.env("HORIZON_LAUNCHER_NO_SELF_UPDATE", "1")
.env("HORIZON_NO_AUDIO", "1")
.env("HORIZON_TELEMETRY_URL", "off")
.env("HORIZON_STARTUP_PROBE_LOG", root.join("probes.log"))
.env("HORIZON_LAUNCHER_BENCH", root.join("timing.json"))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap()
}
fn wait_for_exit(mut child: Child, root: &Path) -> Output {
let deadline = Instant::now() + Duration::from_secs(30);
while child.try_wait().unwrap().is_none() {
if Instant::now() >= deadline {
child.kill().unwrap();
child.wait().unwrap();
panic!("launcher startup timed out: {}", root.display());
}
std::thread::sleep(Duration::from_millis(20));
}
child.wait_with_output().unwrap()
}
#[test]
#[ignore = "requires an interactive Windows desktop and graphics adapter"]
fn hardware_probes_run_hidden_after_the_first_frame() {
let root = fixture();
let output = wait_for_exit(launch(&root), &root);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let timing: serde_json::Value =
serde_json::from_slice(&fs::read(root.join("timing.json")).unwrap()).unwrap();
let first_frame = timing["first_frame_epoch_ms"].as_f64().unwrap().floor();
let probes = fs::read_to_string(root.join("probes.log")).unwrap();
// Rust resolves cmd.exe to the system directory, so instrument the seven PowerShell
// probes, which exercise both shared helpers (the cmd probes use those same helpers).
const POWERSHELL_PROBES: usize = 7;
assert_eq!(probes.lines().count(), POWERSHELL_PROBES, "{probes}");
for probe in probes.lines() {
let fields: Vec<_> = probe.split('|').collect();
assert!(
fields[0].parse::<f64>().unwrap() >= first_frame,
"probe blocked startup: {probe}"
);
assert_eq!(fields[1], "false", "probe opened a terminal: {probe}");
}
}
+73
View File
@@ -0,0 +1,73 @@
//! A real Windows console program used to check hidden children and their streams.
use std::ffi::c_void;
use std::io;
fn hardware_probe(visible: bool) -> bool {
let Some(path) = std::env::var_os("HORIZON_STARTUP_PROBE_LOG") else {
return false;
};
use std::io::Write;
let arguments = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
let program = std::env::current_exe().unwrap();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis();
let mut log = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap();
writeln!(
log,
"{timestamp}|{visible}|{}",
program.file_name().unwrap().to_string_lossy()
)
.unwrap();
// Slow probes make a synchronous startup regression visible without relying on WMI speed.
std::thread::sleep(std::time::Duration::from_millis(100));
let responses = [
("TotalPhysicalMemory", "17179869184"),
("NumberOfCores", "8"),
("MaxClockSpeed", "3600"),
("BatteryStatus", "2"),
("Win32_Battery", "0"),
];
let response = responses
.iter()
.find_map(|&(query, response)| arguments.contains(query).then_some(response))
.unwrap_or("Microsoft Windows [Version 10.0.26100]");
println!("{response}");
true
}
#[link(name = "kernel32")]
extern "system" {
fn GetConsoleWindow() -> *mut c_void;
}
#[link(name = "user32")]
extern "system" {
fn IsWindowVisible(window: *mut c_void) -> i32;
}
fn main() {
// A console connection can exist without a terminal window, including in ConPTY.
// SAFETY: The opaque window handle comes from Windows and is only queried, never changed.
let visible = unsafe {
let window = GetConsoleWindow();
!window.is_null() && IsWindowVisible(window) != 0
};
if hardware_probe(visible) {
return;
}
println!("console_window_visible={visible}");
println!("stdout is captured");
eprintln!("stderr is captured");
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
println!("stdin={}", input.trim());
if std::env::args().any(|argument| argument == "--fail") {
std::process::exit(7);
}
}
+29
View File
@@ -0,0 +1,29 @@
use horizon_launcher::process;
use std::{
fs,
path::{Path, PathBuf},
sync::OnceLock,
};
pub fn console_probe() -> &'static Path {
static PROBE: OnceLock<PathBuf> = OnceLock::new();
PROBE.get_or_init(|| {
let root =
std::env::temp_dir().join(format!("horizon-console-probe-{}", std::process::id()));
fs::create_dir_all(&root).unwrap();
let executable = root.join("console-probe.exe");
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/console_probe.rs");
let output = process::command("rustc")
.arg(source)
.arg("-o")
.arg(&executable)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
executable
})
}
+516
View File
@@ -0,0 +1,516 @@
#!/usr/bin/env python3
"""Server resource packs end to end: a real Horizon client joins a real dedicated server (vanilla 26.3's, or
Horizon's with --horizon-server BIN) that offers a test pack from a local HTTP server, through tools/net_capture.py,
which records the statuses the client sends back.
The pack is built here: dirt recoloured blue, and three lang strings (dirt's name, the pause menu's "Back to Game",
the server list's "Join Server"). Each scenario sets the server list entry's Server Resource Packs setting in
servers.dat, joins, answers the prompt the way a player would (horizon-ctl clicks its buttons), and checks the
statuses against what vanilla's client sends (ServerPackManager):
- required, Prompt, Disconnect: no status, the disconnected screen says "This server requires a custom resource
pack", the setting stays Prompt;
- required, Prompt, Proceed: ACCEPTED, DOWNLOADED, SUCCESSFULLY_LOADED; the setting becomes Enabled, the file is in
downloads/ under its SHA-1 with a log.json entry, the HTTP request carries vanilla's X-Minecraft-* headers, the
blue dirt is on screen (screenshot) and the pause menu says the pack's "Back to Game"; after leaving, the server
list says "Join Server" again (the pack is gone);
- required, Enabled: no prompt, the same three statuses, and no second download (the cache);
- required with a wrong SHA-1: ACCEPTED, FAILED_DOWNLOAD, and the player still joins;
- optional, Prompt, No: DECLINED, joins, the setting becomes Disabled; then joining again sends DECLINED without
asking; then Prompt and Yes: the pack (no hash given) is downloaded and loaded;
- optional on a dead URL: ACCEPTED, FAILED_DOWNLOAD, joins.
python3 tools/server_pack_e2e.py # vanilla's server
python3 tools/server_pack_e2e.py --horizon-server target/release/horizon-client
Every game and server here runs in fresh temporary folders (HORIZON_HOME, HORIZON_LAUNCHER_HOME, XDG_*), with no
audio and no self-update. Needs .local (the vanilla jars and prepared resources) and a built horizon-client and
horizon-ctl (--bin DIR, default target/fast).
"""
import argparse
import hashlib
import http.server
import json
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import zipfile
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
import net_capture # noqa: E402
import test_rust_parity as base # noqa: E402
from test_dedicated_server_parity import Server, free_port # noqa: E402
# ServerboundResourcePackPacket.Action, by ordinal.
ACTIONS = ['successfully_loaded', 'declined', 'failed_download', 'accepted', 'downloaded', 'invalid_url',
'failed_reload', 'discarded']
LOADED = ['accepted', 'downloaded', 'successfully_loaded']
FAILED = ['accepted', 'failed_download']
REQUIRED_REASON = 'This server requires a custom resource pack'
PLAYER = 'Steve'
PROPERTIES = {
'online-mode': 'false', 'white-list': 'false', 'level-seed': '12345', 'level-type': 'minecraft\\:flat',
'generate-structures': 'false', 'view-distance': '3', 'simulation-distance': '3', 'spawn-protection': '0',
'pause-when-empty-seconds': '-1', 'gamemode': 'creative',
}
class Failed(Exception):
pass
def check(condition, what):
if not condition:
raise Failed(what)
print(f' ok: {what}')
# The pack.
def png(width, height, pixel):
rows = b''.join(b'\0' + b''.join(bytes(pixel(x, y)) for x in range(width)) for y in range(height))
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
header = struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b'')
def build_pack(path):
"""The test pack, byte for byte the same every time (fixed dates), and its SHA-1."""
def blue(x, y):
return (40, 90, 230, 255) if (x // 4 + y // 4) % 2 else (20, 50, 170, 255)
files = {
'pack.mcmeta': json.dumps({'pack': {'description': 'Horizon server pack test',
'min_format': 97, 'max_format': 97}}).encode(),
'assets/minecraft/textures/block/dirt.png': png(16, 16, blue),
'assets/minecraft/lang/en_us.json': json.dumps({
'block.minecraft.dirt': 'Blue Test Dirt',
'menu.returnToGame': 'Back to Game (server pack)',
'selectServer.select': 'Join Server (server pack)',
}).encode(),
}
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as z:
for name, data in files.items():
z.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
return hashlib.sha1(path.read_bytes()).hexdigest()
def decode_png(data):
"""RGB(A) pixels of an 8-bit PNG: (width, height, rows of (r, g, b))."""
pos, idat, width = 8, b'', 0
while pos < len(data):
length, kind = struct.unpack('>I4s', data[pos:pos + 8])
body = data[pos + 8:pos + 8 + length]
if kind == b'IHDR':
width, height, depth, colour = struct.unpack('>IIBB', body[:10])
assert depth == 8 and colour in (2, 6), (depth, colour)
channels = 4 if colour == 6 else 3
elif kind == b'IDAT':
idat += body
pos += 12 + length
raw, stride, rows, previous = zlib.decompress(idat), width * channels, [], bytearray(width * channels)
for y in range(height):
kind, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for i in range(stride):
left = line[i - channels] if i >= channels else 0
up, corner = previous[i], previous[i - channels] if i >= channels else 0
if kind == 1:
line[i] = (line[i] + left) & 255
elif kind == 2:
line[i] = (line[i] + up) & 255
elif kind == 3:
line[i] = (line[i] + (left + up) // 2) & 255
elif kind == 4:
p = left + up - corner
pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner)
line[i] = (line[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else corner)) & 255
rows.append([tuple(line[x * channels:x * channels + 3]) for x in range(width)])
previous = line
return width, height, rows
def blue_share(path):
"""How much of the picture's lower middle (the ground under a player looking down) is blue."""
width, height, rows = decode_png(path.read_bytes())
samples = [rows[y][x] for y in range(height // 2 + height // 8, height - height // 8, 4)
for x in range(width // 4, 3 * width // 4, 4)]
return sum(b > r + 60 and b > g + 30 for r, g, b in samples) / len(samples)
# The HTTP server the pack comes from.
class Files(http.server.ThreadingHTTPServer):
def __init__(self, files):
self.files, self.requests = files, []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(handler):
headers = {k: v for k, v in handler.headers.items() if k.lower().startswith(('x-minecraft', 'user-agent'))}
self.requests.append((handler.path, headers))
data = self.files.get(handler.path)
if data is None:
handler.send_error(404)
return
handler.send_response(200)
handler.send_header('Content-Type', 'application/zip')
handler.send_header('Content-Length', str(len(data)))
handler.end_headers()
handler.wfile.write(data)
def log_message(handler, *args):
pass
super().__init__(('127.0.0.1', 0), Handler)
threading.Thread(target=self.serve_forever, daemon=True).start()
def url(self, path):
return f'http://127.0.0.1:{self.server_address[1]}{path}'
# servers.dat (NbtIo.write: uncompressed, a named root compound).
def nbt_string(s):
data = s.encode()
return struct.pack('>H', len(data)) + data
def write_servers(path, ip, setting):
"""One entry for ip; setting True (Enabled), False (Disabled) or None (Prompt: no acceptTextures)."""
entry = b'\x08' + nbt_string('name') + nbt_string('Pack test') + b'\x08' + nbt_string('ip') + nbt_string(ip)
if setting is not None:
entry += b'\x01' + nbt_string('acceptTextures') + bytes([int(setting)])
root = b'\x09' + nbt_string('servers') + b'\x0a' + struct.pack('>i', 1) + entry + b'\x00'
path.write_bytes(b'\x0a' + nbt_string('') + root + b'\x00')
def read_setting(path):
data = path.read_bytes()
key = b'\x01' + nbt_string('acceptTextures')
at = data.find(key)
return None if at < 0 else bool(data[at + len(key)])
# The game.
class Game:
def __init__(self, bins, resources, work):
self.home = work / 'home'
for d in ('home', 'launcher', 'data', 'config'):
(work / d).mkdir(parents=True)
self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'),
XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'),
HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')]
self.log = work / 'c.log'
reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources)
self.pid = reply.get('pid')
def __call__(self, *words, ok=True, timeout=300):
result = subprocess.run(self.base + [str(w) for w in words], cwd=self.home, env=self.env,
capture_output=True, text=True, timeout=timeout)
lines = result.stdout.strip().splitlines()
reply = json.loads(lines[-1]) if lines else {'error': result.stderr.strip()}
print(f' {" ".join(map(str, words))[:80]} -> {json.dumps(reply)[:200]}')
if ok and (result.returncode or 'error' in reply):
raise Failed(f'{" ".join(map(str, words))}: {reply}')
return reply
def labels(self):
return [w.get('label') for w in self('ui').get('widgets', [])]
def wait_widget(self, widget, timeout=60):
return self('wait-for', 'widget', widget, '--timeout', timeout, ok=False)
def quit(self):
try:
self('quit', ok=False, timeout=60)
except subprocess.TimeoutExpired:
pass
if self.pid:
for _ in range(40):
try:
os.kill(self.pid, 0)
except OSError:
return
time.sleep(0.5)
os.kill(self.pid, 9)
def statuses(capture, conn):
"""The resource pack statuses the client sent on one connection: (id, action), in order."""
out = []
for e in net_capture.load(capture):
if e.get('conn') == conn and e.get('dir') == 'c2s' and e.get('name') == 'resource_pack':
data = bytes.fromhex(e['data'])
out.append((data[:16].hex(), ACTIONS[data[16]]))
return out
def connections(capture):
return max([e['conn'] for e in net_capture.load(capture) if 'conn' in e], default=0)
class Run:
def __init__(self, args, out):
self.args, self.out = args, out
lock, jars, libraries = base.verify_artifacts()
deps = os.pathsep.join(map(str, [jars['server'], *libraries]))
self.vanilla = ['java', '-Xmx2g', '-cp', deps, 'net.minecraft.server.Main', 'nogui']
self.resources = lab.LOCAL / 'horizon-client' / lab.VERSION
self.files = {}
self.http = Files(self.files)
self.sha1 = build_pack(out / 'test-pack.zip')
self.files['/test-pack.zip'] = (out / 'test-pack.zip').read_bytes()
self.files['/optional-pack.zip'] = self.files['/test-pack.zip']
dead = free_port() # nothing listens there
self.packs = {
'required': {'resource-pack': self.http.url('/test-pack.zip'), 'resource-pack-sha1': self.sha1,
'require-resource-pack': 'true', 'resource-pack-id': '5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a',
'resource-pack-prompt': '["Blue dirt for ",{"text":"this test","color":"aqua"}]'},
'bad-sha1': {'resource-pack': self.http.url('/test-pack.zip'), 'resource-pack-sha1': '0' * 40,
'require-resource-pack': 'true'},
'optional': {'resource-pack': self.http.url('/optional-pack.zip'), 'require-resource-pack': 'false'},
'dead-url': {'resource-pack': f'http://127.0.0.1:{dead}/gone.zip', 'require-resource-pack': 'false'},
}
self.results = []
def start_server(self, kind, work):
directory = work / f'server-{kind}'
directory.mkdir()
port = free_port()
props = dict(PROPERTIES, **self.packs[kind], **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
if self.args.horizon_server:
command = [self.args.horizon_server, '--resources', self.resources, '--dedicated', '--nogui']
else:
command = self.vanilla
server = Server(command, directory, f'server-{kind}')
server.wait_for(r'Done \(', timeout=300)
return server, port
def join(self, game, address, scenario):
"""Connects; returns the capture's connection number."""
game('connect', address, PLAYER)
deadline = time.time() + 30
while connections(self.capture) <= self.conn and time.time() < deadline:
time.sleep(0.2)
self.conn = connections(self.capture)
print(f' [{scenario}] connection {self.conn}')
return self.conn
def scenario(self, name, fn):
print(f'- {name}')
try:
fn()
self.results.append((name, 'pass', ''))
except Exception as e: # noqa: BLE001: report every scenario
print(f' FAILED: {e}')
self.results.append((name, 'FAIL', str(e)[:300]))
if self.game('state', ok=False).get('screen') not in (None, 'title'):
self.leave(self.game)
def wait_statuses(self, conn, want, timeout=60):
deadline = time.time() + timeout
while time.time() < deadline:
got = [a for _, a in statuses(self.capture, conn)]
if len(got) >= len(want) and got[:len(want)] == want or got[:1] and got != want[:len(got)]:
break
time.sleep(0.3)
time.sleep(1.5) # nothing more comes after the last one
got = [a for _, a in statuses(self.capture, conn)]
check(got == want, f'statuses {got} == {want}')
def leave(self, game):
game('disconnect', ok=False)
time.sleep(1)
def run(self):
work = Path(tempfile.mkdtemp(prefix='hz-server-packs-'))
print(f'scratch: {work}')
# The servers too get scratch homes (the game sets its own below).
for var, sub in (('HORIZON_HOME', 'home'), ('HORIZON_LAUNCHER_HOME', 'launcher'), ('XDG_DATA_HOME', 'data'),
('XDG_CONFIG_HOME', 'config')):
(work / 'servers' / sub).mkdir(parents=True)
os.environ[var] = str(work / 'servers' / sub)
os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
game = self.game = Game(Path(self.args.bin), self.resources, work / 'game')
servers_dat = game.home / 'servers.dat'
downloads = game.home / 'downloads'
try:
for kind, scenarios in self.plan(game, servers_dat, downloads):
server, port = self.start_server(kind, work)
# One capture per server: its connections are numbered from 1.
self.capture, self.conn = self.out / f'capture-{kind}.jsonl', 0
self.capture.touch()
listen = free_port()
stop = net_capture.start_background(listen, f'127.0.0.1:{port}', self.capture)
self.address = f'127.0.0.1:{listen}'
try:
self.server = server
for name, fn in scenarios:
self.scenario(f'{kind}: {name}', fn)
finally:
stop.set()
server.stop()
shutil.copy(server.log_path, self.out / server.log_path.name)
finally:
game.quit()
if game.log.exists():
shutil.copy(game.log, self.out / 'client.log')
if downloads.exists():
shutil.copytree(downloads, self.out / 'downloads')
return work
def plan(self, game, servers_dat, downloads):
sha1 = self.sha1
def required_disconnect():
write_servers(servers_dat, self.address, None)
conn = self.join(game, self.address, 'decline')
check(game.wait_widget('disconnect').get('ok'), 'the required prompt opened')
labels = game.labels()
check('Proceed' in labels and 'Disconnect' in labels, f'Proceed and Disconnect buttons: {labels}')
game('screenshot', self.out / 'prompt-required.png')
game('click', 'disconnect')
self.wait_statuses(conn, [])
screen = json.dumps(game('screen'))
check(REQUIRED_REASON in screen, 'the disconnected screen says "This server requires a custom resource pack"')
check(read_setting(servers_dat) is None, 'the setting stays Prompt')
check(not any(p == '/test-pack.zip' for p, _ in self.http.requests), 'nothing was downloaded')
def required_proceed():
conn = self.join(game, self.address, 'proceed')
check(game.wait_widget('proceed').get('ok'), 'the required prompt opened')
game('click', 'proceed')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, LOADED)
check(read_setting(servers_dat) is True, 'the setting became Enabled (acceptTextures 1)')
pack_id = self.packs['required']['resource-pack-id']
check((downloads / pack_id / sha1).exists(), f'downloads/{pack_id}/{sha1} is cached')
log = json.loads((downloads / 'log.json').read_text().splitlines()[-1])
check(log.get('id') == pack_id and log.get('hash') == sha1
and log.get('file', {}).get('name') == f'{pack_id}/{sha1}', f'log.json entry {log}')
path, headers = [r for r in self.http.requests if r[0] == '/test-pack.zip'][-1]
want = {'X-Minecraft-Username': PLAYER, 'X-Minecraft-Version': lab.VERSION,
'X-Minecraft-Version-ID': lab.VERSION, 'X-Minecraft-Pack-Format': '97.1',
'User-Agent': f'Minecraft Java/{lab.VERSION}'}
check(all(headers.get(k) == v for k, v in want.items()) and len(headers.get('X-Minecraft-UUID', '')) == 32,
f'download headers {headers}')
self.server.console(f'execute at {PLAYER} run fill ~-6 ~-1 ~-6 ~6 ~-1 ~6 minecraft:dirt')
game('look', 0, 90)
game('wait', 40)
shot = self.out / 'applied-blue-dirt.png'
game('screenshot', shot)
share = blue_share(shot)
check(share > 0.5, f'the ground is the pack\'s blue dirt ({share:.0%} of the samples)')
game('key', 'esc', 'tap')
game('wait', 5)
labels = game.labels()
check('Back to Game (server pack)' in labels, f'the pause menu uses the pack\'s lang: {labels}')
game('key', 'esc', 'tap')
self.leave(game)
labels = game.labels()
check('Join Server' in labels and 'Join Server (server pack)' not in labels,
f'after leaving, the pack is gone: {labels}')
def required_enabled():
before = len(self.http.requests)
conn = self.join(game, self.address, 'enabled')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, LOADED)
check(len(self.http.requests) == before, 'no second download: the cached file is used')
game('key', 'esc', 'tap')
game('wait', 5)
check('Back to Game (server pack)' in game.labels(), 'the pack is applied without a prompt')
game('key', 'esc', 'tap')
self.leave(game)
def bad_sha1():
write_servers(servers_dat, self.address, True)
conn = self.join(game, self.address, 'bad-sha1')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, FAILED)
entries = [json.loads(line) for line in (downloads / 'log.json').read_text().splitlines()]
failed = [e for e in entries if e.get('hash') == '0' * 40]
check(failed and failed[-1].get('error') == 'download_failed' and 'file' not in failed[-1],
f'log.json records the failure: {failed[-1:]}')
self.leave(game)
def optional_no():
write_servers(servers_dat, self.address, None)
conn = self.join(game, self.address, 'optional-no')
check(game.wait_widget('no').get('ok'), 'the optional prompt opened')
labels = game.labels()
check('Yes' in labels and 'No' in labels, f'Yes and No buttons: {labels}')
game('screenshot', self.out / 'prompt-optional.png')
game('click', 'no')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, ['declined'])
check(read_setting(servers_dat) is False, 'the setting became Disabled (acceptTextures 0)')
self.leave(game)
def optional_disabled():
conn = self.join(game, self.address, 'optional-disabled')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, ['declined'])
self.leave(game)
def optional_yes():
write_servers(servers_dat, self.address, None)
conn = self.join(game, self.address, 'optional-yes')
check(game.wait_widget('yes').get('ok'), 'the optional prompt opened')
game('click', 'yes')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, LOADED)
check(any(r[0] == '/optional-pack.zip' for r in self.http.requests), 'downloaded without a hash')
self.leave(game)
def dead_url():
write_servers(servers_dat, self.address, True)
conn = self.join(game, self.address, 'dead-url')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, FAILED)
self.leave(game)
return [
('required', [('Disconnect at the prompt', required_disconnect), ('Proceed', required_proceed),
('Enabled, cached', required_enabled)]),
('bad-sha1', [('wrong SHA-1', bad_sha1)]),
('optional', [('No at the prompt', optional_no), ('Disabled', optional_disabled),
('Yes at the prompt, no hash', optional_yes)]),
('dead-url', [('dead URL', dead_url)]),
]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin', default=str(lab.cargo_target() / 'fast'), help='horizon-client and horizon-ctl')
parser.add_argument('--horizon-server', help='a horizon-client binary to run as the dedicated server')
parser.add_argument('--out', default=str(lab.LOCAL / 'server-pack-e2e'))
args = parser.parse_args()
out = Path(args.out) / ('horizon' if args.horizon_server else 'vanilla')
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
run = Run(args, out)
work = run.run()
print(f'\nserver: {"horizon" if args.horizon_server else "vanilla 26.3"}; evidence in {out}')
for name, result, detail in run.results:
print(f' {result:4} {name}' + (f': {detail}' if detail else ''))
shutil.rmtree(work, ignore_errors=True)
if any(r != 'pass' for _, r, _ in run.results):
sys.exit(1)
if __name__ == '__main__':
main()