Server dialogs: the dialog screen, its buttons and their actions

A server's show_dialog (configuration and play) opens vanilla's
DialogScreen instead of being dropped: the header with the title and the
warning button, the message bodies in a scrolling column, the action
buttons packed into columns (MultiButtonDialogScreen) or side by side in
the footer (notice, confirmation). A button runs its click event: a
custom action goes back as custom_click_action, a command runs (in play;
in configuration vanilla only warns), show_dialog opens another dialog,
copy_to_clipboard copies. after_action closes the screen, leaves it, or
opens the WaitingForResponseScreen. The warning button opens the
"custom screen" warning, whose Disconnect leaves the server. clear_dialog
closes it, and so do the level loading screen and a disconnect. The world
and HUD blur behind it as behind any in-game screen.

Inputs come next; here they are not drawn and keep their initial values.

tools/server_e2e.py is a new harness: a vanilla 26.3 dedicated server and
one Horizon client. Its dialog check shows a dialog with /dialog show,
clicks a command button (the server's trigger), a custom action (the
server's debug log shows its payload) and a wait_for_response one, and
clears a dialog with /dialog clear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-25 03:29:45 +01:00
parent 1d90d72a64
commit a7f8650c6b
9 changed files with 1021 additions and 2 deletions
+304
View File
@@ -0,0 +1,304 @@
//! `DialogScreen` and its kinds (`SimpleDialogScreen`, `MultiButtonDialogScreen`):
//! where a server dialog's title, body and buttons go in a
//! `HeaderAndFooterLayout` (a 33 high header, the body in a `ScrollableLayout`,
//! the footer), and the `WaitingForResponseScreen` an answer can leave open.
use crate::{
dialog::{Body, Dialog, Kind},
font::Font,
text::Text,
};
/// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`.
const BAR: f32 = 33.0;
/// `DialogScreen.WARNING_BUTTON_SPRITES`: normal, disabled, highlighted.
pub const WARNING_SPRITES: [&str; 3] = [
"gui/sprites/dialog/warning_button",
"gui/sprites/dialog/warning_button_disabled",
"gui/sprites/dialog/warning_button_highlighted",
];
/// One drawn piece; `y` is from the top of the body (before it scrolls) for
/// the body's parts, from the top of the screen for the footer's.
#[derive(Clone, Debug, PartialEq)]
pub enum Part {
/// A line of text and where it starts.
Line(Text, f32, f32),
/// A button of `Dialog::buttons`.
Button { index: usize, rect: [f32; 4] },
}
#[derive(Clone, Debug)]
pub struct Layout {
/// The title and where it is drawn.
pub title: (f32, f32),
pub warning: [f32; 4],
/// The body's visible area (`ScrollableLayout`'s container): x, y, w, h.
pub area: [f32; 4],
/// The body's full height: more than the area's scrolls.
pub content: f32,
pub body: Vec<Part>,
pub footer: Vec<Part>,
}
/// A laid-out element of a `LinearLayout` before it is placed.
struct Element {
w: f32,
h: f32,
parts: Vec<Part>,
}
impl Element {
/// Its parts moved to `(x, y)`.
fn at(self, x: f32, y: f32) -> impl Iterator<Item = Part> {
self.parts.into_iter().map(move |p| match p {
Part::Line(t, px, py) => Part::Line(t, px + x, py + y),
Part::Button { index, rect } => Part::Button {
index,
rect: shift(rect, x, y),
},
})
}
}
fn shift([x, y, w, h]: [f32; 4], dx: f32, dy: f32) -> [f32; 4] {
[x + dx, y + dy, w, h]
}
/// `FrameLayout.alignInDimension` at 0.5: the offset that centres `inner`.
fn centre(outer: f32, inner: f32) -> f32 {
((outer - inner) * 0.5).trunc()
}
/// `FocusableTextWidget` with the body's settings: `width` wide, the text
/// wrapped to `width - 8` and centred, 4 of padding all round.
fn message(font: &Font, contents: &Text, width: f32) -> Element {
let lines = font.split_lines(contents, width - 8.0);
let mid = (width / 2.0).trunc();
let parts = lines
.into_iter()
.enumerate()
.map(|(i, (line, _))| {
let x = mid - (font.width_text(&line) / 2.0).trunc();
Part::Line(line, x, 4.0 + 9.0 * i as f32)
})
.collect::<Vec<_>>();
Element {
w: width,
h: 9.0 * parts.len() as f32 + 8.0,
parts,
}
}
/// `DialogScreen.packControlsIntoColumns`: full rows in a grid 2 apart, what
/// is left in a centred row under them.
fn columns(widths: &[f32], columns: usize, first: usize) -> Element {
let columns = columns.max(1);
let full = widths.len() / columns * columns;
let row_width = |ws: &[f32]| ws.iter().sum::<f32>() + 2.0 * (ws.len().max(1) - 1) as f32;
let mut col = vec![0.0f32; columns];
for (i, w) in widths[..full].iter().enumerate() {
col[i % columns] = col[i % columns].max(*w);
}
let last = &widths[full..];
if !last.is_empty() {
// GridLayout spreads a cell over every column it spans (Divisor).
let spread = row_width(last) - 2.0 * (columns - 1) as f32;
let (each, extra) = ((spread / columns as f32).floor(), spread % columns as f32);
for (c, w) in col.iter_mut().enumerate() {
*w = w.max(each + f32::from(u8::from((c as f32) < extra)));
}
}
let x_of = |c: usize| col[..c].iter().sum::<f32>() + 2.0 * c as f32;
let mut parts = Vec::new();
for (i, w) in widths[..full].iter().enumerate() {
let (r, c) = (i / columns, i % columns);
parts.push(Part::Button {
index: first + i,
rect: [x_of(c) + centre(col[c], *w), 22.0 * r as f32, *w, 20.0],
});
}
let width = x_of(columns - 1) + col[columns - 1];
if !last.is_empty() {
let y = 22.0 * (full / columns) as f32;
let mut x = centre(width, row_width(last));
for (i, w) in last.iter().enumerate() {
parts.push(Part::Button {
index: first + full + i,
rect: [x, y, *w, 20.0],
});
x += w + 2.0;
}
}
let rows = full / columns + usize::from(!last.is_empty());
Element {
w: width,
h: (22.0 * rows as f32 - 2.0).max(0.0),
parts,
}
}
impl Layout {
/// `DialogScreen.init` and `repositionElements` on a `w` by `h` screen.
pub fn new(dialog: &Dialog, font: &Font, (w, h): (f32, f32)) -> Self {
// The header: the title, 10 right of it the warning button, both
// centred together.
let tw = font.width_text(&dialog.title);
let (hx, hy) = (centre(w, tw + 30.0), centre(BAR, 20.0));
let title = (hx, hy + centre(20.0, 9.0));
let warning = [hx + tw + 10.0, hy, 20.0, 20.0];
let mut elements: Vec<Element> = dialog
.body
.iter()
.filter_map(|b| match b {
Body::Message { contents, width } => Some(message(font, contents, *width as f32)),
Body::Item { .. } => None,
})
.collect();
let buttons = dialog.buttons();
let (listed, footer_buttons, footer_h) = match &dialog.kind {
Kind::MultiAction {
actions,
exit,
columns: n,
} => {
let widths: Vec<f32> = actions.iter().map(|b| b.width as f32).collect();
elements.push(columns(&widths, *n as usize, 0));
// ButtonListDialogScreen: the exit button in the footer, else a 5 high one.
let footer = exit.as_ref().map(|_| actions.len()).into_iter().collect();
(
actions.len(),
footer,
if exit.is_some() { BAR } else { 5.0 },
)
}
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => {
let footer = exit.as_ref().map(|_| 0).into_iter().collect();
(0, footer, if exit.is_some() { BAR } else { 5.0 })
}
// SimpleDialogScreen: the buttons side by side, 8 apart.
Kind::Notice(_) | Kind::Confirmation { .. } => {
(0, (0..buttons.len()).collect::<Vec<_>>(), BAR)
}
};
debug_assert!(listed + footer_buttons.len() <= buttons.len());
// The body: a column 10 apart, each element centred in it.
let body_w = elements.iter().map(|e| e.w).fold(0.0, f32::max);
let content = elements.iter().map(|e| e.h).sum::<f32>()
+ 10.0 * elements.len().saturating_sub(1) as f32;
// ScrollableLayout: 10 each side for the scrollbar (ReserveStrategy.BOTH),
// no higher than what the header and footer leave.
let area_w = body_w + 20.0;
let area_h = content.min(h - BAR - footer_h).max(0.0);
let area_y = (BAR + 30.0).min(h - footer_h - area_h);
let area_x = centre(w, area_w);
let mut body = Vec::new();
let mut y = 0.0;
for e in elements {
let (x, eh) = (area_x + 10.0 + centre(body_w, e.w), e.h);
body.extend(e.at(x, y));
y += eh + 10.0;
}
let widths: Vec<f32> = footer_buttons
.iter()
.map(|&i| buttons[i].width as f32)
.collect();
let row = widths.iter().sum::<f32>() + 8.0 * widths.len().saturating_sub(1) as f32;
let (mut x, fy) = (centre(w, row), h - footer_h + centre(footer_h, 20.0));
let mut footer = Vec::new();
for (&i, bw) in footer_buttons.iter().zip(&widths) {
footer.push(Part::Button {
index: i,
rect: [x, fy, *bw, 20.0],
});
x += bw + 8.0;
}
Self {
title,
warning: Self::in_bounds(warning, w, h),
area: [area_x, area_y, area_w, area_h],
content,
body,
footer,
}
}
/// `makeSureWarningButtonIsInBounds`.
fn in_bounds(r: [f32; 4], w: f32, h: f32) -> [f32; 4] {
if r[0] < 0.0 || r[1] < 0.0 || r[0] > w - 20.0 || r[1] > h - 20.0 {
[(w - 40.0).max(0.0), 5.0f32.min(h), 20.0, 20.0]
} else {
r
}
}
/// Every part where it is drawn with the body scrolled by `scroll`, and
/// whether it is in the body (clipped to its area).
pub fn placed(&self, scroll: f32) -> impl Iterator<Item = (Part, bool)> + '_ {
let dy = self.area[1] - scroll;
let body = self.body.iter().map(move |p| {
let p = match p.clone() {
Part::Line(t, x, y) => Part::Line(t, x, y + dy),
Part::Button { index, rect } => Part::Button {
index,
rect: shift(rect, 0.0, dy),
},
};
(p, true)
});
body.chain(self.footer.iter().map(|p| (p.clone(), false)))
}
}
/// `WaitingForResponseScreen`: its Back button's label after `ticks`, and
/// whether it shows and works (it shows after a second, works after five).
pub fn waiting_button(ticks: u32) -> (Text, bool, bool) {
let seconds = (ticks / 20).min(5);
let label = match seconds {
0 => Text::literal(""),
5 => Text::translate("gui.back", &[]),
s => Text::translate(
"gui.waitingForResponse.button.inactive",
&[Text::literal((5 - s).to_string())],
),
};
(label, seconds >= 1, seconds == 5)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grids_pack_full_rows_and_centre_the_rest() {
// AuthMe's two buttons: one row, 2 apart.
let two = columns(&[150.0, 150.0], 2, 0);
assert_eq!((two.w, two.h), (302.0, 20.0));
// Three in two columns: the third alone, centred under them.
let three = columns(&[150.0, 150.0, 150.0], 2, 0);
assert_eq!((three.w, three.h), (302.0, 42.0));
assert_eq!(
three.parts[2],
Part::Button {
index: 2,
rect: [76.0, 22.0, 150.0, 20.0]
}
);
// One in two columns spreads over both.
let one = columns(&[100.0], 2, 0);
assert_eq!(one.w, 100.0);
}
#[test]
fn the_waiting_screens_button_counts_down() {
assert!(!waiting_button(0).1);
assert_eq!(
waiting_button(20).0,
Text::translate(
"gui.waitingForResponse.button.inactive",
&[Text::literal("4")]
)
);
assert_eq!(
waiting_button(100),
(Text::translate("gui.back", &[]), true, true)
);
}
}
+23 -2
View File
@@ -36,6 +36,7 @@ mod debug_keys;
mod decorated_pot;
mod dedicated;
mod deflect;
mod dialogs;
mod dispense_fixture;
mod dispenser;
mod dragon;
@@ -1130,6 +1131,7 @@ struct Game<'a> {
pending_pack_reload: bool,
/// A server's resource packs (game/server_packs.rs).
server_packs: server_packs::ServerPackState,
dialogs: dialogs::DialogState,
world_renderer_ready: bool,
collision: &'a BlockCollisionRegistry<'a>,
motion: &'a MotionResources,
@@ -4777,11 +4779,14 @@ impl Game<'_> {
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
// 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() {
let mut batch = if (self.server_packs.prompt.is_some() || self.dialog_open())
&& self.player.is_none()
{
HudBatch::new(size)
} else {
self.hud_layers(size)
};
self.draw_dialog(&mut batch);
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.
@@ -10246,6 +10251,7 @@ impl Game<'_> {
|| (self.title.is_none()
&& self.player.is_some()
&& (self.screen.blurs_background(self.pause_menu)
|| self.dialog_open()
|| (self.screen == Screen::Win && self.win_screen_pauses())));
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
@@ -10936,7 +10942,9 @@ impl ApplicationHandler for Game<'_> {
}) * wheel_sensitivity
};
let d = scaled(raw_y) as f32;
if let Some(title) = &mut self.title
if self.dialog_open() {
self.dialog_scroll(d);
} else if let Some(title) = &mut self.title
&& self.screen != Screen::Win
{
let size = self
@@ -11003,6 +11011,11 @@ impl ApplicationHandler for Game<'_> {
self.pack_prompt_click()?;
}
}
WindowEvent::MouseInput { state, button, .. } if self.dialog_open() => {
if state == ElementState::Pressed && button == MouseButton::Left {
self.dialog_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 {
@@ -11210,6 +11223,13 @@ impl ApplicationHandler for Game<'_> {
self.answer_pack_prompt(false)?;
}
}
WindowEvent::KeyboardInput { event, .. } if self.dialog_open() => {
if event.state == ElementState::Pressed
&& let PhysicalKey::Code(key) = event.physical_key
{
self.dialog_key(key)?
}
}
WindowEvent::KeyboardInput { event, .. }
if self.screen == Screen::Chat && self.title.is_none() =>
{
@@ -11684,6 +11704,7 @@ impl<'a> Game<'a> {
world_loader: None,
pending_pack_reload: false,
server_packs: Default::default(),
dialogs: Default::default(),
world_renderer_ready: false,
collision: res.collision(),
motion: res.motion(),
+4
View File
@@ -390,6 +390,9 @@ impl Game<'_> {
Ok(())
}
pub(super) fn screen_label(&self) -> &'static str {
if self.dialog_open() {
return "dialog";
}
if self.title.is_some() {
return "title";
}
@@ -483,6 +486,7 @@ impl Game<'_> {
})
});
json!({
"dialog": self.dialog_status(),
"screen": self.screen_label(),
"menu": self.title.as_ref().map(|_| self.title_value()),
"world": (self.title.is_none()).then(|| match &self.integrated {
@@ -231,6 +231,13 @@ impl Game<'_> {
"pad" => Ok(Some(self.pad_command(&words)?)),
"key" => {
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
// A server's dialog takes the keys, in configuration too.
if self.dialog_open() {
if arg(2)? != "up" {
self.dialog_key(key)?;
}
return ok();
}
self.require_world()?;
// The sign editor takes raw presses (Enter, arrows, Backspace, Escape).
if self.sign_edit.is_some() {
+450
View File
@@ -0,0 +1,450 @@
//! A server's dialogs bound to the game (`ClientCommonPacketListenerImpl.
//! showDialog` and `clearDialog`, `DialogScreen`, its `WarningScreen` and the
//! `WaitingForResponseScreen`): the screen over whatever is open (the
//! connecting screen in configuration), its inputs, and the actions its
//! buttons send back.
use super::Game;
use horizon_client::{
Result,
confirm_screen::Confirm,
dialog::{AfterAction, Click, Dialog, InputValue},
dialog_screen::{Layout, Part, WARNING_SPRITES, waiting_button},
hud::{HudBatch, rgba},
text::Text,
ui,
};
use horizon_world::nbt::Tag;
use std::time::Instant;
use winit::keyboard::KeyCode;
/// An open `DialogScreen`.
struct Open {
dialog: Dialog,
values: Vec<InputValue>,
scroll: ui::Scroll,
}
/// The dialog screens a server can open.
#[derive(Default)]
pub(super) struct DialogState {
open: Option<Open>,
/// `WaitingForResponseScreen`, since when.
waiting: Option<Instant>,
/// `DialogScreen.WarningScreen`, over the dialog.
warning: bool,
}
fn warning_texts() -> (Text, Text, [Text; 2]) {
let t = |key: &str| Text::translate(key, &[]);
(
t("menu.custom_screen_info.title"),
t("menu.custom_screen_info.contents"),
[t("menu.disconnect"), t("gui.back")],
)
}
impl Game<'_> {
/// Whether a dialog screen takes the input.
pub(super) fn dialog_open(&self) -> bool {
let d = &self.dialogs;
d.open.is_some() || d.waiting.is_some() || d.warning
}
/// `showDialog`: the dialog replaces an open one (and a waiting screen);
/// under the warning screen, it is what Back returns to.
pub(super) fn show_dialog(&mut self, tag: &Tag) {
let Some(dialog) = Dialog::parse(tag) else {
log::warn!("Horizon: failed to show dialog for data {tag:?}");
return;
};
let values = dialog.inputs.iter().map(|i| i.control.initial()).collect();
self.dialogs.open = Some(Open {
dialog,
values,
scroll: ui::Scroll::default(),
});
self.dialogs.waiting = None;
self.capture(false);
}
/// `clearDialog`: the dialog closes (under the warning screen, Back then
/// returns to what was open before it).
pub(super) fn clear_dialog(&mut self) {
if self.dialogs.open.take().is_some() && !self.dialog_open() {
self.dialog_closed();
}
}
/// Every dialog screen goes (a disconnect, or the level loading screen).
pub(super) fn close_dialogs(&mut self) {
self.dialogs = DialogState::default();
}
fn dialog_closed(&mut self) {
if self.player.is_some() && self.screen == super::Screen::Playing && self.title.is_none() {
self.capture(true);
}
}
/// `DialogScreen.runAction`: the click event, then the screen the dialog's
/// `after_action` leaves.
fn run_dialog_action(&mut self, click: Option<Click>, after: AfterAction) -> Result<()> {
match after {
AfterAction::None => {}
AfterAction::Close => self.dialogs.open = None,
AfterAction::WaitForResponse => {
self.dialogs.open = None;
self.dialogs.waiting = Some(Instant::now());
}
}
match click {
Some(Click::Custom { id, payload }) => {
if let Some(r) = &self.remote {
r.session.send_custom_click(&id, payload);
}
}
Some(Click::RunCommand(command)) => {
// In configuration there is nothing to run it (vanilla warns).
if self.player.is_some() {
let command = command.strip_prefix('/').unwrap_or(&command);
self.send_chat(&format!("/{command}"));
} else {
log::warn!(
"Horizon: commands are not supported in configuration, trying to run '{command}'"
);
}
}
Some(Click::ShowDialog(dialog)) => self.show_dialog_ref(&dialog),
Some(Click::CopyToClipboard(value)) => {
use horizon_client::clipboard::Clipboard;
self.clipboard.set(&value);
}
Some(other) => log::info!("Horizon: dialog action {other:?} is not supported yet"),
None => {}
}
if !self.dialog_open() {
self.dialog_closed();
}
Ok(())
}
/// A `show_dialog` click event's dialog: a registry id or the dialog itself.
fn show_dialog_ref(&mut self, dialog: &Tag) {
match dialog {
Tag::String(id) => {
let id = id.to_string_lossy();
let name = if id.contains(':') {
id.clone()
} else {
format!("minecraft:{id}")
};
let found = self.remote.as_ref().and_then(|r| {
let entries = r.registries.registries.get("minecraft:dialog")?;
entries.iter().find(|(n, _)| *n == name)?.1.clone()
});
match found {
Some(tag) => self.show_dialog(&tag),
None => log::warn!("Horizon: unknown dialog {id}"),
}
}
tag => self.show_dialog(tag),
}
}
/// `ClientboundShowDialogPacket` in play: a registry entry or the dialog.
pub(super) fn show_play_dialog(
&mut self,
dialog: &horizon_protocol::packets::play::DialogHolder,
) {
use horizon_protocol::packets::play::DialogHolder;
match dialog {
DialogHolder::Direct(tag) => self.show_dialog(tag),
DialogHolder::Registry(id) => {
let tag = self
.remote
.as_ref()
.and_then(|r| r.registries.data("minecraft:dialog", *id).cloned());
match tag {
Some(tag) => self.show_dialog(&tag),
None => log::warn!("Horizon: unknown dialog {id}"),
}
}
}
}
fn dialog_layout(&self) -> Option<Layout> {
let open = self.dialogs.open.as_ref()?;
Some(Layout::new(
&open.dialog,
&self.gui.atlas.font,
self.gui_size(),
))
}
pub(super) fn draw_dialog(&mut self, batch: &mut HudBatch) {
if !self.dialog_open() {
return;
}
let (w, h) = (batch.width, batch.height);
let cursor = self.cursor;
let atlas = &self.gui.atlas;
if self.player.is_none() {
// In place of the connecting screen, on its background.
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
}
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
if self.dialogs.warning {
let (title, message, [disconnect, back]) = warning_texts();
Confirm::new(&atlas.font, (w, h), &title, &message).draw(
batch,
atlas,
cursor,
[&disconnect, &back],
);
return;
}
if let Some(since) = self.dialogs.waiting {
// HeaderAndFooterLayout(33, 0) centred: the title, the button 33 below.
let ticks = (since.elapsed().as_millis() / 50) as u32;
let (label, visible, active) = waiting_button(ticks);
let title = Text::translate("gui.waitingForResponse.title", &[]);
let top = ((h - 53.0) / 2.0).trunc();
let tw = atlas.font.width_text(&title);
batch.text_styled(
atlas,
&title,
((w - tw) / 2.0).trunc(),
top + 12.0,
u32::MAX,
true,
);
if visible {
let (bx, by) = (((w - 200.0) / 2.0).trunc(), top + 33.0);
let hover = ui::hovered(cursor, bx, by, 200.0, 20.0);
ui::button(batch, atlas, bx, by, 200.0, 20.0, &label, active, hover);
}
return;
}
let Some(layout) = self.dialog_layout() else {
return;
};
let Some(open) = self.dialogs.open.as_mut() else {
return;
};
let atlas = &self.gui.atlas;
let [ax, ay, aw, ah] = layout.area;
open.scroll.clamp(ay, ay + ah, layout.content);
batch.text_styled(
atlas,
&open.dialog.title,
layout.title.0,
layout.title.1,
u32::MAX,
true,
);
let [wx, wy, ww, wh] = layout.warning;
let warn_hover = ui::hovered(cursor, wx, wy, ww, wh);
horizon_client::widgets::record("warning", layout.warning, true);
batch.sprite_scaled(
atlas,
WARNING_SPRITES[if warn_hover { 2 } else { 0 }],
wx,
wy,
ww,
wh,
u32::MAX,
);
let buttons = open.dialog.buttons();
let in_area = |y: f32| y >= ay && y < ay + ah;
let mut tooltip = None;
let mut start = None;
for (part, clipped) in layout.placed(open.scroll.amount) {
if clipped && start.is_none() {
start = Some(batch.vertices.len());
} else if !clipped && let Some(s) = start.take() {
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
}
match part {
Part::Line(text, x, y) => {
batch.text_styled(atlas, &text, x, y, u32::MAX, true);
}
Part::Button { index, rect } => {
let [x, y, bw, bh] = rect;
let hover =
(!clipped || in_area(cursor.1)) && ui::hovered(cursor, x, y, bw, bh);
let b = buttons[index];
ui::button(batch, atlas, x, y, bw, bh, &b.label, true, hover);
if hover && let Some(t) = &b.tooltip {
tooltip = Some(t.clone());
}
}
}
}
if let Some(s) = start {
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
}
if layout.content > ah {
ui::scrollbar(
batch,
atlas,
ax + aw - 6.0,
ay,
ay + ah,
layout.content,
open.scroll.amount,
);
}
if warn_hover {
tooltip = Some(Text::translate("menu.custom_screen_info.tooltip", &[]));
}
if let Some(t) = tooltip {
let lines: Vec<Text> = atlas
.font
.split_lines(&t, 170.0)
.into_iter()
.map(|l| l.0)
.collect();
ui::tooltip(batch, atlas, &lines, cursor);
}
}
/// A left click on a dialog screen.
pub(super) fn dialog_click(&mut self) -> Result<()> {
let cursor = self.cursor;
if self.dialogs.warning {
let (title, message, _) = warning_texts();
let answer = Confirm::new(&self.gui.atlas.font, self.gui_size(), &title, &message)
.answer_at(cursor);
match answer {
Some(true) => {
self.audio.play_button_click();
let reason = Text::translate("menu.custom_screen_info.disconnect", &[]);
return self.leave_server(Some(reason.plain()));
}
Some(false) => {
self.audio.play_button_click();
self.dialogs.warning = false;
if !self.dialog_open() {
self.dialog_closed();
}
}
None => {}
}
return Ok(());
}
if let Some(since) = self.dialogs.waiting {
let (w, h) = self.gui_size();
let active = waiting_button((since.elapsed().as_millis() / 50) as u32).2;
let (bx, by) = (
((w - 200.0) / 2.0).trunc(),
((h - 53.0) / 2.0).trunc() + 33.0,
);
if active && ui::hovered(cursor, bx, by, 200.0, 20.0) {
self.audio.play_button_click();
self.dialogs.waiting = None;
self.dialog_closed();
}
return Ok(());
}
let Some(layout) = self.dialog_layout() else {
return Ok(());
};
let [wx, wy, ww, wh] = layout.warning;
if ui::hovered(cursor, wx, wy, ww, wh) {
self.audio.play_button_click();
self.dialogs.warning = true;
return Ok(());
}
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
let [_, ay, _, ah] = layout.area;
let mut action = None;
for (part, clipped) in layout.placed(open.scroll.amount) {
if clipped && !(cursor.1 >= ay && cursor.1 < ay + ah) {
continue;
}
match part {
Part::Button {
index,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
action = Some(index);
}
_ => {}
}
}
let Some(index) = action else {
return Ok(());
};
self.audio.play_button_click();
let d = &open.dialog;
let click = d.buttons()[index]
.action
.as_ref()
.and_then(|a| a.click(&d.inputs, &open.values));
let after = d.after_action;
self.run_dialog_action(click, after)
}
/// The mouse wheel over a dialog: its body scrolls 10 a step.
pub(super) fn dialog_scroll(&mut self, delta: f32) {
let Some(layout) = self.dialog_layout() else {
return;
};
if let Some(open) = self.dialogs.open.as_mut() {
let [_, ay, _, ah] = layout.area;
open.scroll.wheel(delta, 10.0, ay, ay + ah, layout.content);
}
}
/// A key pressed on a dialog screen: Escape closes what allows it.
pub(super) fn dialog_key(&mut self, key: KeyCode) -> Result<()> {
let escape = key == KeyCode::Escape;
if self.dialogs.warning {
if escape {
self.dialogs.warning = false;
if !self.dialog_open() {
self.dialog_closed();
}
}
return Ok(());
}
if let Some(since) = self.dialogs.waiting {
// shouldCloseOnEsc: once Back works.
if escape && waiting_button((since.elapsed().as_millis() / 50) as u32).2 {
self.dialogs.waiting = None;
self.dialog_closed();
}
return Ok(());
}
let Some(open) = self.dialogs.open.as_ref() else {
return Ok(());
};
if escape {
if !open.dialog.can_close_with_escape {
return Ok(());
}
// onClose: the cancel action, and the screen closes.
let d = &open.dialog;
let click = d.on_cancel().and_then(|a| a.click(&d.inputs, &open.values));
return self.run_dialog_action(click, AfterAction::Close);
}
Ok(())
}
/// What `state` reports: the open dialog and its values, or the waiting
/// and warning screens.
pub(super) fn dialog_status(&self) -> serde_json::Value {
let d = &self.dialogs;
let screen = if d.warning {
Some("warning")
} else if d.waiting.is_some() {
Some("waiting_for_response")
} else {
None
};
let open = d.open.as_ref().map(|open| open.dialog.json(&open.values));
serde_json::json!({ "open": open, "screen": screen })
}
}
+8
View File
@@ -468,6 +468,7 @@ impl Game<'_> {
r.session.disconnect();
}
self.server_packs_disconnect();
self.close_dialogs();
// Single player's server thread saves the world before the title shows.
let single_player = match self.integrated.take() {
Some(server) => {
@@ -829,6 +830,8 @@ impl Game<'_> {
} => {
self.set_registries(registries);
self.extras_joined();
// handleLogin: the level loading screen replaces any dialog.
self.close_dialogs();
if let Some(r) = self.remote.as_mut() {
r.joined = true;
r.profile = uuid;
@@ -844,6 +847,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::ShowDialog(dialog) => self.show_dialog(&dialog),
Event::ClearDialog => self.clear_dialog(),
Event::DecodeError(e) => {
if let Some(r) = self.remote.as_mut() {
r.decode_errors += 1;
@@ -2676,6 +2681,9 @@ impl Game<'_> {
C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)),
C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)),
C::SetTitlesAnimation(p) => self.titles.set_times(p.fade_in, p.stay, p.fade_out),
// ClientCommonPacketListenerImpl.handleShowDialog / handleClearDialog.
C::ShowDialog(p) => self.show_play_dialog(&p.dialog),
C::ClearDialog(_) => self.clear_dialog(),
C::ClearTitles(p) => {
self.titles.clear();
if p.value {
+1
View File
@@ -54,6 +54,7 @@ pub mod debug_chart;
pub mod debug_keys;
pub mod debug_overlay;
pub mod dialog;
pub mod dialog_screen;
pub mod dynamic_light;
pub mod effects;
pub mod enchant;
+30
View File
@@ -48,6 +48,10 @@ pub enum Event {
PackPush(cfg::ResourcePackPush),
/// ClientboundResourcePackPopPacket: one pack, or every pack.
PackPop(Option<u128>),
/// `show_dialog` in configuration: the dialog itself.
ShowDialog(horizon_world::nbt::Tag),
/// `clear_dialog` in configuration.
ClearDialog,
/// 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).
@@ -189,6 +193,25 @@ impl Session {
w.shutdown();
}
}
/// ServerboundCustomClickActionPacket (a dialog's answer), in whichever
/// phase the connection is.
pub fn send_custom_click(&self, id: &str, payload: Option<horizon_world::nbt::Tag>) {
let click = cfg::CustomClickAction {
id: id.to_owned(),
payload,
};
let mut writer = self.writer.lock().unwrap();
let body = if self.configuring.load(Ordering::Relaxed) {
cfg::Serverbound::CustomClickAction(click).encode()
} else {
play::Serverbound::CustomClickAction(click).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();
@@ -524,6 +547,13 @@ fn configure(
cfg::Clientbound::ResourcePackPop(p) => {
let _ = send.send(Event::PackPop(p.id));
}
// The game shows it; the answer goes back from there.
cfg::Clientbound::ShowDialog(d) => {
let _ = send.send(Event::ShowDialog(d.dialog));
}
cfg::Clientbound::ClearDialog(_) => {
let _ = send.send(Event::ClearDialog);
}
cfg::Clientbound::CookieRequest(q) => {
reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse {
key: q.key,
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Horizon's client on a vanilla 26.3 dedicated server, end to end.
A vanilla server (the pinned server jar, offline mode, a flat world) and one Horizon game joined to it,
driven by horizon-ctl. The server's console does what a server or its plugins do; the checks read what
the game shows and what reaches the server (its console and, for custom click actions, its debug log).
python3 tools/server_e2e.py --bin-dir target/fast # every check
python3 tools/server_e2e.py --bin-dir target/fast --check dialog
Checks:
- dialog: `/dialog show` with a multi-action dialog (a message, three buttons): the game shows it,
a command runs on the server (`trigger`), a custom action reaches it with its
payload (the server's "Received custom click action" line), `wait_for_response` leaves the
waiting screen, and `/dialog clear` closes a dialog (servers used to see nothing: the game
dropped the packets).
The game runs with fresh HORIZON_HOME, launcher and XDG folders and without audio. Screenshots and both
logs go to --out.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
import test_rust_parity as base # noqa: E402
from agent_control_e2e import Failed # noqa: E402
from lan_e2e import Game # noqa: E402
from test_dedicated_server_parity import Server # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
PLAYER = 'Steve'
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
'level-type': 'minecraft\\:flat',
'generate-structures': 'false',
'spawn-protection': '0',
'view-distance': '3',
'simulation-distance': '3',
'pause-when-empty-seconds': '-1',
}
# MinecraftServer.handleCustomClickAction logs at debug level: the console shows that logger's debug lines.
LOG4J = """<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders><Console name="out" target="SYSTEM_OUT"><PatternLayout pattern="[%level] %msg%n"/></Console></Appenders>
<Loggers>
<Logger name="net.minecraft.server.MinecraftServer" level="debug"/>
<Root level="info"><AppenderRef ref="out"/></Root>
</Loggers>
</Configuration>
"""
def snbt(value):
"""A JSON value as SNBT (strings quoted, booleans as bytes)."""
if isinstance(value, bool):
return '1b' if value else '0b'
if isinstance(value, str):
return json.dumps(value)
if isinstance(value, list):
return '[' + ','.join(snbt(v) for v in value) + ']'
if isinstance(value, dict):
return '{' + ','.join(f'{k}:{snbt(v)}' for k, v in value.items()) + '}'
return str(value)
def check_dialog(server, game, out):
server.console('scoreboard objectives add answer trigger')
server.console(f'scoreboard players enable {PLAYER} answer')
dialog = {
'type': 'minecraft:multi_action',
'title': {'text': 'Sign in', 'color': 'gold'},
'body': {'type': 'minecraft:plain_message', 'contents': 'Pick a number.'},
'actions': [
{'label': 'Send', 'action': {'type': 'minecraft:run_command', 'command': 'trigger answer set 41'}},
{'label': 'Submit', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:e2e',
'additions': {'tag': 'x'}}},
{'label': 'Wait', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:wait'}},
],
'after_action': 'none',
'pause': False, # a pausing dialog must close after an action
}
shown = {}
server.console(f'dialog show {PLAYER} {snbt(dialog)}')
game.raw('wait-for', 'screen', 'dialog', '--timeout', 30)
state = game('state')
shown['shown'] = state['dialog']['open']
assert shown['shown']['title'] == 'Sign in', shown
assert shown['shown']['buttons'] == ['Send', 'Submit', 'Wait'], shown
game.shot(out, 'dialog')
game.raw('click', 'send')
time.sleep(1)
server.console(f'scoreboard players get {PLAYER} answer')
server.wait_for(rf'{PLAYER} has 41 \[answer\]', timeout=30)
shown['trigger'] = 41
# A custom action and its additions.
game.raw('click', 'submit')
server.wait_for(r'Received custom click action horizon:e2e with payload', timeout=30)
line = next(l for l in server.lines if 'horizon:e2e' in l)
shown['custom'] = line.split('payload ', 1)[1]
assert shown['custom'] == '{tag:"x"}', shown
# after_action none: still open. Then clear it.
assert game('state')['dialog']['open'], 'the dialog closed after an action with after_action none'
server.console(f'dialog clear {PLAYER}')
game.raw('wait-for', 'screen', 'playing', '--timeout', 30)
# wait_for_response: the waiting screen until the server answers (here, never).
server.console(f'dialog show {PLAYER} {snbt(dict(dialog, after_action="wait_for_response"))}')
game.raw('wait-for', 'screen', 'dialog', '--timeout', 30)
game.raw('click', 'wait')
server.wait_for(r'Received custom click action horizon:wait', timeout=30)
shown['waiting'] = game('state')['dialog']['screen']
game.shot(out, 'waiting')
assert shown['waiting'] == 'waiting_for_response', shown
# Its Back works after 5 s, and so does Escape (clear_dialog leaves it open, as in vanilla).
time.sleep(5.5)
game.raw('key', 'esc', 'tap')
game.raw('wait-for', 'screen', 'playing', '--timeout', 10)
return shown
CHECKS = {'dialog': check_dialog}
def run(bins, out, checks):
lock, jars, libraries = base.verify_artifacts()
work = Path(tempfile.mkdtemp(prefix='hz-server-e2e-'))
port = lab.free_port()
directory = work / 'server'
directory.mkdir()
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
(directory / 'eula.txt').write_text('eula=true\n')
(work / 'log4j2.xml').write_text(LOG4J)
classpath = os.pathsep.join(map(str, [jars['server'], *libraries]))
server = Server(['java', '-Xmx2g', f'-Dlog4j.configurationFile={work / "log4j2.xml"}', '-cp', classpath,
'net.minecraft.server.Main', 'nogui'], directory, 'vanilla')
game = Game('client', bins / 'horizon-ctl', lab.RESOURCES.resolve())
for key in ('XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'HORIZON_LAUNCHER_HOME'):
game.d.env[key] = str(game.work / key.lower())
game.d.env['HORIZON_LAUNCHER_NO_SELF_UPDATE'] = '1'
results = {}
try:
server.wait_for(r'Done \(')
server.console('gamerule spawn_mobs false')
game('launch', wait=False, offscreen=sys.platform == 'darwin')
game.raw('connect', f'127.0.0.1:{port}', PLAYER)
game.raw('wait-for', 'loaded', '--timeout', 300)
server.wait_for(rf'{PLAYER} joined the game')
server.console(f'op {PLAYER}')
game.wait(20)
for name in checks:
try:
results[name] = {'pass': True, 'detail': CHECKS[name](server, game, out)}
except (Failed, AssertionError, StopIteration, KeyError) as e:
results[name] = {'pass': False, 'detail': repr(e)}
print(f'[server] {name}: {"PASS" if results[name]["pass"] else "FAIL"} {results[name]["detail"]}')
finally:
(out / 'client.log').write_text(game.close())
server.stop()
shutil.copy(server.log_path, out / 'server.log')
shutil.rmtree(game.work, ignore_errors=True)
shutil.rmtree(work, ignore_errors=True)
return results
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
parser.add_argument('--check', action='append', choices=list(CHECKS), help='run only these checks (repeatable)')
parser.add_argument('--out', default=str(ROOT / '.local/server-e2e'), help='screenshots and logs go here')
args = parser.parse_args()
if args.bin_dir:
bins = Path(args.bin_dir).resolve()
else:
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
cwd=ROOT, check=True)
bins = ROOT / 'target/fast'
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
results = run(bins, out, args.check or list(CHECKS))
print(json.dumps(results, indent=1))
sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1)
if __name__ == '__main__':
main()