diff --git a/crates/horizon-client/src/dialog_screen.rs b/crates/horizon-client/src/dialog_screen.rs index c9434cfc2..ad4f47a17 100644 --- a/crates/horizon-client/src/dialog_screen.rs +++ b/crates/horizon-client/src/dialog_screen.rs @@ -1,15 +1,17 @@ //! `DialogScreen` and its kinds (`SimpleDialogScreen`, `MultiButtonDialogScreen`): -//! where a server dialog's title, body and buttons go in a +//! where a server dialog's title, body, inputs 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}, + dialog::{Body, Control, Dialog, Kind}, font::Font, text::Text, }; /// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`. const BAR: f32 = 33.0; +/// `Checkbox.getBoxSize`. +pub const BOX: f32 = 17.0; /// `DialogScreen.WARNING_BUTTON_SPRITES`: normal, disabled, highlighted. pub const WARNING_SPRITES: [&str; 3] = [ "gui/sprites/dialog/warning_button", @@ -23,6 +25,10 @@ pub const WARNING_SPRITES: [&str; 3] = [ pub enum Part { /// A line of text and where it starts. Line(Text, f32, f32), + /// A text input's box. + Field { input: usize, rect: [f32; 4] }, + /// A boolean input: the box, its label right of it. + Check { input: usize, rect: [f32; 4] }, /// A button of `Dialog::buttons`. Button { index: usize, rect: [f32; 4] }, } @@ -51,6 +57,14 @@ impl Element { fn at(self, x: f32, y: f32) -> impl Iterator { self.parts.into_iter().map(move |p| match p { Part::Line(t, px, py) => Part::Line(t, px + x, py + y), + Part::Field { input, rect } => Part::Field { + input, + rect: shift(rect, x, y), + }, + Part::Check { input, rect } => Part::Check { + input, + rect: shift(rect, x, y), + }, Part::Button { index, rect } => Part::Button { index, rect: shift(rect, x, y), @@ -86,6 +100,55 @@ fn message(font: &Font, contents: &Text, width: f32) -> Element { } } +/// `InputControlHandlers`: the control for input `i`, if Horizon has it. +fn input(font: &Font, i: usize, control: &Control) -> Option { + Some(match control { + Control::Text { + width, + label, + label_visible, + .. + } => { + let w = *width as f32; + if !label_visible { + return Some(Element { + w, + h: 20.0, + parts: vec![Part::Field { + input: i, + rect: [0.0, 0.0, w, 20.0], + }], + }); + } + // CommonLayouts.labeledElement: the label, 4 below it the box, + // both on the left. + Element { + w: w.max(font.width_text(label)), + h: 9.0 + 4.0 + 20.0, + parts: vec![ + Part::Line(label.clone(), 0.0, 0.0), + Part::Field { + input: i, + rect: [0.0, 13.0, w, 20.0], + }, + ], + } + } + Control::Boolean { label, .. } => { + let w = BOX + 4.0 + font.width_text(label); + Element { + w, + h: BOX, + parts: vec![Part::Check { + input: i, + rect: [0.0, 0.0, w, BOX], + }], + } + } + Control::SingleOption { .. } | Control::NumberRange { .. } => return None, + }) +} + /// `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 { @@ -152,6 +215,13 @@ impl Layout { Body::Item { .. } => None, }) .collect(); + elements.extend( + dialog + .inputs + .iter() + .enumerate() + .filter_map(|(i, input_)| input(font, i, &input_.control)), + ); let buttons = dialog.buttons(); let (listed, footer_buttons, footer_h) = match &dialog.kind { Kind::MultiAction { @@ -236,6 +306,14 @@ impl Layout { 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::Field { input, rect } => Part::Field { + input, + rect: shift(rect, 0.0, dy), + }, + Part::Check { input, rect } => Part::Check { + input, + rect: shift(rect, 0.0, dy), + }, Part::Button { index, rect } => Part::Button { index, rect: shift(rect, 0.0, dy), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 283bd2cad..583b95313 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11224,10 +11224,11 @@ impl ApplicationHandler for Game<'_> { } } WindowEvent::KeyboardInput { event, .. } if self.dialog_open() => { + let shortcut = self.edit_shortcut(&event); if event.state == ElementState::Pressed && let PhysicalKey::Code(key) = event.physical_key { - self.dialog_key(key)? + self.dialog_key(key, shortcut, event.text.as_deref())? } } WindowEvent::KeyboardInput { event, .. } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index adba0bc05..598009e6a 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -234,7 +234,7 @@ impl Game<'_> { // A server's dialog takes the keys, in configuration too. if self.dialog_open() { if arg(2)? != "up" { - self.dialog_key(key)?; + self.dialog_key(key, None, None)?; } return ok(); } @@ -527,13 +527,17 @@ impl Game<'_> { )) } "type" => { - self.require_world()?; let text = line .trim_start() .strip_prefix("type") .unwrap_or("") .strip_prefix(' ') .unwrap_or(""); + // A server's dialog, in configuration too. + if self.dialog_type(text) { + return ok(); + } + self.require_world()?; if self.book.is_some() { self.book_type(text); return ok(); diff --git a/crates/horizon-client/src/game/dialogs.rs b/crates/horizon-client/src/game/dialogs.rs index 28a7a7609..4928b0aa8 100644 --- a/crates/horizon-client/src/game/dialogs.rs +++ b/crates/horizon-client/src/game/dialogs.rs @@ -6,9 +6,10 @@ use super::Game; use horizon_client::{ Result, + clipboard::EditShortcut, confirm_screen::Confirm, - dialog::{AfterAction, Click, Dialog, InputValue}, - dialog_screen::{Layout, Part, WARNING_SPRITES, waiting_button}, + dialog::{AfterAction, Click, Control, Dialog, InputValue}, + dialog_screen::{BOX, Layout, Part, WARNING_SPRITES, waiting_button}, hud::{HudBatch, rgba}, text::Text, ui, @@ -21,6 +22,9 @@ use winit::keyboard::KeyCode; struct Open { dialog: Dialog, values: Vec, + /// The box of each text input. + fields: Vec>, + focus: Option, scroll: ui::Scroll, } @@ -58,9 +62,30 @@ impl Game<'_> { return; }; let values = dialog.inputs.iter().map(|i| i.control.initial()).collect(); + let fields = dialog + .inputs + .iter() + .map(|i| match &i.control { + Control::Text { + width, + initial, + max_length, + .. + } => { + let mut edit = ui::EditBox::new(0.0, 0.0, *width as f32, 20.0); + edit.max_length = (*max_length).max(1) as usize; + edit.set_value(initial); + edit.focused = false; + Some(edit) + } + _ => None, + }) + .collect(); self.dialogs.open = Some(Open { dialog, values, + fields, + focus: None, scroll: ui::Scroll::default(), }); self.dialogs.waiting = None; @@ -86,6 +111,15 @@ impl Game<'_> { } } + /// The input values as the controls hold them now. + fn dialog_values(open: &mut Open) { + for (value, field) in open.values.iter_mut().zip(&open.fields) { + if let Some(f) = field { + *value = InputValue::Text(f.value.clone()); + } + } + } + /// `DialogScreen.runAction`: the click event, then the screen the dialog's /// `after_action` leaves. fn run_dialog_action(&mut self, click: Option, after: AfterAction) -> Result<()> { @@ -268,6 +302,37 @@ impl Game<'_> { Part::Line(text, x, y) => { batch.text_styled(atlas, &text, x, y, u32::MAX, true); } + Part::Field { input, rect } => { + if let Some(Some(edit)) = open.fields.get_mut(input) { + [edit.x, edit.y, edit.width, edit.height] = rect; + edit.focused = open.focus == Some(input); + edit.draw(batch, atlas, None); + } + } + Part::Check { input, rect } => { + let [x, y, cw, ch] = rect; + let hover = in_area(cursor.1) && ui::hovered(cursor, x, y, cw, ch); + let on = open.values.get(input) == Some(&InputValue::Bool(true)); + let sprite = match (on, hover) { + (true, true) => "gui/sprites/widget/checkbox_selected_highlighted", + (true, false) => "gui/sprites/widget/checkbox_selected", + (false, true) => "gui/sprites/widget/checkbox_highlighted", + (false, false) => "gui/sprites/widget/checkbox", + }; + let Control::Boolean { label, .. } = &open.dialog.inputs[input].control else { + continue; + }; + horizon_client::widgets::record(&label.plain(), rect, true); + batch.sprite_scaled(atlas, sprite, x, y, BOX, BOX, u32::MAX); + batch.text_styled( + atlas, + label, + x + BOX + 4.0, + y + 4.0, + rgba(224, 224, 224, 255), + true, + ); + } Part::Button { index, rect } => { let [x, y, bw, bh] = rect; let hover = @@ -360,24 +425,51 @@ impl Game<'_> { }; let [_, ay, _, ah] = layout.area; let mut action = None; + open.focus = None; for (part, clipped) in layout.placed(open.scroll.amount) { if clipped && !(cursor.1 >= ay && cursor.1 < ay + ah) { continue; } match part { + Part::Field { + input, + rect: [x, y, w, h], + } if ui::hovered(cursor, x, y, w, h) => { + open.focus = Some(input); + if let Some(Some(edit)) = open.fields.get_mut(input) { + edit.focused = true; + edit.click(&self.gui.atlas, cursor.0, false, false); + } + } + Part::Check { + input, + rect: [x, y, w, h], + } if ui::hovered(cursor, x, y, w, h) => { + if let Some(InputValue::Bool(b)) = open.values.get_mut(input) { + *b = !*b; + } + action = Some(None); + } Part::Button { index, rect: [x, y, w, h], } if ui::hovered(cursor, x, y, w, h) => { - action = Some(index); + action = Some(Some(index)); } _ => {} } } - let Some(index) = action else { + let Some(action) = action else { return Ok(()); }; self.audio.play_button_click(); + let Some(index) = action else { + return Ok(()); + }; + let Some(open) = self.dialogs.open.as_mut() else { + return Ok(()); + }; + Self::dialog_values(open); let d = &open.dialog; let click = d.buttons()[index] .action @@ -398,8 +490,15 @@ impl Game<'_> { } } - /// A key pressed on a dialog screen: Escape closes what allows it. - pub(super) fn dialog_key(&mut self, key: KeyCode) -> Result<()> { + /// A key pressed on a dialog screen: Escape closes what allows it, Tab + /// moves between the text inputs, the rest goes to the focused one + /// (`shortcut`: the press as an edit shortcut; `text`: what it types). + pub(super) fn dialog_key( + &mut self, + key: KeyCode, + shortcut: Option, + text: Option<&str>, + ) -> Result<()> { let escape = key == KeyCode::Escape; if self.dialogs.warning { if escape { @@ -418,7 +517,9 @@ impl Game<'_> { } return Ok(()); } - let Some(open) = self.dialogs.open.as_ref() else { + let ctrl = self.modifiers.control_key() || self.modifiers.super_key(); + let shift = self.modifiers.shift_key(); + let Some(open) = self.dialogs.open.as_mut() else { return Ok(()); }; if escape { @@ -426,13 +527,65 @@ impl Game<'_> { return Ok(()); } // onClose: the cancel action, and the screen closes. + Self::dialog_values(open); 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); } + if key == KeyCode::Tab { + let texts: Vec = (0..open.fields.len()) + .filter(|&i| open.fields[i].is_some()) + .collect(); + if !texts.is_empty() { + let at = open.focus.and_then(|f| texts.iter().position(|&i| i == f)); + let next = match at { + None if shift => texts.len() - 1, + None => 0, + Some(p) if shift => (p + texts.len() - 1) % texts.len(), + Some(p) => (p + 1) % texts.len(), + }; + open.focus = Some(texts[next]); + } + return Ok(()); + } + let Some(Some(edit)) = open.focus.and_then(|f| open.fields.get_mut(f)) else { + return Ok(()); + }; + if let Some(shortcut) = shortcut { + edit.shortcut(shortcut, &mut self.clipboard); + return Ok(()); + } + if edit.key(key, ctrl, shift) { + return Ok(()); + } + let typed: String = text + .unwrap_or_default() + .chars() + .filter(|c| !c.is_control()) + .collect(); + if !typed.is_empty() { + edit.insert_text(&typed); + } Ok(()) } + /// `type TEXT` with a dialog open: into the focused text input, or the + /// first one. + pub(super) fn dialog_type(&mut self, text: &str) -> bool { + let Some(open) = self.dialogs.open.as_mut() else { + return false; + }; + let focus = open + .focus + .or_else(|| open.fields.iter().position(Option::is_some)); + let Some(Some(edit)) = focus.and_then(|f| open.fields.get_mut(f)) else { + return false; + }; + open.focus = focus; + edit.insert_text(text); + true + } + /// What `state` reports: the open dialog and its values, or the waiting /// and warning screens. pub(super) fn dialog_status(&self) -> serde_json::Value { @@ -444,7 +597,15 @@ impl Game<'_> { } else { None }; - let open = d.open.as_ref().map(|open| open.dialog.json(&open.values)); + let open = d.open.as_ref().map(|open| { + let mut values = open.values.clone(); + for (value, field) in values.iter_mut().zip(&open.fields) { + if let Some(f) = field { + *value = InputValue::Text(f.value.clone()); + } + } + open.dialog.json(&values) + }); serde_json::json!({ "open": open, "screen": screen }) } } diff --git a/tools/server_e2e.py b/tools/server_e2e.py index 397e03549..590072249 100644 --- a/tools/server_e2e.py +++ b/tools/server_e2e.py @@ -9,8 +9,9 @@ the game shows and what reaches the server (its console and, for custom click ac 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 +- dialog: `/dialog show` with a multi-action dialog (a message, a text and a boolean input, three + buttons): the game shows it with its inputs and buttons, the text typed and the box ticked + go back in a command template (`trigger`, run by the server) and in a custom action's 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). @@ -79,8 +80,13 @@ def check_dialog(server, game, out): 'type': 'minecraft:multi_action', 'title': {'text': 'Sign in', 'color': 'gold'}, 'body': {'type': 'minecraft:plain_message', 'contents': 'Pick a number.'}, + 'inputs': [ + {'type': 'minecraft:text', 'key': 'number', 'label': 'Number'}, + {'type': 'minecraft:boolean', 'key': 'agree', 'label': 'Agree', 'on_true': '1', 'on_false': '0'}, + ], 'actions': [ - {'label': 'Send', 'action': {'type': 'minecraft:run_command', 'command': 'trigger answer set 41'}}, + {'label': 'Send', 'action': {'type': 'minecraft:dynamic/run_command', + 'template': 'trigger answer set $(number)$(agree)'}}, {'label': 'Submit', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:e2e', 'additions': {'tag': 'x'}}}, {'label': 'Wait', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:wait'}}, @@ -94,19 +100,24 @@ def check_dialog(server, game, out): state = game('state') shown['shown'] = state['dialog']['open'] assert shown['shown']['title'] == 'Sign in', shown + assert [i['key'] for i in shown['shown']['inputs']] == ['number', 'agree'], shown assert shown['shown']['buttons'] == ['Send', 'Submit', 'Wait'], shown game.shot(out, 'dialog') + # The text, the box, then the command the template makes of them. + game.raw('type', '4') + game.raw('click', 'agree') 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. + # A custom action: its additions and every input's tag. 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 + for part in ('agree:1b', 'number:"4"', 'tag:"x"'): + assert part in shown['custom'], 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}')