Merge pull request #241 from ludovic111/feat/controllers2-focus

Controllers: focus navigation in menus, on-screen keyboard, menu navigation option
This commit is contained in:
Ludovic Marie
2026-10-15 05:25:30 +02:00
committed by GitHub
23 changed files with 2055 additions and 154 deletions
+11
View File
@@ -274,6 +274,17 @@ impl Game<'_> {
}
}
/// Clicks on the power, confirm and cancel buttons.
/// The effect, upgrade, confirm and cancel buttons a controller can
/// focus (GUI origin relative).
pub(super) fn beacon_targets(&self) -> Vec<[f32; 4]> {
let (ux, uy) = upgrade_button();
buttons()
.into_iter()
.map(|(_, x, y, _)| (x, y))
.chain([(ux, uy), (164.0, 107.0), (190.0, 107.0)])
.map(|(x, y)| [x + SHIFT, y, 22.0, 22.0])
.collect()
}
pub(super) fn beacon_click(&mut self, local: (f32, f32)) -> bool {
let l = (local.0 - SHIFT, local.1);
let levels = self.beacon_levels();
+7 -2
View File
@@ -139,6 +139,11 @@ impl Game<'_> {
PhysicalKey::Code(k) => Some(k),
_ => None,
};
self.book_input(key, event.text.as_deref());
}
/// A key and the text it typed in the open book (the keyboard, or a
/// controller's on-screen keyboard).
pub(super) fn book_input(&mut self, key: Option<KeyCode>, text: Option<&str>) {
match self.book.as_mut() {
Some(BookScreen::View { .. }) => match key {
Some(KeyCode::Escape) => self.close_book(),
@@ -167,7 +172,7 @@ impl Game<'_> {
}
}
_ => {
if let Some(typed) = event.text.as_ref() {
if let Some(typed) = text {
self.text_selection.take(BOOK_TITLE, title);
for c in typed.chars().filter(|c| !c.is_control()) {
if title.chars().count() < 15 {
@@ -193,7 +198,7 @@ impl Game<'_> {
self.type_into_page("\n")
}
_ => {
if let Some(typed) = event.text.as_ref().map(|t| t.to_string()) {
if let Some(typed) = text {
let typed: String = typed.chars().filter(|c| !c.is_control()).collect();
if !typed.is_empty() {
self.take_page_selection();
+20 -7
View File
@@ -333,13 +333,26 @@ impl Game<'_> {
o.port.shortcut(shortcut, &mut self.clipboard);
return;
}
if !o.port.key(key, ctrl, false)
&& !ctrl
&& let Some(text) = &event.text
{
let digits: String = text.chars().filter(char::is_ascii_digit).collect();
if !digits.is_empty() {
o.port.insert_text(&digits);
if !o.port.key(key, ctrl, false) && !ctrl {
self.world_options_text(event.text.as_deref());
}
}
/// Digits typed into the port field (the keyboard, or a controller's
/// on-screen keyboard), and its backspace.
pub(super) fn world_options_text(&mut self, text: Option<&str>) {
let Some(o) = self.world_options.as_mut().filter(|o| o.port.focused) else {
return;
};
match text {
Some(text) => {
let digits: String = text.chars().filter(char::is_ascii_digit).collect();
if !digits.is_empty() {
o.port.insert_text(&digits);
}
}
None => {
o.port
.key(winit::keyboard::KeyCode::Backspace, false, false);
}
}
}
+18
View File
@@ -128,6 +128,24 @@ impl Game<'_> {
}
false
}
/// The pattern buttons a controller can focus (GUI origin relative).
pub(super) fn loom_targets(&self) -> Vec<[f32; 4]> {
let Some(loom) = self.station.as_ref().map(|s| &s.loom).filter(|l| l.display) else {
return Vec::new();
};
(0..16)
.filter(|i| (i / 4 + loom.start_row) * 4 + i % 4 < loom.patterns.len())
.map(|i| {
let (row, column) = (i / 4, i % 4);
[
60.0 + column as f32 * BUTTON,
13.0 + row as f32 * BUTTON,
BUTTON,
BUTTON,
]
})
.collect()
}
/// `LoomScreen.mouseDragged` on the scroller.
pub(super) fn loom_drag(&mut self) {
let Some(size) = self
+9 -12
View File
@@ -255,7 +255,7 @@ impl Game<'_> {
if down && !self.pad_focused() {
return Ok(());
}
let playing = self.title.is_none() && self.screen == Screen::Playing;
let playing = !self.pad_in_menu();
if down && playing && !self.captured && self.focused {
// Like a click into the window: take the pointer.
self.capture(true);
@@ -315,6 +315,11 @@ impl Game<'_> {
/// B and Start: what Escape does where the pad is.
pub(super) fn pad_back(&mut self) -> Result<()> {
// The options open over the title screen too: they come first, as
// for the keyboard's Escape.
if self.screen == Screen::Options {
return self.options_key(KeyCode::Escape, None);
}
if let Some(title) = self.title.as_mut() {
title.escape();
return Ok(());
@@ -340,11 +345,7 @@ impl Game<'_> {
/// The left stick as the move vector, while playing.
pub(super) fn pad_move(&self) -> Option<[f32; 2]> {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| !self.pad_focused()
{
if !settings.enabled || self.pad_in_menu() || !self.pad_focused() {
return None;
}
gamepad::move_vector(self.pad.state.left, settings.move_deadzone)
@@ -353,12 +354,7 @@ impl Game<'_> {
/// The right stick turns the view, once per frame (`Entity.turn`).
pub(super) fn pad_look(&mut self, seconds: f32) {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| self.player.is_none()
|| !self.pad_focused()
{
if !settings.enabled || self.pad_in_menu() || self.player.is_none() || !self.pad_focused() {
return;
}
// A long frame (a hitch) must not spin the view.
@@ -478,6 +474,7 @@ impl Game<'_> {
"reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis,
})),
"in_use": self.pad.in_use,
"menu": self.pad_menu_status(),
"held": held,
"left": s.left,
"right": s.right,
+713 -79
View File
@@ -1,17 +1,29 @@
//! A controller in menus, screens and inventories (Horizon's own;
//! docs/controllers.md): a virtual cursor the left stick moves and the
//! D-pad steps between slots and buttons, with A, X and the stick feeding
//! the screens the same pointer events a mouse sends. Every screen keeps
//! its mouse behaviour (drags, sliders, scrollbars) with no pad code of its
//! own.
//! docs/controllers.md). Two ways to drive them, picked in the controller
//! options:
//!
//! - **Focus** (console-style): a highlight steps between the widgets, list
//! rows, fields and slots each screen registers (`widgets::target_as`)
//! with vanilla's arrow-key navigation; A presses the focused one, the
//! bumpers switch tabs, left/right move a focused slider, A on a text field
//! opens the on-screen keyboard (`osk`).
//! - **Pointer**: a virtual cursor the left stick moves and the D-pad steps
//! between slots and buttons.
//!
//! Both feed the screens the same pointer events a mouse sends (the pointer
//! sits on the focused widget, hidden), so every screen keeps its mouse
//! behaviour (drags, sliders, scrollbars, hover highlights) with no pad code
//! of its own. A screen with nothing registered falls back to the pointer,
//! and a right stick click swaps modes for the open screen.
use super::{Game, Screen};
use horizon_client::{
Result,
creative::Creative,
gamepad::{self, Button},
gamepad::{self, Button, MenuNav, Rect},
hud::{HudBatch, rgba},
options_ui::{Event, Page},
widgets,
osk::{self, Keyboard},
widgets::{self, Kind, Target},
};
use std::time::Instant;
use winit::{
@@ -19,7 +31,7 @@ use winit::{
dpi::PhysicalPosition,
event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent},
event_loop::ActiveEventLoop,
keyboard::KeyCode,
keyboard::{KeyCode, NamedKey},
};
/// D-pad auto-repeat: the first step at once, the next after a pause.
@@ -27,6 +39,23 @@ const REPEAT_DELAY: f32 = 0.35;
const REPEAT_EVERY: f32 = 0.09;
/// Lines per second the right stick scrolls at full tilt.
const SCROLL_SPEED: f32 = 12.0;
/// How far the stick must lean to step focus.
const STICK_STEP: f32 = 0.55;
/// Scrolls a step may try to reveal the next row of a list.
const SCROLL_TRIES: u8 = 4;
/// A focus step that ran off the visible part of a list: the list was
/// scrolled and the step runs again once a new frame is drawn. When the
/// targets didn't move (nothing scrolled), the step takes vanilla's vague
/// pass instead.
#[derive(Clone)]
struct Pending {
button: Button,
from: Rect,
generation: u64,
tries: u8,
before: Vec<Rect>,
}
#[derive(Default)]
pub(super) struct MenuCursor {
@@ -45,12 +74,31 @@ pub(super) struct MenuCursor {
os_hidden: bool,
/// Polls since a menu opened (its widgets are drawn after one frame).
open_polls: u32,
/// Focus mode: the focused target as last drawn.
focus: Option<Target>,
/// The left stick's step direction last poll.
stick: Option<Button>,
/// A right stick click swapped modes for this screen.
swapped: bool,
pending: Option<Pending>,
/// The focused slider being nudged and where the pad put its handle.
nudge: Option<(Rect, f32)>,
/// Steps since the held direction went down (sliders speed up).
repeats: u32,
/// The on-screen keyboard, open over a text field.
pub(super) osk: Option<Keyboard>,
/// The keyboard was closed on this screen (it doesn't open by itself again).
osk_dismissed: bool,
}
impl Game<'_> {
/// A menu, a screen or the title is open: the pad drives a cursor.
/// A menu, a screen, the title, a sign or a book is open: the pad drives
/// it instead of the player.
pub(super) fn pad_in_menu(&self) -> bool {
self.title.is_some() || self.screen != Screen::Playing
self.title.is_some()
|| self.screen != Screen::Playing
|| self.sign_edit.is_some()
|| self.book.is_some()
}
fn gui_scale(&self) -> Option<HudBatch> {
@@ -59,46 +107,96 @@ impl Game<'_> {
.map(|r| HudBatch::new([r.config.width, r.config.height]))
}
/// Where focus can land: buttons drawn last frame, and the slots and
/// tabs of inventories (centres, GUI pixels).
fn pad_targets(&self) -> Vec<(f32, f32)> {
let mut targets: Vec<(f32, f32)> = widgets::last()
/// Focus mode is on for the open screen.
fn pad_focus_mode(&self) -> bool {
(self.settings.controller.menu_nav == MenuNav::Focus) != self.pad.menu.swapped
}
/// Where focus can land: buttons drawn last frame, every registered
/// target (sliders, fields, rows, Horizon-style widgets), and the slots
/// and tabs of inventories (GUI pixels), on screen.
fn pad_targets(&self) -> Vec<Target> {
let mut targets = self.pad_all_targets();
if let Some(batch) = self.gui_scale() {
let (w, h) = (batch.width + 0.5, batch.height + 0.5);
targets.retain(|t| {
let [x, y, tw, th] = t.rect;
x >= -0.5 && y >= -0.5 && x + tw <= w && y + th <= h
});
}
targets
}
fn pad_all_targets(&self) -> Vec<Target> {
let mut targets: Vec<Target> = widgets::last()
.iter()
.filter(|w| w.enabled)
.map(|w| (w.x + w.w / 2.0, w.y + w.h / 2.0))
.chain(
widgets::last_targets()
.into_iter()
.map(|[x, y, w, h]| (x + w / 2.0, y + h / 2.0)),
)
.map(|w| Target {
rect: [w.x, w.y, w.w, w.h],
kind: Kind::Button,
})
.collect();
if self.title.is_some() {
for t in widgets::last_targets() {
// A Horizon button is both a labelled button and a target.
if let Some(same) = targets.iter_mut().find(|o| o.rect == t.rect) {
same.kind = t.kind;
} else {
targets.push(t);
}
}
if self.title.is_some() || self.sign_edit.is_some() || self.book.is_some() {
return targets;
}
let Some(batch) = self.gui_scale() else {
return targets;
};
let slot = |x: f32, y: f32| Target {
rect: [x, y, 16.0, 16.0],
kind: Kind::Slot,
};
match self.screen {
Screen::Inventory => {
let (ox, oy) = self.inventory_origin(&batch);
targets.extend(self.slots().into_iter().map(|i| {
let (x, y) = self.slot_position(i);
(ox + x + 8.0, oy + y + 8.0)
slot(ox + x, oy + y)
}));
targets.extend(
self.station_targets()
.into_iter()
.map(|[x, y, w, h]| Target {
rect: [ox + x, oy + y, w, h],
kind: Kind::Button,
}),
);
targets.extend(self.recipe_book_targets());
}
Screen::Creative => {
let (ox, oy) = Self::creative_origin(&batch);
for r in 0..5 {
if self.creative_inventory_open() {
targets.extend(self.slots().into_iter().map(|i| {
let (x, y) = self.slot_position(i);
slot(ox + x, oy + y)
}));
} else {
for r in 0..5 {
for c in 0..9 {
targets.push(slot(
ox + 9.0 + c as f32 * 18.0,
oy + 18.0 + r as f32 * 18.0,
));
}
}
for c in 0..9 {
targets.push((ox + 17.0 + c as f32 * 18.0, oy + 26.0 + r as f32 * 18.0));
targets.push(slot(ox + 9.0 + c as f32 * 18.0, oy + 112.0));
}
}
for c in 0..9 {
targets.push((ox + 17.0 + c as f32 * 18.0, oy + 120.0));
}
for t in &self.creative_screen.tabs {
for (i, t) in self.creative_screen.tabs.iter().enumerate() {
let (x, y) = Creative::tab_position(t);
targets.push((ox + x + 13.0, oy + y + 16.0));
targets.push(Target {
rect: [ox + x, oy + y, 26.0, 32.0],
kind: Kind::Tab(i == self.creative_screen.selected),
});
}
}
_ => {}
@@ -107,25 +205,40 @@ impl Game<'_> {
}
/// Where focus starts when a menu opens: the held hotbar slot in an
/// inventory, else the first button.
fn pad_first_target(&self) -> Option<(f32, f32)> {
/// inventory, else the first button, else the first target that isn't
/// a tab.
fn pad_first_target(&self, targets: &[Target]) -> Option<Target> {
let batch = self.gui_scale()?;
match self.screen {
Screen::Inventory if self.title.is_none() => {
let (ox, oy) = self.inventory_origin(&batch);
let (x, y) = self.slot_position(self.selected);
return Some((ox + x + 8.0, oy + y + 8.0));
let at = |x: f32, y: f32| {
targets
.iter()
.find(|t| t.rect[0] == x && t.rect[1] == y)
.copied()
};
if self.title.is_none() {
match self.screen {
Screen::Inventory => {
let (ox, oy) = self.inventory_origin(&batch);
let (x, y) = self.slot_position(self.selected);
if let Some(t) = at(ox + x, oy + y) {
return Some(t);
}
}
Screen::Creative if !self.creative_inventory_open() => {
let (ox, oy) = Self::creative_origin(&batch);
if let Some(t) = at(ox + 9.0 + self.selected as f32 * 18.0, oy + 112.0) {
return Some(t);
}
}
_ => {}
}
Screen::Creative if self.title.is_none() => {
let (ox, oy) = Self::creative_origin(&batch);
return Some((ox + 17.0 + self.selected as f32 * 18.0, oy + 120.0));
}
_ => {}
}
widgets::last()
targets
.iter()
.find(|w| w.enabled)
.map(|w| (w.x + w.w / 2.0, w.y + w.h / 2.0))
.find(|t| t.kind == Kind::Button)
.or_else(|| targets.iter().find(|t| !matches!(t.kind, Kind::Tab(_))))
.or(targets.first())
.copied()
}
/// Send the window a pointer move to `at` (GUI pixels), as the mouse would.
@@ -178,6 +291,13 @@ impl Game<'_> {
);
}
/// A click (press and release) at a point, the pointer staying there.
fn pad_click_at(&mut self, event_loop: &ActiveEventLoop, at: (f32, f32), right: bool) {
self.pad_pointer_to(event_loop, at);
self.pad_pointer_button(event_loop, right, true);
self.pad_pointer_button(event_loop, right, false);
}
fn pad_wheel(&mut self, event_loop: &ActiveEventLoop, x: f32, y: f32) {
let Some(id) = self.window.as_ref().map(|w| w.id()) else {
return;
@@ -193,15 +313,26 @@ impl Game<'_> {
);
}
/// Put the cursor where the pad last left it, or on the first target.
/// Put the pointer where the pad last left it, or on the first target
/// (focus mode: focus lands there too).
fn pad_take_pointer(&mut self, event_loop: &ActiveEventLoop) {
if self.pad.menu.pos.is_some() {
return;
}
let at = self.pad_first_target().unwrap_or(self.cursor);
let targets = self.pad_targets();
let first = self.pad_first_target(&targets);
if self.pad_focus_mode() && first.is_some() {
self.pad.menu.focus = first;
}
let at = first.map_or(self.cursor, |t| t.center());
self.pad_pointer_to(event_loop, at);
}
/// Focus mode with something to focus on this screen.
fn pad_focusing(&self) -> bool {
self.pad_focus_mode() && self.pad.menu.focus.is_some()
}
/// A button in a menu.
pub(super) fn pad_menu_button(
&mut self,
@@ -232,8 +363,45 @@ impl Game<'_> {
}
return self.handle_option_events(vec![Event::Changed]);
}
// The on-screen keyboard takes every button while it is open.
if let Some(keyboard) = self.pad.menu.osk.as_mut() {
if let Some(out) = keyboard.button(button) {
self.pad_osk_output(out);
}
if matches!(
button,
Button::DPadUp | Button::DPadDown | Button::DPadLeft | Button::DPadRight
) {
self.pad.menu.repeat = Some((button, Instant::now(), false));
}
return Ok(());
}
match button {
Button::East | Button::Start => return self.pad_back(),
Button::RightStick => {
// Swap focus and pointer for this screen.
self.pad.menu.swapped = !self.pad.menu.swapped;
self.pad.menu.focus = None;
self.pad.menu.pending = None;
self.pad.menu.nudge = None;
self.pad.menu.pos = None;
self.pad_take_pointer(event_loop);
}
Button::South if self.pad_focusing() => {
let focus = self.pad.menu.focus.expect("focusing");
match focus.kind {
// A click would jump the handle; left/right move it.
Kind::Slider { .. } => {}
Kind::Field => {
self.pad_click_at(event_loop, focus.center(), false);
self.pad_open_keyboard();
}
_ => {
self.pad_pointer_to(event_loop, focus.center());
self.pad_pointer_button(event_loop, false, true);
}
}
}
Button::South | Button::West => {
self.pad_take_pointer(event_loop);
self.pad_pointer_button(event_loop, button == Button::West, true);
@@ -256,20 +424,56 @@ impl Game<'_> {
self.physical_keys.remove(&KeyCode::ShiftLeft);
}
}
// View / left stick in an inventory: throw one / the stack from
// the slot under focus (Q / Ctrl+Q).
Button::Select | Button::LeftStick
if matches!(self.screen, Screen::Inventory | Screen::Creative)
&& self.title.is_none() =>
{
self.pad_take_pointer(event_loop);
let all = button == Button::LeftStick;
let ctrl = self.physical_keys.contains(&KeyCode::ControlLeft);
if all {
self.physical_keys.insert(KeyCode::ControlLeft);
}
let result = self.key_pressed(KeyCode::KeyQ);
if all && !ctrl {
self.physical_keys.remove(&KeyCode::ControlLeft);
}
result?;
}
Button::DPadUp | Button::DPadDown | Button::DPadLeft | Button::DPadRight => {
self.pad_focus_step(event_loop, button);
self.pad.menu.repeats = 0;
self.pad_step(event_loop, button);
self.pad.menu.repeat = Some((button, Instant::now(), false));
}
// Bumpers switch creative tabs.
Button::LeftBumper | Button::RightBumper if self.screen == Screen::Creative => {
self.pad_creative_tab(event_loop, button == Button::RightBumper);
// Bumpers switch tabs (creative, Horizon's options sections, ...).
Button::LeftBumper | Button::RightBumper => {
self.pad_tab(event_loop, button == Button::RightBumper);
}
_ => {}
}
Ok(())
}
fn pad_focus_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
/// One D-pad (or stick) step in either mode.
fn pad_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
if let Some(keyboard) = self.pad.menu.osk.as_mut() {
keyboard.step(button);
return;
}
if self.pad_focus_mode() {
let targets = self.pad_targets();
if !targets.is_empty() {
self.pad_focus_step(event_loop, button, &targets);
return;
}
}
self.pad_pointer_step(event_loop, button);
}
/// Pointer mode: hop the cursor to the nearest target that way.
fn pad_pointer_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
if self.pad.menu.pos.is_none() {
self.pad_take_pointer(event_loop);
return;
@@ -287,9 +491,106 @@ impl Game<'_> {
return;
}
let from = self.cursor;
let targets = self.pad_targets();
if let Some(i) = gamepad::focus_step(from, button, &targets) {
self.pad_pointer_to(event_loop, targets[i]);
let centres: Vec<(f32, f32)> = self.pad_targets().iter().map(Target::center).collect();
if let Some(i) = gamepad::focus_step(from, button, &centres) {
self.pad_pointer_to(event_loop, centres[i]);
}
}
/// Focus mode: move the highlight (or a focused slider's value).
fn pad_focus_step(&mut self, event_loop: &ActiveEventLoop, button: Button, targets: &[Target]) {
let Some(focus) = self.pad.menu.focus else {
self.pad.menu.pos = None;
self.pad_take_pointer(event_loop);
return;
};
if let Kind::Slider { value, track } = focus.kind
&& matches!(button, Button::DPadLeft | Button::DPadRight)
{
let from = match self.pad.menu.nudge {
Some((rect, x)) if rect == focus.rect => x,
_ => gamepad::slider_x(track, value),
};
let step = gamepad::slider_step(self.pad.menu.repeats);
let x = (from
+ if button == Button::DPadLeft {
-step
} else {
step
})
.clamp(track[0], track[0] + track[1]);
self.pad.menu.nudge = Some((focus.rect, x));
self.pad_click_at(event_loop, (x, focus.center().1), false);
return;
}
let rects: Vec<Rect> = targets.iter().map(|t| t.rect).collect();
let vertical = matches!(button, Button::DPadUp | Button::DPadDown);
let step = if vertical {
gamepad::focus_step_strict(focus.rect, button, &rects)
} else {
gamepad::focus_step_rect(focus.rect, button, &rects)
};
match step {
Some(i) => self.pad_focus_on(event_loop, targets[i]),
None if vertical => {
// Off the visible rows of a list: scroll it and try again on
// the next frame.
let up = button == Button::DPadUp;
self.pad_wheel(event_loop, 0.0, if up { 1.0 } else { -1.0 });
self.pad.menu.pending = Some(Pending {
button,
from: focus.rect,
generation: widgets::generation(),
tries: 1,
before: rects,
});
}
None => {}
}
}
fn pad_focus_on(&mut self, event_loop: &ActiveEventLoop, target: Target) {
self.pad.menu.focus = Some(target);
self.pad.menu.pending = None;
self.pad.menu.nudge = None;
if !self.pad.menu.held[0] {
self.pad_pointer_to(event_loop, target.center());
}
}
/// A bumper: the next or previous tab, wrapping (creative keeps its own
/// order; other screens register their tabs).
fn pad_tab(&mut self, event_loop: &ActiveEventLoop, next: bool) {
if self.screen == Screen::Creative && self.title.is_none() {
self.pad_creative_tab(event_loop, next);
return;
}
let tabs: Vec<(Rect, bool)> = self
.pad_targets()
.into_iter()
.filter_map(|t| match t.kind {
Kind::Tab(selected) => Some((t.rect, selected)),
_ => None,
})
.collect();
let Some(i) = gamepad::tab_step(&tabs, next) else {
return;
};
let rect = tabs[i].0;
let back = self.pad.menu.pos;
self.pad_click_at(
event_loop,
(rect[0] + rect[2] / 2.0, rect[1] + rect[3] / 2.0),
false,
);
if self.pad_focus_mode() {
// The page changed under the old focus: start again on the new one.
self.pad.menu.focus = Some(Target {
rect,
kind: Kind::Tab(true),
});
} else if let Some(at) = back {
self.pad_pointer_to(event_loop, at);
}
}
@@ -311,17 +612,16 @@ impl Game<'_> {
let (ox, oy) = Self::creative_origin(&batch);
let (x, y) = Creative::tab_position(&self.creative_screen.tabs[tab]);
let back = self.pad.menu.pos;
self.pad_pointer_to(event_loop, (ox + x + 13.0, oy + y + 16.0));
self.pad_pointer_button(event_loop, false, true);
self.pad_pointer_button(event_loop, false, false);
self.pad_click_at(event_loop, (ox + x + 13.0, oy + y + 16.0), false);
if let Some(at) = back {
self.pad_pointer_to(event_loop, at);
}
}
/// Once per poll in a menu: the stick moves the cursor, the right stick
/// scrolls, a held D-pad repeats, and the OS pointer hides while the
/// pad's cursor shows.
/// Once per poll in a menu: the stick moves the cursor (pointer) or
/// steps focus, the right stick scrolls, a held direction repeats, focus
/// follows its widget from frame to frame, and the OS pointer hides
/// while the pad drives.
pub(super) fn pad_menu_frame(&mut self, event_loop: &ActiveEventLoop) {
let now = Instant::now();
let seconds = self
@@ -332,10 +632,17 @@ impl Game<'_> {
self.pad.menu.last_poll = Some(now);
let in_menu = self.pad_in_menu() && self.settings.controller.enabled;
if !in_menu {
self.pad.menu.open_polls = 0;
self.pad.menu.pos = None;
self.pad.menu.repeat = None;
self.pad.menu.held = [false; 2];
let menu = &mut self.pad.menu;
menu.open_polls = 0;
menu.pos = None;
menu.repeat = None;
menu.held = [false; 2];
menu.focus = None;
menu.swapped = false;
menu.pending = None;
menu.nudge = None;
menu.osk = None;
menu.osk_dismissed = false;
self.pad_show_os_pointer(true);
return;
}
@@ -345,29 +652,65 @@ impl Game<'_> {
&& ((at.0 - self.cursor.0).abs() > 0.5 || (at.1 - self.cursor.1).abs() > 0.5)
{
self.pad.menu.pos = None;
self.pad.menu.focus = None;
self.pad.in_use = false;
}
// Focus lands on the menu as it opens when the pad was in use.
if self.pad.in_use && self.pad.menu.pos.is_none() && self.pad.menu.open_polls == 3 {
self.pad_take_pointer(event_loop);
}
let focus_mode = self.pad_focus_mode();
let targets = if focus_mode {
self.pad_targets()
} else {
Vec::new()
};
let focusing = focus_mode && !targets.is_empty();
if focusing {
self.pad_follow_focus(event_loop, &targets);
}
let (move_deadzone, look_deadzone) = (
self.settings.controller.move_deadzone,
self.settings.controller.look_deadzone,
);
let state = self.pad.state;
let (dx, dy) = gamepad::cursor_delta(state.left, move_deadzone, seconds);
if dx != 0.0 || dy != 0.0 {
self.pad_take_pointer(event_loop);
let at = self.cursor;
self.pad_pointer_to(event_loop, (at.0 + dx, at.1 + dy));
self.pad.menu.moving = true;
} else if self.pad.menu.moving {
// Let go: settle onto a slot or button close by.
self.pad.menu.moving = false;
let targets = self.pad_targets();
if let Some(i) = gamepad::nearest(self.cursor, &targets, 10.0) {
self.pad_pointer_to(event_loop, targets[i]);
if focusing || self.pad.menu.osk.is_some() {
// The stick steps like the D-pad.
let dir =
gamepad::stick_direction(gamepad::radial(state.left, move_deadzone), STICK_STEP);
if dir != self.pad.menu.stick {
if let Some((b, ..)) = self.pad.menu.repeat
&& Some(b) == self.pad.menu.stick
{
self.pad.menu.repeat = None;
}
self.pad.menu.stick = dir;
if let Some(button) = dir {
if self.pad.menu.pos.is_none() && self.pad.menu.osk.is_none() {
self.pad_take_pointer(event_loop);
} else {
self.pad.menu.repeats = 0;
self.pad_step(event_loop, button);
}
self.pad.menu.repeat = Some((button, now, false));
}
}
} else {
self.pad.menu.stick = None;
let (dx, dy) = gamepad::cursor_delta(state.left, move_deadzone, seconds);
if dx != 0.0 || dy != 0.0 {
self.pad_take_pointer(event_loop);
let at = self.cursor;
self.pad_pointer_to(event_loop, (at.0 + dx, at.1 + dy));
self.pad.menu.moving = true;
} else if self.pad.menu.moving {
// Let go: settle onto a slot or button close by.
self.pad.menu.moving = false;
let centres: Vec<(f32, f32)> =
self.pad_targets().iter().map(Target::center).collect();
if let Some(i) = gamepad::nearest(self.cursor, &centres, 10.0) {
self.pad_pointer_to(event_loop, centres[i]);
}
}
}
let scroll = gamepad::radial(state.right, look_deadzone);
@@ -392,12 +735,88 @@ impl Game<'_> {
};
if now.duration_since(since).as_secs_f32() >= wait {
self.pad.menu.repeat = Some((button, now, true));
self.pad_focus_step(event_loop, button);
self.pad.menu.repeats = self.pad.menu.repeats.saturating_add(1);
self.pad_step(event_loop, button);
}
}
self.pad_auto_keyboard();
self.pad_show_os_pointer(self.pad.menu.pos.is_none());
}
/// Focus mode, each poll: find the focused widget in the new frame (a
/// list scrolled, a page changed), finish a step that scrolled a list,
/// and keep the hidden pointer on the focused widget.
fn pad_follow_focus(&mut self, event_loop: &ActiveEventLoop, targets: &[Target]) {
let rects: Vec<Rect> = targets.iter().map(|t| t.rect).collect();
let ready = self
.pad
.menu
.pending
.as_ref()
.map(|p| widgets::generation() > p.generation);
if ready == Some(true)
&& let Some(p) = self.pad.menu.pending.take()
{
// A step scrolled a list: carry on from where the focused row
// moved, or take the vague pass when nothing scrolled.
let step = match gamepad::scroll_shift(&p.before, &rects) {
Some(dy) => {
let mut from = p.from;
from[1] += dy;
self.pad.menu.focus = gamepad::refind(from, &rects, 2.0).map(|i| targets[i]);
gamepad::focus_step_strict(from, p.button, &rects).map(|i| (i, Some(from)))
}
None => gamepad::focus_step_vague(p.from, p.button, &rects).map(|i| (i, None)),
};
match step {
Some((i, _)) => self.pad_focus_on(event_loop, targets[i]),
None => {
if let Some(dy) = gamepad::scroll_shift(&p.before, &rects)
&& p.tries < SCROLL_TRIES
{
let up = p.button == Button::DPadUp;
self.pad_wheel(event_loop, 0.0, if up { 1.0 } else { -1.0 });
let mut from = p.from;
from[1] += dy;
self.pad.menu.pending = Some(Pending {
from,
generation: widgets::generation(),
tries: p.tries + 1,
before: rects.clone(),
..p
});
}
}
}
} else if ready.is_none() {
if let Some(focus) = self.pad.menu.focus {
self.pad.menu.focus = gamepad::refind(focus.rect, &rects, 12.0).map(|i| targets[i]);
if self.pad.menu.focus.is_none() && self.pad.menu.pos.is_some() {
// The widget went away (a page changed): start again.
self.pad.menu.focus = self.pad_first_target(targets);
}
} else if self.pad.menu.pos.is_some() {
// The pad drives but nothing is focused (switched from the pointer).
let centres: Vec<(f32, f32)> = targets.iter().map(Target::center).collect();
self.pad.menu.focus =
gamepad::nearest(self.cursor, &centres, f32::INFINITY).map(|i| targets[i]);
}
}
let Some(focus) = self.pad.menu.focus else {
return;
};
if self.pad.menu.pos.is_none() || self.pad.menu.held.iter().any(|h| *h) {
return;
}
let at = match self.pad.menu.nudge {
Some((rect, x)) if rect == focus.rect => (x, focus.center().1),
_ => focus.center(),
};
if (at.0 - self.cursor.0).abs() > 0.5 || (at.1 - self.cursor.1).abs() > 0.5 {
self.pad_pointer_to(event_loop, at);
}
}
fn pad_show_os_pointer(&mut self, show: bool) {
if self.pad.menu.os_hidden != show {
return;
@@ -408,12 +827,178 @@ impl Game<'_> {
}
}
/// The pad's cursor, over everything else.
/// `pad status`: the menu mode, the focused target and every target.
pub(super) fn pad_menu_status(&self) -> serde_json::Value {
let kind = |k: Kind| match k {
Kind::Button => "button",
Kind::Slider { .. } => "slider",
Kind::Field => "field",
Kind::Row => "row",
Kind::Slot => "slot",
Kind::Tab(true) => "tab*",
Kind::Tab(false) => "tab",
};
let target = |t: &Target| serde_json::json!({ "rect": t.rect, "kind": kind(t.kind) });
serde_json::json!({
"mode": if self.pad_focus_mode() { "focus" } else { "pointer" },
"focus": self.pad.menu.focus.as_ref().map(target),
"keyboard": self.pad.menu.osk.is_some(),
"targets": self.pad_targets().iter().map(target).collect::<Vec<_>>(),
})
}
// ---- text fields ----
/// A text field has keyboard focus: chat, a sign, a book being written,
/// a search box, the anvil's name, the title screens' and the options'
/// fields, the LAN port.
fn pad_typing(&self) -> bool {
(self.screen == Screen::Chat && self.title.is_none())
|| self.sign_edit.is_some()
|| matches!(self.book, Some(super::books::BookScreen::Edit { .. }))
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
|| self.recipe_search_focused()
|| self.station_typing()
|| self.remote_chat_open()
}
/// Open the on-screen keyboard over the focused field: Horizon's, or
/// Steam's on a Steam Deck (`steam://open/keyboard`, which types into
/// the window like a real keyboard).
fn pad_open_keyboard(&mut self) {
// Without xdg-open (macOS, Windows), Horizon's keyboard instead.
if gamepad::steam_keyboard(self.settings.controller.keyboard)
&& std::process::Command::new("xdg-open")
.arg("steam://open/keyboard")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.is_ok()
{
return;
}
self.pad.menu.osk = Some(Keyboard::default());
}
/// Chat or a sign opened by the pad in focus mode: the keyboard opens
/// with it (once per screen; B closes it for good).
fn pad_auto_keyboard(&mut self) {
let menu = &self.pad.menu;
if menu.osk.is_none()
&& !menu.osk_dismissed
&& self.pad.in_use
&& menu.open_polls >= 3
&& self.pad_focus_mode()
&& (self.screen == Screen::Chat || self.sign_edit.is_some() || self.remote_chat_open())
{
self.pad.menu.osk_dismissed = true;
self.pad_open_keyboard();
}
}
/// What a key of the on-screen keyboard does: the same as a typed key in
/// the field that has focus.
fn pad_osk_output(&mut self, out: osk::Output) {
use osk::Output;
let (key, named, text) = match &out {
Output::Text(t) => (None, None, Some(t.as_str())),
Output::Backspace => (Some(KeyCode::Backspace), Some(NamedKey::Backspace), None),
Output::Enter => (Some(KeyCode::Enter), Some(NamedKey::Enter), None),
Output::Close => {
self.pad.menu.osk = None;
self.pad.menu.osk_dismissed = true;
return;
}
};
let backspace = key == Some(KeyCode::Backspace);
if self.screen == Screen::Chat && self.title.is_none() {
match text {
Some(t) => self.chat_type(t),
None => self.chat_key_code(key.expect("a key"), None),
}
} else if self.sign_edit.is_some() {
self.sign_input(key, text);
} else if self.book.is_some() {
self.book_input(key, text);
} else if self.screen == Screen::Creative && self.creative_screen.tab().search {
if key != Some(KeyCode::Enter) {
self.creative_search_edit(text, backspace);
}
} else if self.recipe_search_focused() {
if key != Some(KeyCode::Enter) {
self.recipe_text(text, backspace);
}
} else if self.station_typing() {
if key != Some(KeyCode::Enter) {
self.station_text(text, backspace);
}
} else if self.remote_chat_open() {
self.remote_chat_input(named, text);
} else if self.screen == Screen::WorldOptions {
if key != Some(KeyCode::Enter) {
self.world_options_text(text);
}
} else if self.screen == Screen::Options {
let result = match text {
Some(t) => {
self.ui.options.type_text(&self.res.atlas, t);
Ok(())
}
None => self.options_key(key.expect("a key"), None),
};
if let Err(e) = result {
log::warn!("Horizon: on-screen keyboard: {e}");
}
} else if self.title.is_some() {
match key {
Some(KeyCode::Enter) => {
if let Some(t) = self.title.as_mut() {
t.confirm_edit();
}
}
Some(KeyCode::Backspace) => self.title_edit(None, true),
_ => self.title_edit(text, false),
}
}
// Enter ends the typing; a field that closed with it closes the keyboard.
if key == Some(KeyCode::Enter)
|| (!self.pad_typing()
&& self.title.is_none()
&& !matches!(self.screen, Screen::Options | Screen::WorldOptions))
{
self.pad.menu.osk = None;
}
}
// ---- drawing ----
/// The pad's cursor (pointer mode) or focus highlight (focus mode), and
/// the on-screen keyboard, over everything else.
pub(super) fn draw_pad_cursor(&self, batch: &mut HudBatch) {
if !self.pad_in_menu() {
return;
}
if let Some(keyboard) = &self.pad.menu.osk {
let at_top = self
.pad
.menu
.focus
.is_some_and(|f| f.center().1 > batch.height / 2.0)
|| self.screen == Screen::Chat
|| self.remote_chat_open();
let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor);
keyboard.draw(&mut ui, at_top, self.ui.options.pad_style);
ui.finish();
return;
}
let Some((x, y)) = self.pad.menu.pos else {
return;
};
if !self.pad_in_menu() {
if self.pad_focus_mode()
&& let Some(focus) = self.pad.menu.focus
{
self.draw_pad_focus(batch, focus);
return;
}
// An arrow, outlined, pointing up-left at (x, y).
@@ -444,4 +1029,53 @@ impl Game<'_> {
);
}
}
/// The focus highlight. Classic screens look as vanilla's keyboard focus
/// does: buttons, sliders and slots already draw their highlighted
/// sprite under the (hidden) pointer, and list rows and fields get
/// vanilla's white one-pixel outline (`AbstractSelectionList`'s focused
/// selection, `EditBox`'s highlighted border). Horizon-style screens get
/// the design system's focus colour: a two-dp accent ring.
fn draw_pad_focus(&self, batch: &mut HudBatch, focus: Target) {
let [x, y, w, h] = focus.rect;
// The options' sub-pages keep the classic layout under either style.
let horizon = horizon_client::ui_theme::horizon()
&& if self.screen == Screen::Options {
self.ui.options.page() == Page::Main
} else {
self.title.is_some() || self.screen == Screen::Paused
};
if horizon {
use horizon_client::ui_theme::{self as theme, Ui, color};
let mut ui = Ui::new(&self.res.atlas, batch, self.cursor);
let k = ui.batch.scale / ui.density;
let (x, y, w, h) = (x * k, y * k, w * k, h * k);
let radius = match focus.kind {
Kind::Button | Kind::Tab(_) | Kind::Slider { .. } => (h + 6.0) / 2.0,
Kind::Field => theme::RADIUS + 3.0,
_ => theme::RADIUS_PLATE + 3.0,
};
for inset in [0.0, 1.0] {
let o = 3.0 - inset;
ui.border(
x - o,
y - o,
w + 2.0 * o,
h + 2.0 * o,
radius - inset,
color::ACCENT,
);
}
ui.finish();
return;
}
if matches!(focus.kind, Kind::Row | Kind::Field) {
let atlas = &self.res.atlas;
let white = rgba(255, 255, 255, 255);
batch.fill(atlas, x, y, w, 1.0, white);
batch.fill(atlas, x, y + h - 1.0, w, 1.0, white);
batch.fill(atlas, x, y, 1.0, h, white);
batch.fill(atlas, x + w - 1.0, y, 1.0, h, white);
}
}
}
@@ -629,6 +629,66 @@ impl Game<'_> {
}
false
}
/// The recipe book's buttons a controller can focus: the book button,
/// recipes, page arrows, the craftable filter and the tabs (GUI pixels;
/// the search box registers itself as a field).
pub(super) fn recipe_book_targets(&self) -> Vec<horizon_client::widgets::Target> {
use horizon_client::widgets::{Kind, Target};
let (Some(book_type), Some(batch)) = (self.active_book(), self.batch_for_size()) else {
return Vec::new();
};
let button = |rect| Target {
rect,
kind: Kind::Button,
};
let (ox, _) = self.inventory_origin(&batch);
let (bx, by) = self.book_button_pos(book_type, ox, &batch);
let mut out = vec![button([bx, by, 20.0, 18.0])];
if !self.book_open(book_type) || self.spectator() {
return out;
}
let (xo, yo) = self.book_origin(&batch);
if let Some(overlay) = &self.recipe_ui.overlay {
// The alternatives overlay takes every click while open.
let maxrow = if overlay.entries.len() <= 16 { 4 } else { 5 };
return (0..overlay.entries.len())
.map(|n| {
let x = overlay.x + 4.0 + 25.0 * (n % maxrow) as f32;
let y = overlay.y + 5.0 + 25.0 * (n / maxrow) as f32;
button([x, y, 24.0, 24.0])
})
.collect();
}
let first = self.recipe_ui.page * 20;
let shown = self
.recipe_ui
.view
.buttons
.len()
.saturating_sub(first)
.min(20);
out.extend((0..shown).map(|n| {
let (x, y) = Self::button_pos(xo, yo, n);
button([x, y, 25.0, 25.0])
}));
let pages = self.recipe_ui.view.buttons.len().div_ceil(20);
if pages > 1 && self.recipe_ui.page + 1 < pages {
out.push(button([xo + 93.0, yo + 137.0, 12.0, 17.0]));
}
if pages > 1 && self.recipe_ui.page > 0 {
out.push(button([xo + 38.0, yo + 137.0, 12.0, 17.0]));
}
out.push(button([xo + 110.0, yo + 12.0, 26.0, 16.0]));
let selected = self.recipe_ui.tab.unwrap_or(Tab::Search);
for (n, tab) in self.recipe_ui.view.tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
out.push(Target {
rect: [x, y, 35.0, 27.0],
kind: Kind::Tab(*tab == selected),
});
}
out
}
fn shift_down(&self) -> bool {
self.has_shift_down()
}
+27 -6
View File
@@ -2300,7 +2300,7 @@ impl Game<'_> {
}
/// ChatScreen: typing, Enter to send, Escape to cancel.
pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) {
use winit::keyboard::{Key, NamedKey};
use winit::keyboard::Key;
if event.state != winit::event::ElementState::Pressed {
return;
}
@@ -2325,23 +2325,44 @@ impl Game<'_> {
return;
}
// Logical keys: the text, not the scancode, decides (layouts, virtual keyboards).
match &event.logical_key {
Key::Named(NamedKey::Escape) => {
let named = match &event.logical_key {
Key::Named(n) => Some(*n),
_ => None,
};
self.remote_chat_input(named, event.text.as_deref());
}
/// A named key or typed text in the chat input (the keyboard, or a
/// controller's on-screen keyboard).
pub(super) fn remote_chat_input(
&mut self,
named: Option<winit::keyboard::NamedKey>,
text: Option<&str>,
) {
use winit::keyboard::NamedKey;
const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0);
let Some(r) = self.remote.as_mut() else {
return;
};
let Some(input) = r.chat_input.as_mut() else {
return;
};
match named {
Some(NamedKey::Escape) => {
r.chat_input = None;
self.capture(true);
}
Key::Named(NamedKey::Backspace) => {
Some(NamedKey::Backspace) => {
if !self.text_selection.take(INPUT, input) {
input.pop();
}
}
Key::Named(NamedKey::Enter) => {
Some(NamedKey::Enter) => {
let message = r.chat_input.take().unwrap_or_default();
self.send_chat(&message);
self.capture(true);
}
_ => {
if let Some(text) = &event.text {
if let Some(text) = text {
self.text_selection.take(INPUT, input);
for c in text.chars().filter(|c| !c.is_control()) {
if input.chars().count() < 256 {
+15 -6
View File
@@ -49,18 +49,27 @@ impl Game<'_> {
self.sign_shortcut(shortcut);
return;
}
let key = match event.physical_key {
PhysicalKey::Code(k) => Some(k),
_ => None,
};
self.sign_input(key, event.text.as_deref());
}
/// A key and the text it typed on the sign being edited (the keyboard,
/// or a controller's on-screen keyboard).
pub(super) fn sign_input(&mut self, key: Option<KeyCode>, typed: Option<&str>) {
let Some(edit) = self.sign_edit.as_mut() else {
return;
};
let front = edit.front;
let id = sign_line_id(front, edit.line);
match event.physical_key {
PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(),
PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3,
PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => {
match key {
Some(KeyCode::Escape) => self.close_sign_editor(),
Some(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3,
Some(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => {
edit.line = (edit.line + 1) & 3
}
PhysicalKey::Code(KeyCode::Backspace) => {
Some(KeyCode::Backspace) => {
let (line, key) = (edit.line, edit.pos);
if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) {
let text = if front {
@@ -75,7 +84,7 @@ impl Game<'_> {
}
}
_ => {
let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else {
let Some(typed) = typed else {
return;
};
let line = edit.line;
@@ -1015,6 +1015,38 @@ impl Game<'_> {
self.station_changed();
}
/// Mouse click while a station or the brewing stand is open. True when handled.
/// A station's own buttons a controller can focus besides its slots
/// (GUI origin relative): offers, patterns, effects, enchantments and
/// stonecutter recipes.
pub(super) fn station_targets(&self) -> Vec<[f32; 4]> {
let Some(s) = self.station.as_ref() else {
return Vec::new();
};
match s.kind {
Kind::Merchant => self.merchant_targets(),
Kind::Loom => self.loom_targets(),
Kind::Beacon => self.beacon_targets(),
Kind::Enchanting => (0..3)
.map(|i| {
let (x, y, w, h) = enchant_button(i);
[x, y, w, h]
})
.collect(),
Kind::Stonecutter if s.inputs[0].is_some() => (s.start
..(s.start + 12).min(s.recipes.len()))
.map(|index| {
let p = index - s.start;
[
52.0 + (p % 4) as f32 * 16.0,
14.0 + (p / 4) as f32 * 18.0,
16.0,
18.0,
]
})
.collect(),
_ => Vec::new(),
}
}
pub(super) fn station_click(&mut self, right: bool) -> bool {
if self.station.is_none() && !self.brewing_open() {
return false;
+10
View File
@@ -507,6 +507,16 @@ impl Game<'_> {
}
false
}
/// The offer buttons a controller can focus (GUI origin relative).
pub(super) fn merchant_targets(&self) -> Vec<[f32; 4]> {
let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else {
return Vec::new();
};
(0..7)
.filter(|i| i + m.scroll < m.session.offers.len())
.map(|i| [5.0 + SHIFT, 18.0 + 20.0 * i as f32, 88.0, 20.0])
.collect()
}
pub(super) fn merchant_scroll(&mut self, d: f32) {
let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) else {
return;
+364 -1
View File
@@ -313,6 +313,73 @@ impl GlyphStyle {
}
}
/// How a controller drives menus (docs/controllers.md, "Menus and
/// inventories").
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MenuNav {
/// A console-style highlight moved between widgets and slots.
#[default]
Focus,
/// A virtual mouse pointer.
Pointer,
}
impl MenuNav {
pub fn name(self) -> &'static str {
match self {
MenuNav::Focus => "focus",
MenuNav::Pointer => "pointer",
}
}
pub fn parse(name: &str) -> Self {
match name {
"pointer" => MenuNav::Pointer,
_ => MenuNav::Focus,
}
}
}
/// The on-screen keyboard A opens on a text field in focus mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum TextKeyboard {
/// Steam's on a Steam Deck under Steam, else Horizon's.
#[default]
Auto,
Horizon,
Steam,
}
impl TextKeyboard {
pub const ALL: [TextKeyboard; 3] = [
TextKeyboard::Auto,
TextKeyboard::Horizon,
TextKeyboard::Steam,
];
pub fn name(self) -> &'static str {
match self {
TextKeyboard::Auto => "auto",
TextKeyboard::Horizon => "horizon",
TextKeyboard::Steam => "steam",
}
}
pub fn parse(name: &str) -> Self {
match name {
"horizon" => TextKeyboard::Horizon,
"steam" => TextKeyboard::Steam,
_ => TextKeyboard::Auto,
}
}
}
/// Whether A on a text field asks Steam for its keyboard
/// (`steam://open/keyboard`) instead of opening Horizon's: chosen, or `Auto`
/// on a Steam Deck (Steam sets `SteamDeck=1` for the games it starts).
pub fn steam_keyboard(choice: TextKeyboard) -> bool {
match choice {
TextKeyboard::Steam => true,
TextKeyboard::Horizon => false,
TextKeyboard::Auto => std::env::var("SteamDeck").is_ok_and(|v| v == "1"),
}
}
/// The controller settings (`horizon-controller.txt`).
#[derive(Clone, Debug, PartialEq)]
pub struct PadSettings {
@@ -329,6 +396,9 @@ pub struct PadSettings {
/// holding it, unless vanilla's toggle crouch is on already.
pub toggle_sneak: bool,
pub glyphs: GlyphStyle,
/// How the pad drives menus: a focus highlight or a virtual pointer.
pub menu_nav: MenuNav,
pub keyboard: TextKeyboard,
/// Action name -> button, `None` for unbound; missing means the default.
bindings: BTreeMap<&'static str, Option<Button>>,
}
@@ -345,6 +415,8 @@ impl Default for PadSettings {
trigger_threshold: 0.4,
toggle_sneak: true,
glyphs: GlyphStyle::Auto,
menu_nav: MenuNav::Focus,
keyboard: TextKeyboard::Auto,
bindings: BTreeMap::new(),
}
}
@@ -398,6 +470,8 @@ impl PadSettings {
}
"toggleSneak" => s.toggle_sneak = flag(s.toggle_sneak),
"glyphs" => s.glyphs = GlyphStyle::parse(value),
"menuNavigation" => s.menu_nav = MenuNav::parse(value),
"keyboard" => s.keyboard = TextKeyboard::parse(value),
other => {
if let Some(action) = other.strip_prefix("bind_") {
let button = if value == "none" {
@@ -416,7 +490,7 @@ impl PadSettings {
}
pub fn serialize(&self) -> String {
let mut text = format!(
"enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\n",
"enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\nmenuNavigation:{}\nkeyboard:{}\n",
bool_text(self.enabled),
bool_text(self.vibration),
self.look_sensitivity,
@@ -427,6 +501,8 @@ impl PadSettings {
self.trigger_threshold,
bool_text(self.toggle_sneak),
self.glyphs.name(),
self.menu_nav.name(),
self.keyboard.name(),
);
for (action, button) in &self.bindings {
text.push_str(&format!(
@@ -577,6 +653,202 @@ pub fn focus_step(from: (f32, f32), button: Button, targets: &[(f32, f32)]) -> O
.map(|(i, _)| i)
}
/// A rectangle `[x, y, w, h]` in GUI pixels.
pub type Rect = [f32; 4];
/// The D-pad direction a stick points to, when pushed past `threshold`
/// mostly along one axis (focus steps like the D-pad).
pub fn stick_direction(stick: [f32; 2], threshold: f32) -> Option<Button> {
let [x, y] = stick;
if length(stick) < threshold {
return None;
}
Some(if x.abs() > y.abs() {
if x > 0.0 {
Button::DPadRight
} else {
Button::DPadLeft
}
} else if y > 0.0 {
Button::DPadUp
} else {
Button::DPadDown
})
}
/// Arrow-key focus navigation as vanilla does it
/// (`ContainerEventHandler.nextFocusPathInDirection`), over every target of
/// the screen at once: from a strip one pixel past the focused edge, the
/// nearest target overlapping it on the other axis wins (ties: leftmost or
/// topmost); without one, the target whose facing edge's centre is nearest
/// the focused edge's centre (`nextFocusPathVaguelyInDirection`). Bounds are
/// inclusive as in `ScreenRectangle` (a right edge is `x + w - 1`).
pub fn focus_step_rect(from: Rect, button: Button, targets: &[Rect]) -> Option<usize> {
focus_step_strict(from, button, targets).or_else(|| focus_step_vague(from, button, targets))
}
/// The direction as (axis: 0 = x, 1 = y; positive).
fn direction(button: Button) -> Option<(usize, bool)> {
match button {
Button::DPadUp => Some((1, false)),
Button::DPadDown => Some((1, true)),
Button::DPadLeft => Some((0, false)),
Button::DPadRight => Some((0, true)),
_ => None,
}
}
/// The first pass of [`focus_step_rect`]: targets overlapping the focused
/// one on the other axis (a row, a column).
pub fn focus_step_strict(from: Rect, button: Button, targets: &[Rect]) -> Option<usize> {
let (axis, positive) = direction(button)?;
let other = 1 - axis;
let lo = |r: &Rect, a: usize| r[a];
let hi = |r: &Rect, a: usize| r[a] + r[a + 2] - 1.0;
// Bound in a direction (`getBoundInDirection`).
let bound = |r: &Rect, a: usize, pos: bool| if pos { hi(r, a) } else { lo(r, a) };
let after = |a: f32, b: f32| if positive { a > b + 1e-3 } else { b > a + 1e-3 };
// `getBorder(direction)`: the strip one pixel past the focused edge.
let mut strip = from;
strip[axis] = bound(&from, axis, positive) + if positive { 1.0 } else { -1.0 };
strip[axis + 2] = 1.0;
let first = bound(&strip, axis, !positive);
let same = |a: &Rect, b: &Rect| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5);
let mut strict: Vec<(usize, f32, f32)> = targets
.iter()
.enumerate()
.filter(|(_, r)| !same(r, &from))
.filter(|(_, r)| lo(r, other).max(lo(&strip, other)) <= hi(r, other).min(hi(&strip, other)))
.filter(|(_, r)| {
let child_first = bound(r, axis, !positive);
after(child_first, first)
|| ((child_first - first).abs() < 1e-3
&& after(bound(r, axis, positive), bound(&strip, axis, positive)))
})
.map(|(i, r)| (i, bound(r, axis, !positive), lo(r, other)))
.collect();
strict.sort_by(|a, b| {
let primary = if positive {
a.1.total_cmp(&b.1)
} else {
b.1.total_cmp(&a.1)
};
primary.then(a.2.total_cmp(&b.2))
});
strict.first().map(|s| s.0)
}
/// The second pass of [`focus_step_rect`]: the target whose facing edge's
/// centre is nearest the focused edge's centre.
pub fn focus_step_vague(from: Rect, button: Button, targets: &[Rect]) -> Option<usize> {
let (axis, positive) = direction(button)?;
let other = 1 - axis;
let lo = |r: &Rect, a: usize| r[a];
let hi = |r: &Rect, a: usize| r[a] + r[a + 2] - 1.0;
let bound = |r: &Rect, a: usize, pos: bool| if pos { hi(r, a) } else { lo(r, a) };
let after = |a: f32, b: f32| if positive { a > b + 1e-3 } else { b > a + 1e-3 };
let same = |a: &Rect, b: &Rect| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5);
let mut strip = from;
strip[axis] = bound(&from, axis, positive) + if positive { 1.0 } else { -1.0 };
strip[axis + 2] = 1.0;
let centre = |r: &Rect, a: usize| (hi(r, a) + lo(r, a)) / 2.0;
let edge = bound(&strip, axis, positive);
let mid = centre(&strip, other);
targets
.iter()
.enumerate()
.filter(|(_, r)| !same(r, &from))
.filter_map(|(i, r)| {
let facing = bound(r, axis, !positive);
after(facing, edge).then(|| {
let (d1, d2) = (facing - edge, centre(r, other) - mid);
(i, d1 * d1 + d2 * d2)
})
})
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
}
/// How far a list scrolled between two frames' targets: the vertical shift
/// most targets of the same position and size agree on (targets that didn't
/// move, outside the list, don't count). `None` when nothing moved.
pub fn scroll_shift(before: &[Rect], after: &[Rect]) -> Option<f32> {
let same = |a: &Rect, b: &Rect| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5);
if before.len() == after.len() && before.iter().zip(after).all(|(a, b)| same(a, b)) {
return None;
}
let mut votes: Vec<(f32, usize)> = Vec::new();
for b in before {
for a in after {
let dy = a[1] - b[1];
if (a[0] - b[0]).abs() < 0.5
&& (a[2] - b[2]).abs() < 0.5
&& (a[3] - b[3]).abs() < 0.5
&& dy.abs() >= 0.5
{
match votes.iter_mut().find(|v| (v.0 - dy).abs() < 0.5) {
Some(v) => v.1 += 1,
None => votes.push((dy, 1)),
}
}
}
}
// Most votes; among equals the smallest move (the next row, not a far one).
votes
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.abs().total_cmp(&a.0.abs())))
.map(|v| v.0)
}
/// The target a remembered focus rectangle stands for in a new frame: the
/// same rectangle, else the nearest centre within `radius` (the screen
/// moved it a little: a scrolled list, a resized window).
pub fn refind(focus: Rect, targets: &[Rect], radius: f32) -> Option<usize> {
let same = |r: &Rect| r.iter().zip(&focus).all(|(a, b)| (a - b).abs() < 0.5);
if let Some(i) = targets.iter().position(same) {
return Some(i);
}
let c = |r: &Rect| (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
let centres: Vec<(f32, f32)> = targets.iter().map(c).collect();
nearest(c(&focus), &centres, radius)
}
/// The next tab after a bumper among tab targets (left to right, then top
/// to bottom), wrapping; `None` with fewer than two tabs.
pub fn tab_step(tabs: &[(Rect, bool)], forward: bool) -> Option<usize> {
if tabs.len() < 2 {
return None;
}
let mut order: Vec<usize> = (0..tabs.len()).collect();
order.sort_by(|&a, &b| {
let (ra, rb) = (tabs[a].0, tabs[b].0);
// A vertical strip of tabs (a sidebar) reads top to bottom.
ra[1].total_cmp(&rb[1]).then(ra[0].total_cmp(&rb[0]))
});
let n = order.len();
let at = order.iter().position(|&i| tabs[i].1).unwrap_or(0);
Some(
order[if forward {
(at + 1) % n
} else {
(at + n - 1) % n
}],
)
}
/// A slider nudge: the pointer x that sets `value` (0..1) on a track
/// `[start, width]` (for vanilla's sliders `x + 4` and `w - 8`:
/// `AbstractSliderButton.setValueFromMouse` inverted).
pub fn slider_x(track: [f32; 2], value: f32) -> f32 {
track[0] + value.clamp(0.0, 1.0) * track[1]
}
/// Pixels a held left/right moves a slider handle per step: one pixel (a
/// vanilla arrow key press) at first, faster while held.
pub fn slider_step(repeats: u32) -> f32 {
[1.0, 1.0, 2.0, 2.0, 4.0, 4.0, 8.0][repeats.min(6) as usize]
}
/// The target within `radius` of `at`, nearest first (the cursor settles
/// onto a slot or button when the stick lets go).
pub fn nearest(at: (f32, f32), targets: &[(f32, f32)], radius: f32) -> Option<usize> {
@@ -819,6 +1091,97 @@ mod tests {
assert_eq!(cursor_delta([0.1, 0.0], 0.15, 0.1), (0.0, 0.0));
}
#[test]
fn focus_follows_vanilla_arrow_navigation() {
// An options screen: two columns of 150-wide buttons 20 high with
// 4 pixels between rows, a full-width Done button under them.
let mut rects: Vec<Rect> = (0..6)
.map(|i| {
let (col, row) = (i % 2, i / 2);
[
5.0 + col as f32 * 160.0,
40.0 + row as f32 * 24.0,
150.0,
20.0,
]
})
.collect();
rects.push([85.0, 120.0, 150.0, 20.0]);
assert_eq!(
focus_step_rect(rects[0], Button::DPadRight, &rects),
Some(1)
);
assert_eq!(focus_step_rect(rects[1], Button::DPadRight, &rects), None);
assert_eq!(focus_step_rect(rects[0], Button::DPadDown, &rects), Some(2));
assert_eq!(focus_step_rect(rects[3], Button::DPadUp, &rects), Some(1));
assert_eq!(focus_step_rect(rects[0], Button::DPadUp, &rects), None);
// Done overlaps both columns: down from either bottom button lands
// on it, up from it picks the leftmost overlapping one.
assert_eq!(focus_step_rect(rects[5], Button::DPadDown, &rects), Some(6));
assert_eq!(focus_step_rect(rects[4], Button::DPadDown, &rects), Some(6));
assert_eq!(focus_step_rect(rects[6], Button::DPadUp, &rects), Some(4));
// Nothing overlaps on the other axis: the vague pass takes the
// nearest facing edge (a crafting result right of the grid).
let grid: Vec<Rect> = vec![
[10.0, 10.0, 16.0, 16.0],
[28.0, 10.0, 16.0, 16.0],
[10.0, 28.0, 16.0, 16.0],
[28.0, 28.0, 16.0, 16.0],
[80.0, 50.0, 16.0, 16.0],
];
assert_eq!(focus_step_rect(grid[1], Button::DPadRight, &grid), Some(4));
assert_eq!(focus_step_rect(grid[4], Button::DPadLeft, &grid), Some(3));
assert_eq!(focus_step_rect(grid[0], Button::DPadDown, &grid), Some(2));
// The focused rectangle itself is never a step, even listed twice.
let dup = vec![grid[0], grid[0]];
assert_eq!(focus_step_rect(grid[0], Button::DPadRight, &dup), None);
assert_eq!(focus_step_rect(grid[0], Button::South, &grid), None);
}
#[test]
fn refind_tabs_sliders_and_stick_steps() {
let rects: Vec<Rect> = vec![[0.0, 0.0, 10.0, 10.0], [0.0, 20.0, 10.0, 10.0]];
assert_eq!(refind([0.0, 20.0, 10.0, 10.0], &rects, 8.0), Some(1));
// A list scrolled by 4 pixels keeps the row.
assert_eq!(refind([0.0, 24.0, 10.0, 10.0], &rects, 8.0), Some(1));
assert_eq!(refind([90.0, 90.0, 10.0, 10.0], &rects, 8.0), None);
// Rows 24 apart scrolled up by 24 under a fixed button.
let before: Vec<Rect> = (0..5)
.map(|i| [10.0, 40.0 + 24.0 * i as f32, 100.0, 20.0])
.chain([[10.0, 200.0, 50.0, 20.0]])
.collect();
let after: Vec<Rect> = (0..5)
.map(|i| [10.0, 16.0 + 24.0 * i as f32, 100.0, 20.0])
.chain([[10.0, 200.0, 50.0, 20.0]])
.collect();
assert_eq!(scroll_shift(&before, &after), Some(-24.0));
assert_eq!(scroll_shift(&before, &before), None);
let tabs = [
([60.0, 0.0, 26.0, 32.0], false),
([0.0, 0.0, 26.0, 32.0], true),
([30.0, 0.0, 26.0, 32.0], false),
];
assert_eq!(tab_step(&tabs, true), Some(2));
assert_eq!(tab_step(&tabs, false), Some(0), "wraps to the last");
assert_eq!(tab_step(&tabs[..1], true), None);
assert_eq!(slider_x([14.0, 142.0], 0.0), 14.0);
assert_eq!(slider_x([14.0, 142.0], 1.0), 156.0);
assert!(slider_step(0) == 1.0 && slider_step(99) == 8.0);
assert_eq!(stick_direction([0.9, 0.2], 0.5), Some(Button::DPadRight));
assert_eq!(stick_direction([-0.2, -0.8], 0.5), Some(Button::DPadDown));
assert_eq!(stick_direction([0.3, 0.3], 0.5), None);
let mut s = PadSettings::default();
assert_eq!(s.menu_nav, MenuNav::Focus);
s.menu_nav = MenuNav::Pointer;
s.keyboard = TextKeyboard::Horizon;
let back = PadSettings::parse(&s.serialize());
assert_eq!(
(back.menu_nav, back.keyboard),
(MenuNav::Pointer, TextKeyboard::Horizon)
);
assert!(steam_keyboard(TextKeyboard::Steam) && !steam_keyboard(TextKeyboard::Horizon));
}
#[test]
fn labels_and_conflicts() {
assert_eq!(Button::South.label(GlyphStyle::Xbox), "A");
+1
View File
@@ -107,6 +107,7 @@ pub mod options_file;
pub mod options_fixes;
pub mod options_horizon;
pub mod options_ui;
pub mod osk;
pub mod overlay;
pub mod pack_screen;
pub mod packs;
+12
View File
@@ -266,6 +266,10 @@ impl Screen {
blink: bool,
) {
let w = batch.width;
crate::widgets::target_as(
[w / 2.0 - 100.0, y + 11.0, 200.0, 20.0],
crate::widgets::Kind::Field,
);
batch.text(
atlas,
label,
@@ -331,6 +335,10 @@ impl Screen {
break;
}
let x = w / 2.0 - 152.0;
crate::widgets::target_as(
[x - 2.0, y - 2.0, 306.0, 36.0],
crate::widgets::Kind::Row,
);
if *selected == Some(i) {
batch.fill(
atlas,
@@ -391,6 +399,10 @@ impl Screen {
break;
}
let x = w / 2.0 - 152.0;
crate::widgets::target_as(
[x - 2.0, y - 2.0, 306.0, 36.0],
crate::widgets::Kind::Row,
);
if *selected == Some(i) {
batch.fill(
atlas,
@@ -108,6 +108,8 @@ pub const SECTIONS: &[Section] = &[
Opt::PadMoveDeadzone,
Opt::PadLookDeadzone,
Opt::PadGlyphs,
Opt::PadMenuNav,
Opt::PadKeyboard,
]
.map(HRow::Opt),
);
@@ -306,6 +308,7 @@ impl OptionsUi {
y -= self.hscroll;
let vstart = ui.batch.vertices.len();
let hstart = ui.hits.len();
let tstart = crate::widgets::targets_mark();
let mut sliders = Vec::new();
ui.divider(x, y, cw);
let control_x = x + cw;
@@ -456,6 +459,9 @@ impl OptionsUi {
let k = ui.density / scale;
let (y0, y1) = ((top - 1.0 + oy) * k, (bottom + oy) * k);
ui.batch.clip_since(vstart, 0.0, y0, ui.batch.width, y1);
if ui.is_real() {
crate::widgets::clip_targets(tstart, y0, y1);
}
let (cy0, cy1) = (top - 1.0 + oy, bottom + oy);
let kept: Vec<_> = ui
.hits
+30
View File
@@ -78,6 +78,8 @@ pub enum Opt {
PadMoveDeadzone,
PadLookDeadzone,
PadGlyphs,
PadMenuNav,
PadKeyboard,
}
fn tr(key: &str) -> Text {
Text::translate(key, &[])
@@ -174,6 +176,8 @@ impl Opt {
Opt::PadMoveDeadzone => "Move Deadzone",
Opt::PadLookDeadzone => "Look Deadzone",
Opt::PadGlyphs => "Button Glyphs",
Opt::PadMenuNav => "Menu Navigation",
Opt::PadKeyboard => "On-Screen Keyboard",
}
}
pub(crate) fn kind(self, s: &Settings) -> Kind {
@@ -432,6 +436,15 @@ impl Opt {
GlyphStyle::PlayStation => "PlayStation",
GlyphStyle::Nintendo => "Nintendo",
}),
Opt::PadMenuNav => Text::literal(match s.controller.menu_nav {
gamepad::MenuNav::Focus => "Focus",
gamepad::MenuNav::Pointer => "Pointer",
}),
Opt::PadKeyboard => Text::literal(match s.controller.keyboard {
gamepad::TextKeyboard::Auto => "Auto",
gamepad::TextKeyboard::Horizon => "Horizon",
gamepad::TextKeyboard::Steam => "Steam",
}),
_ => Text::empty(),
}
}
@@ -563,6 +576,20 @@ impl Opt {
.unwrap_or(0) as u8;
s.controller.glyphs = GlyphStyle::ALL[usize::from(next(i, 4))];
}
Opt::PadMenuNav => {
s.controller.menu_nav = match s.controller.menu_nav {
gamepad::MenuNav::Focus => gamepad::MenuNav::Pointer,
gamepad::MenuNav::Pointer => gamepad::MenuNav::Focus,
}
}
Opt::PadKeyboard => {
let all = gamepad::TextKeyboard::ALL;
let i = all
.iter()
.position(|k| *k == s.controller.keyboard)
.unwrap_or(0) as u8;
s.controller.keyboard = all[usize::from(next(i, 3))];
}
_ => {}
}
if self.affects_preset() {
@@ -1005,6 +1032,8 @@ impl OptionsUi {
Opt::PadMoveDeadzone,
Opt::PadLookDeadzone,
Opt::PadGlyphs,
Opt::PadMenuNav,
Opt::PadKeyboard,
]));
rows
}
@@ -1573,6 +1602,7 @@ impl OptionsUi {
WKind::LanguageRow {
label, selected, ..
} => {
crate::widgets::target_as([wd.x, wd.y, wd.w, wd.h], crate::widgets::Kind::Row);
if *selected {
batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, u32::MAX);
batch.fill(
+412
View File
@@ -0,0 +1,412 @@
//! The on-screen keyboard a controller types with in focus mode (Horizon's
//! own; docs/controllers.md, "Text fields"): a QWERTY grid and a symbols
//! grid in Horizon's design language, moved over with the D-pad or stick.
//! A types the key, X deletes, Y is a space, Start is Enter, B closes it.
//! It only produces [`Output`]s; the game feeds them to the focused field
//! the way typed keys reach it.
use crate::gamepad::{Button, GlyphStyle};
use crate::ui_theme::{self, Face, Ui, color};
/// What a key press does to the focused field.
#[derive(Clone, Debug, PartialEq)]
pub enum Output {
Text(String),
Backspace,
Enter,
/// The keyboard closes; the field keeps its text.
Close,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Key {
Char(char),
Shift,
Layer,
Space,
Backspace,
Done,
}
/// A row of keys and their widths in key units (every row is 10 wide).
type Row = &'static [(Key, f32)];
const fn c(ch: char) -> (Key, f32) {
(Key::Char(ch), 1.0)
}
const BOTTOM: Row = &[
(Key::Shift, 1.5),
(Key::Layer, 1.5),
(Key::Space, 4.0),
(Key::Backspace, 1.5),
(Key::Done, 1.5),
];
const LETTERS: [Row; 5] = [
&[
c('1'),
c('2'),
c('3'),
c('4'),
c('5'),
c('6'),
c('7'),
c('8'),
c('9'),
c('0'),
],
&[
c('q'),
c('w'),
c('e'),
c('r'),
c('t'),
c('y'),
c('u'),
c('i'),
c('o'),
c('p'),
],
&[
c('a'),
c('s'),
c('d'),
c('f'),
c('g'),
c('h'),
c('j'),
c('k'),
c('l'),
c('\''),
],
&[
c('z'),
c('x'),
c('c'),
c('v'),
c('b'),
c('n'),
c('m'),
c(','),
c('.'),
c('-'),
],
BOTTOM,
];
const SYMBOLS: [Row; 5] = [
&[
c('!'),
c('@'),
c('#'),
c('$'),
c('%'),
c('^'),
c('&'),
c('*'),
c('('),
c(')'),
],
&[
c('/'),
c('\\'),
c('_'),
c('='),
c('+'),
c('['),
c(']'),
c('{'),
c('}'),
c('|'),
],
&[
c(';'),
c(':'),
c('"'),
c('<'),
c('>'),
c('?'),
c('~'),
c('`'),
c('§'),
c('°'),
],
&[
c('é'),
c('è'),
c('à'),
c('ç'),
c('ù'),
c('ü'),
c('ö'),
c('ä'),
c('ß'),
c('ñ'),
],
BOTTOM,
];
/// The keyboard's state while open.
#[derive(Clone, Debug, PartialEq)]
pub struct Keyboard {
row: usize,
col: usize,
symbols: bool,
/// The next letter is upper case (Shift), or every letter (double Shift).
shift: bool,
caps: bool,
}
impl Default for Keyboard {
fn default() -> Self {
// Focus starts on `q`.
Self {
row: 1,
col: 0,
symbols: false,
shift: false,
caps: false,
}
}
}
impl Keyboard {
fn rows(&self) -> &'static [Row; 5] {
if self.symbols { &SYMBOLS } else { &LETTERS }
}
/// A key's left edge and width in key units.
fn span(row: Row, col: usize) -> (f32, f32) {
let left: f32 = row[..col].iter().map(|k| k.1).sum();
(left, row[col].1)
}
fn key(&self) -> Key {
self.rows()[self.row][self.col].0
}
/// A D-pad step: across a row with wrap-around; up and down to the key
/// under the focused key's centre (wrapping top and bottom).
pub fn step(&mut self, button: Button) {
let rows = self.rows();
let row = rows[self.row];
match button {
Button::DPadLeft => self.col = (self.col + row.len() - 1) % row.len(),
Button::DPadRight => self.col = (self.col + 1) % row.len(),
Button::DPadUp | Button::DPadDown => {
let (left, width) = Self::span(row, self.col);
let centre = left + width / 2.0;
self.row = if button == Button::DPadUp {
(self.row + rows.len() - 1) % rows.len()
} else {
(self.row + 1) % rows.len()
};
let next = rows[self.row];
self.col = (0..next.len())
.find(|&i| {
let (l, w) = Self::span(next, i);
centre < l + w
})
.unwrap_or(next.len() - 1);
}
_ => {}
}
}
fn letter(&self, ch: char) -> String {
if self.shift || self.caps {
ch.to_uppercase().collect()
} else {
ch.to_string()
}
}
/// A pressed: the focused key's output (Shift and the symbols switch only
/// change the keyboard).
pub fn press(&mut self) -> Option<Output> {
match self.key() {
Key::Char(ch) => {
let text = self.letter(ch);
self.shift = false;
Some(Output::Text(text))
}
Key::Shift => {
// Shift, then Shift again locks capitals; a third press lets go.
(self.shift, self.caps) = match (self.shift, self.caps) {
(false, false) => (true, false),
(true, false) => (false, true),
_ => (false, false),
};
None
}
Key::Layer => {
self.symbols = !self.symbols;
self.col = self.col.min(self.rows()[self.row].len() - 1);
None
}
Key::Space => Some(Output::Text(" ".into())),
Key::Backspace => Some(Output::Backspace),
Key::Done => Some(Output::Enter),
}
}
/// A pad button while the keyboard is open; `None` when it does nothing
/// to the field (moving, Shift).
pub fn button(&mut self, button: Button) -> Option<Output> {
match button {
Button::South => self.press(),
Button::West => Some(Output::Backspace),
Button::North => Some(Output::Text(" ".into())),
Button::Start => Some(Output::Enter),
Button::East => Some(Output::Close),
Button::LeftStick | Button::LeftTrigger => {
self.shift = !self.shift;
None
}
Button::RightBumper | Button::LeftBumper => {
self.symbols = !self.symbols;
self.col = self.col.min(self.rows()[self.row].len() - 1);
None
}
Button::DPadUp | Button::DPadDown | Button::DPadLeft | Button::DPadRight => {
self.step(button);
None
}
_ => None,
}
}
/// Draw the keyboard across the bottom of the screen, or the top when
/// the field it types into is in the lower half.
pub fn draw(&self, ui: &mut Ui, at_top: bool, glyphs: GlyphStyle) {
const UNIT: f32 = 50.0;
const GAP: f32 = 6.0;
const KEY_H: f32 = 38.0;
let width = 10.0 * UNIT + 9.0 * GAP;
let height = 5.0 * KEY_H + 4.0 * GAP + 24.0 + 30.0;
let x0 = ((ui.w - width) / 2.0).round();
let y0 = if at_top { 16.0 } else { ui.h - height - 16.0 };
ui.rounded(
x0 - 12.0,
y0 - 12.0,
width + 24.0,
height,
ui_theme::RADIUS_PLATE,
color::with_alpha(color::BG, 0.94),
);
ui.border(
x0 - 12.0,
y0 - 12.0,
width + 24.0,
height,
ui_theme::RADIUS_PLATE,
color::BORDER,
);
for (r, row) in self.rows().iter().enumerate() {
let y = y0 + r as f32 * (KEY_H + GAP);
for (i, (key, units)) in row.iter().enumerate() {
let (left, _) = Self::span(row, i);
let x = x0 + left * (UNIT + GAP);
let w = units * UNIT + (units - 1.0) * GAP;
let focused = r == self.row && i == self.col;
let lit = matches!(key, Key::Shift) && (self.shift || self.caps)
|| matches!(key, Key::Layer) && self.symbols;
let (plate, ink) = if focused {
(color::ACCENT, color::ON_ACCENT)
} else if lit {
(color::HOVER, color::TEXT)
} else {
(color::RAISED, color::TEXT)
};
ui.rounded(x, y, w, KEY_H, ui_theme::RADIUS, plate);
let label = match key {
Key::Char(ch) => self.letter(*ch),
Key::Shift if self.caps => "CAPS".into(),
Key::Shift => "Shift".into(),
Key::Layer if self.symbols => "abc".into(),
Key::Layer => "&123".into(),
Key::Space => "Space".into(),
Key::Backspace => "Delete".into(),
Key::Done => "Done".into(),
};
let lw = ui.measure(Face::Medium, ui_theme::BODY, &label);
ui.text_line(
Face::Medium,
ui_theme::BODY,
KEY_H,
x + ((w - lw) / 2.0).round(),
y,
ink,
&label,
);
}
}
let hints = [
(Button::South, "Type"),
(Button::West, "Delete"),
(Button::North, "Space"),
(Button::LeftTrigger, "Shift"),
(Button::RightBumper, "Symbols"),
(Button::Start, "Done"),
(Button::East, "Close"),
];
let line: Vec<String> = hints
.iter()
.map(|(b, what)| format!("{} {what}", b.label(glyphs)))
.collect();
ui.text_centered(
Face::Regular,
ui_theme::SMALL,
x0 + width / 2.0,
y0 + 5.0 * (KEY_H + GAP) + 2.0,
color::MUTED,
&line.join(" "),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rows_are_ten_units_wide() {
for rows in [&LETTERS, &SYMBOLS] {
for row in rows {
let units: f32 = row.iter().map(|k| k.1).sum();
assert_eq!(units, 10.0);
}
}
}
#[test]
fn types_shifts_and_moves() {
let mut k = Keyboard::default();
assert_eq!(k.press(), Some(Output::Text("q".into())));
k.step(Button::DPadRight);
k.button(Button::LeftTrigger);
assert_eq!(k.press(), Some(Output::Text("W".into())));
assert_eq!(k.press(), Some(Output::Text("w".into())), "one-shot shift");
// Left wraps to the end of the row.
k.col = 0;
k.step(Button::DPadLeft);
assert_eq!(k.press(), Some(Output::Text("p".into())));
// Down from `p` to the row of `'`, then the bottom row: `Done` sits
// under the right edge; up from the wide Space bar lands mid-row.
k.step(Button::DPadDown);
k.step(Button::DPadDown);
k.step(Button::DPadDown);
assert_eq!(k.press(), Some(Output::Enter));
k.col = 2;
assert_eq!(k.press(), Some(Output::Text(" ".into())));
k.step(Button::DPadUp);
assert_eq!(k.press(), Some(Output::Text("n".into())));
// Up from the top row wraps to the bottom row.
k.row = 0;
k.col = 0;
k.step(Button::DPadUp);
assert_eq!(k.key(), Key::Shift);
// Shift twice locks capitals; the symbols grid has no case.
k.press();
k.press();
k.row = 1;
k.col = 0;
assert_eq!(k.press(), Some(Output::Text("Q".into())));
assert_eq!(k.press(), Some(Output::Text("Q".into())));
k.button(Button::RightBumper);
assert_eq!(k.press(), Some(Output::Text("/".into())));
assert_eq!(k.button(Button::West), Some(Output::Backspace));
assert_eq!(k.button(Button::East), Some(Output::Close));
assert_eq!(k.button(Button::Start), Some(Output::Enter));
}
}
+9
View File
@@ -736,6 +736,15 @@ impl TextField {
blink_ms: u64,
format: Option<&dyn Fn(&str, usize) -> Text>,
) {
crate::widgets::target_as(
[
self.x as f32,
self.y as f32,
self.width as f32,
self.height as f32,
],
crate::widgets::Kind::Field,
);
if self.bordered {
let s = if self.focused {
"widget/text_field_highlighted"
+12
View File
@@ -738,6 +738,13 @@ impl Title {
if y + 32.0 <= LIST_TOP || y >= bottom {
continue;
}
let mid = y - 2.0 + ROW_HEIGHT / 2.0;
if mid > LIST_TOP && mid < bottom {
crate::widgets::target_as(
[x - 2.0, y - 2.0, ROW_WIDTH, ROW_HEIGHT],
crate::widgets::Kind::Row,
);
}
if *selected == Some(i) {
batch.fill(
atlas,
@@ -847,6 +854,10 @@ impl Title {
.enumerate()
{
let y = 40.0 + i as f32 * 40.0;
crate::widgets::target_as(
[(w / 2.0).floor() - 100.0, y + 11.0, 200.0, 20.0],
crate::widgets::Kind::Field,
);
batch.text(
atlas,
label,
@@ -1388,6 +1399,7 @@ fn text_field(
blink: bool,
) {
let (x, y) = pos;
crate::widgets::target_as([x, y, 200.0, 20.0], crate::widgets::Kind::Field);
batch.fill(
atlas,
x,
+11 -1
View File
@@ -285,7 +285,13 @@ pub fn slider(
) {
if active {
// A controller's D-pad can focus it (Horizon's controller support).
crate::widgets::target([x, y, w, 20.0]);
crate::widgets::target_as(
[x, y, w, 20.0],
crate::widgets::Kind::Slider {
value,
track: [x + 4.0, w - 8.0],
},
);
}
let track = if hover && active {
"gui/sprites/widget/slider_highlighted"
@@ -750,6 +756,10 @@ impl EditBox {
/// Draw the field; `format` styles the visible text (command colouring).
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) {
self.layout(atlas);
crate::widgets::target_as(
[self.x, self.y, self.width, self.height],
crate::widgets::Kind::Field,
);
if self.bordered {
let sprite = if self.focused {
"gui/sprites/widget/text_field_highlighted"
+39 -5
View File
@@ -500,6 +500,10 @@ impl<'a> Ui<'a> {
ui.real = false;
ui
}
/// A drawn frame, not a hit-testing pass.
pub fn is_real(&self) -> bool {
self.real
}
/// Move rasterized glyphs into the batch's atlas uploads (real frames only).
pub fn finish(self) {
if self.real {
@@ -579,11 +583,28 @@ impl<'a> Ui<'a> {
/// Register an interactive rectangle; returns its hover layer (0..1,
/// eased over `QUICK` like the launcher's `hover_layer`).
pub fn interact(&mut self, id: u64, x: f32, y: f32, w: f32, h: f32, enabled: bool) -> f32 {
self.interact_as(id, [x, y, w, h], enabled, crate::widgets::Kind::Button)
}
/// [`Ui::interact`] for a controller focus target of a given kind.
pub fn interact_as(
&mut self,
id: u64,
[x, y, w, h]: [f32; 4],
enabled: bool,
kind: crate::widgets::Kind,
) -> f32 {
if enabled && self.real {
// Where a controller's D-pad can move focus, in GUI pixels.
// Where a controller can move focus, in GUI pixels.
let k = self.density / self.scale;
let (ox, oy) = self.offset;
crate::widgets::target([(x + ox) * k, (y + oy) * k, w * k, h * k]);
let kind = match kind {
crate::widgets::Kind::Slider { value, track } => crate::widgets::Kind::Slider {
value,
track: [(track[0] + ox) * k, track[1] * k],
},
other => other,
};
crate::widgets::target_as([(x + ox) * k, (y + oy) * k, w * k, h * k], kind);
}
if enabled {
let (ox, oy) = self.offset;
@@ -1022,7 +1043,12 @@ impl<'a> Ui<'a> {
for (i, label) in labels.iter().enumerate() {
let iy = y + i as f32 * STEP;
let active = i == selected;
let hover = self.interact(base + i as u64, x, iy, w, CONTROL, true);
let hover = self.interact_as(
base + i as u64,
[x, iy, w, CONTROL],
true,
crate::widgets::Kind::Tab(active),
);
if !active {
self.rounded(
x,
@@ -1191,8 +1217,16 @@ impl<'a> Ui<'a> {
/// filled with ink, an ink 14px knob that grows under the pointer.
/// Dragging is the screen's job (see [`slider_value`]).
pub fn slider(&mut self, id: u64, x: f32, cy: f32, w: f32, value: f32) {
let hover = self.interact(id, x - 8.0, cy - 12.0, w + 16.0, 24.0, true);
let v = value.clamp(0.0, 1.0);
let hover = self.interact_as(
id,
[x - 8.0, cy - 12.0, w + 16.0, 24.0],
true,
crate::widgets::Kind::Slider {
value: v,
track: [x, w],
},
);
self.rounded(x, cy - 1.0, w, 2.0, 1.0, color::BORDER);
self.rounded(x, cy - 1.0, w * v, 2.0, 1.0, color::TEXT);
let r = 7.0 + hover;
@@ -1209,7 +1243,7 @@ impl<'a> Ui<'a> {
focused: bool,
caret: bool,
) {
let hover = self.interact(id, x, y, w, h, true);
let hover = self.interact_as(id, [x, y, w, h], true, crate::widgets::Kind::Field);
let focus = self.tween(id ^ 0xf0c05ed, if focused { 1.0 } else { 0.0 }, quick());
self.rounded(x, y, w, h, RADIUS, color::RAISED);
self.rounded(
+106 -11
View File
@@ -14,27 +14,95 @@ pub struct Widget {
pub enabled: bool,
}
/// What a controller does with a focus target (docs/controllers.md, "Focus
/// navigation").
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Kind {
/// Clicked with A (buttons, switches, segments, sidebar items).
Button,
/// Left and right move the value instead of focus; A does nothing (a
/// click would jump the handle to the middle). `value` is 0..1 as drawn;
/// `track` is where a click sets 0 and the width a click spans to 1.
Slider { value: f32, track: [f32; 2] },
/// A text field: A focuses it and opens an on-screen keyboard.
Field,
/// A list row (worlds, servers, packs, languages): A selects it.
Row,
/// An inventory slot: A/X/Y click, right click and quick-move it.
Slot,
/// A tab (`true` is the selected one): the bumpers step through them.
Tab(bool),
}
/// A focus target: a rectangle in GUI pixels and what it is.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Target {
pub rect: [f32; 4],
pub kind: Kind,
}
impl Target {
pub fn center(&self) -> (f32, f32) {
let [x, y, w, h] = self.rect;
(x + w / 2.0, y + h / 2.0)
}
}
thread_local! {
/// Buttons drawn since the last `end_frame`, and the last frame's.
static WIDGETS: RefCell<(Vec<Widget>, Vec<Widget>, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
/// Every interactive rectangle of Horizon-style menus (sidebar items,
/// switches, sliders, segments), labelled or not: where a controller's
/// D-pad can move focus. Drawn since `end_frame`, and the last frame's.
static TARGETS: RefCell<(Vec<[f32; 4]>, Vec<[f32; 4]>)> = const { RefCell::new((Vec::new(), Vec::new())) };
/// Every interactive rectangle (Horizon-style menus' sidebar items,
/// switches, sliders, segments; classic sliders, fields and list rows),
/// labelled or not: where a controller can move focus. Drawn since
/// `end_frame`, the last frame's, and how many frames rotated.
static TARGETS: RefCell<(Vec<Target>, Vec<Target>, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
}
/// An interactive rectangle (GUI pixels) a controller can focus.
/// An interactive rectangle (GUI pixels) a controller can focus and click.
pub fn target(rect: [f32; 4]) {
TARGETS.with_borrow_mut(|(current, _)| {
target_as(rect, Kind::Button);
}
/// An interactive rectangle of a given kind.
pub fn target_as(rect: [f32; 4], kind: Kind) {
if !rect.iter().all(|v| v.is_finite()) || rect[2] <= 0.0 || rect[3] <= 0.0 {
return;
}
TARGETS.with_borrow_mut(|(current, _, _)| {
if current.len() < 1024 {
current.push(rect);
current.push(Target { rect, kind });
}
});
}
/// How many targets the frame has so far, for [`clip_targets`].
pub fn targets_mark() -> usize {
TARGETS.with_borrow(|(current, _, _)| current.len())
}
/// Drop the targets registered since `mark` that aren't inside `y0..y1`
/// (GUI pixels): rows a scrolling list clipped away.
pub fn clip_targets(mark: usize, y0: f32, y1: f32) {
TARGETS.with_borrow_mut(|(current, _, _)| {
let mut i = mark.min(current.len());
while i < current.len() {
let [_, y, _, h] = current[i].rect;
if y < y0 - 0.5 || y + h > y1 + 0.5 {
current.remove(i);
} else {
i += 1;
}
}
});
}
/// The focus targets of the last drawn frame.
pub fn last_targets() -> Vec<[f32; 4]> {
TARGETS.with_borrow(|(_, last)| last.clone())
pub fn last_targets() -> Vec<Target> {
TARGETS.with_borrow(|(_, last, _)| last.clone())
}
/// Counts drawn frames: focus waits for a new one after scrolling a list.
pub fn generation() -> u64 {
TARGETS.with_borrow(|(_, _, generation)| *generation)
}
/// Called by the button drawers.
@@ -64,7 +132,10 @@ pub fn end_frame(frames: u64) {
if *seen != frames {
*seen = frames;
*last = std::mem::take(current);
TARGETS.with_borrow_mut(|(current, last)| *last = std::mem::take(current));
TARGETS.with_borrow_mut(|(current, last, generation)| {
*last = std::mem::take(current);
*generation += 1;
});
}
});
}
@@ -129,11 +200,35 @@ mod tests {
#[test]
fn frames_rotate_only_when_drawn() {
record("Respawn", [1.0, 2.0, 3.0, 4.0], true);
target_as(
[1.0, 2.0, 3.0, 4.0],
Kind::Slider {
value: 0.5,
track: [1.0, 3.0],
},
);
target_as([1.0, 2.0, 0.0, 4.0], Kind::Row);
let before = generation();
end_frame(1);
assert_eq!(last().len(), 1);
assert_eq!(last_targets().len(), 1, "an empty rectangle isn't a target");
assert!(matches!(last_targets()[0].kind, Kind::Slider { value, .. } if value == 0.5));
assert_eq!(last_targets()[0].center(), (2.5, 4.0));
end_frame(1);
assert_eq!(last().len(), 1);
assert_eq!(generation(), before + 1);
end_frame(2);
assert!(last().is_empty());
assert!(last().is_empty() && last_targets().is_empty());
target([0.0, 0.0, 5.0, 5.0]);
let mark = targets_mark();
target([0.0, 10.0, 5.0, 5.0]);
target([0.0, 40.0, 5.0, 5.0]);
clip_targets(mark, 8.0, 30.0);
end_frame(3);
assert_eq!(
last_targets().len(),
2,
"the clipped row is gone, earlier ones stay"
);
}
}
+131 -24
View File
@@ -70,25 +70,128 @@ hold-to-sneak.
## Menus and inventories
Vanilla's screens are all mouse-driven, and Horizon draws them 1:1, so a pad
drives them through a **virtual cursor** (as Bedrock's classic inventory UI
and Java's controller mods do), not focus navigation:
Vanilla's screens are all mouse-driven, and Horizon draws them 1:1. A pad
drives them in one of two ways, picked in the controller options ("Menu
Navigation: Focus / Pointer", `menuNavigation:focus|pointer`):
- **Focus** (the default): a console-style highlight that the D-pad and the
left stick move between buttons, sliders, switches, text fields, list
rows, tabs and inventory slots.
- **Pointer**: a virtual cursor the left stick moves, as Bedrock's classic
inventory UI and Java's controller mods do.
Focus is the default because it is what a pad player expects from a console
game, it needs no aiming (every widget is one D-pad press away, which also
suits the Steam Deck's small screen), and it works from the couch. The
pointer stays one option away, and a **right stick click swaps the two for
the open screen**, for the few places a pointer is better (dragging the
advancements map, painting a crafting grid with a held stack).
Both modes feed the screens the same pointer events a mouse sends: in focus
mode the (hidden) pointer sits on the focused widget. So every screen keeps
its mouse behaviour (drags, sliders, scrollbars, hover highlights) with no
controller code of its own, and both modes reach every screen. Moving the
real mouse hands control back at once.
### Focus navigation
Every interactive rectangle a screen draws registers itself as a focus
target with its kind (`widgets::target_as`): classic buttons, sliders, edit
boxes and list rows (worlds, servers, languages), every Horizon-style widget
(`ui_theme::Ui::interact`: sidebar items, switches, segments, sliders,
fields, buttons), inventory and container slots, creative and recipe-book
tabs, and the stations' own buttons (trades, loom patterns, beacon effects,
enchantments, stonecutter recipes, the recipe book's recipes, pages and
filter). A screen that registers nothing falls back to the pointer.
The step itself is **vanilla's arrow-key navigation**
(`ContainerEventHandler.nextFocusPathInDirection`, 26.3), applied to every
target of the screen at once: from a strip one pixel past the focused edge,
the nearest target that overlaps it on the other axis wins (ties go to the
leftmost or topmost); without one, the target whose facing edge's centre is
nearest the focused edge's centre (`nextFocusPathVaguelyInDirection`). That
gives vanilla-like jumps in containers too: hotbar to inventory, the grid to
the crafting result, armour to the player's grid.
| Input | Focus mode |
|---|---|
| D-pad, left stick | move focus (held: repeats after 0.35 s, every 0.09 s) |
| A | press the focused widget (held: drag); on a text field, type with the on-screen keyboard |
| B, Menu | back (Escape) |
| X | right click (inventories: take half, place one) |
| Y | quick move (shift-click) in inventories |
| View | throw one item from the focused slot (Q) |
| Left stick click | throw the focused stack (Ctrl+Q) |
| LB / RB | previous / next tab (creative, recipe book, the Horizon options' sections) |
| Right stick | scroll |
| Right stick click | swap focus and pointer for this screen |
- **Sliders**: left and right move the value (one pixel per press like
vanilla's arrow keys, faster while held); A does nothing on a slider, as a
click would jump the handle.
- **Lists** follow focus: a step past the last visible row scrolls the list
and lands on the next row once it is drawn.
- **Inventories**: the carried stack is drawn on the focused slot (vanilla
draws it under the pointer). A takes or places, X splits or places one, Y
quick-moves, View and the left stick click throw.
- **Where focus lands** when a screen opens: the held hotbar slot in an
inventory, else the first button.
How it looks follows the menu style:
- **Classic screens** look as vanilla's own keyboard focus does: buttons,
sliders and slots show their highlighted sprite (`isHoveredOrFocused`,
drawn because the hidden pointer is over them), and list rows and text
fields get vanilla's white one-pixel outline (`AbstractSelectionList`'s
focused selection, `EditBox`'s highlighted border).
- **Horizon-style screens** get the design system's focus colour: a two-dp
ring in the accent colour around the focused widget, pill-shaped on
buttons, tabs and sliders.
### Pointer
- Left stick moves the cursor with acceleration; in container screens the
cursor is gently pulled toward the nearest slot centre.
- D-pad steps one slot (18 GUI pixels in containers) or one widget row in
menus and snaps to it.
- A = left click (take / place stack, press a button), X = right click
(half stack / place one), Y = quick move (shift-click), B = back / close.
- LB / RB switch creative tabs and recipe book pages; right stick scrolls
(creative grid, lists, chat).
- D-pad steps to the nearest target that way (a slot, a button) and snaps to
it.
- A = left click, X = right click, Y = quick move, B = back; View and the left
stick click throw, as in focus mode.
- LB / RB switch tabs; right stick scrolls.
- Sliders: hold A on the slider and move the stick, or nudge with the D-pad.
- Text fields: the Steam Deck's keyboard (Steam + X) types into them like a
real keyboard. Other platforms have no on-screen keyboard yet; text input
needs a keyboard.
The cursor is drawn only while the pad is the last-used input; moving the
mouse hands control back immediately.
The cursor is drawn only while the pad is the last-used input.
### Text fields
A on a focused text field (A in pointer mode clicks into it) opens the
**on-screen keyboard**: a QWERTY grid and a symbols grid in Horizon's design
language, at the bottom of the screen (at the top when the field is in the
lower half, as chat is). D-pad or stick to move, A types, X deletes, Y is a
space, LT is Shift (twice: caps lock), RB switches to symbols and accents,
Menu is Enter, B closes it. It opens by itself when the pad opens chat or a
sign. It types into every field the keyboard reaches: chat (local and
server), signs, books, the title screens' fields, the options' searches, the
creative and recipe-book searches, the anvil, the LAN port.
On a Steam Deck under Steam (`SteamDeck=1`), A asks Steam for its own
keyboard instead (`steam://open/keyboard`), which types like a real keyboard;
Steam + X opens it at any time. "On-Screen Keyboard: Auto / Horizon / Steam"
(`keyboard:`) picks one.
### Screens covered
Both modes reach every screen through the pointer events. Focus mode
registers targets on: the title menus (main, world list and its search, create
and edit world, delete, multiplayer list and its edit screens), every options
page (classic pages and the Horizon-style sections, key and controller binds,
language list), pause, death, chat, signs and books (their buttons), the
survival and creative inventories, every container and station (chests,
furnaces, brewing, crafter, crafting table with its recipe book, anvil,
grindstone, smithing, stonecutter, loom, cartography, enchanting, beacon,
villager and wandering-trader trades, mount inventories), and the LAN /
world options. Where a screen draws something clickable no target names
(the advancements map, the statistics lists, the pack screen's rows, the
book's page text), the right stick click gives the pointer for that screen.
## Glyphs
@@ -161,14 +264,18 @@ no force feedback, so it is silently skipped there.
## PR plan
1. **Input layer and gameplay** (this note, gilrs, defaults, movement,
camera, actions, hotbar, B/Start to leave screens, `horizon-ctl pad`,
`horizon-controller.txt` with the look/deadzone settings).
2. **Menus and inventories**: virtual cursor, slot snapping, clicks, quick
move, tabs, scrolling, sliders.
3. **Glyphs and the Controller options page**: glyph drawing per pad type,
the options page, remapping UI.
4. **Rumble**.
The first round (input layer, menus, glyphs and options, rumble) shipped in
PRs #120, #129, #145 and #149. The second round, each shippable alone:
Each is shippable alone. Testing is with unit tests, the injected pad and
vscreen screenshots; each PR says what still needs a real controller.
1. **Focus navigation** (this section above): the menu navigation option,
focus targets and vanilla's arrow-key step, the focus highlight in both
menu styles, the on-screen keyboard.
2. **Button prompts**: contextual hints with the pad's glyphs in menus and
optionally in game, and rebinding from them.
3. **DualSense output**: adaptive triggers, lightbar, player LEDs and richer
rumble over HID, off-safe.
4. **Launcher**: the same focus navigation in the gpui launcher.
Each is tested with unit tests (focus steps, prompt contexts, report bytes),
the injected pad and vscreen screenshots; each PR says what still needs a
real controller.