Controllers: focus navigation in menus, on-screen keyboard, menu navigation option

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 00:41:42 +02:00
parent 6ddabae4dd
commit 9927d06049
17 changed files with 1596 additions and 130 deletions
+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);
}
}
}
+3 -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);
@@ -340,11 +340,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 +349,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.
+635 -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,20 @@ 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.
#[derive(Clone, Copy)]
struct Pending {
button: Button,
from: Rect,
generation: u64,
tries: u8,
}
#[derive(Default)]
pub(super) struct MenuCursor {
@@ -45,12 +71,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 +104,75 @@ 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).
fn pad_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)
}));
}
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 +181,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 +267,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 +289,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 +339,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 +400,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 +467,102 @@ 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();
match gamepad::focus_step_rect(focus.rect, button, &rects) {
Some(i) => self.pad_focus_on(event_loop, targets[i]),
None if matches!(button, Button::DPadUp | Button::DPadDown) => {
// Off the visible rows of a list: scroll it and try again on
// the next frame.
self.pad_wheel(
event_loop,
0.0,
if button == Button::DPadUp { 1.0 } else { -1.0 },
);
self.pad.menu.pending = Some(Pending {
button,
from: focus.rect,
generation: widgets::generation(),
tries: 1,
});
}
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 +584,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 +604,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 +624,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 +707,64 @@ 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();
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]);
}
if let Some(p) = self.pad.menu.pending
&& widgets::generation() > p.generation
{
self.pad.menu.pending = None;
match gamepad::focus_step_rect(p.from, p.button, &rects) {
Some(i) => self.pad_focus_on(event_loop, targets[i]),
None if p.tries < SCROLL_TRIES => {
let up = p.button == Button::DPadUp;
self.pad_wheel(event_loop, 0.0, if up { 1.0 } else { -1.0 });
self.pad.menu.pending = Some(Pending {
generation: widgets::generation(),
tries: p.tries + 1,
..p
});
}
None => {}
}
}
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 +775,155 @@ impl Game<'_> {
}
}
/// The pad's cursor, over everything else.
// ---- 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) {
if gamepad::steam_keyboard(self.settings.controller.keyboard) {
let _ = 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();
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 +954,50 @@ 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;
let horizon = horizon_client::ui_theme::horizon()
&& (self.title.is_some()
|| self.screen == Screen::Options
|| 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);
}
}
}
+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;
+299 -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,148 @@ 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> {
// (axis: 0 = x, 1 = y; positive direction)
let (axis, positive) = match button {
Button::DPadUp => (1, false),
Button::DPadDown => (1, true),
Button::DPadLeft => (0, false),
Button::DPadRight => (0, true),
_ => return None,
};
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))
});
if let Some((i, ..)) = strict.first() {
return Some(*i);
}
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)
}
/// 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 +1037,86 @@ 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);
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
@@ -106,6 +106,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;
+8
View File
@@ -305,6 +305,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,
@@ -365,6 +369,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),
);
+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() {
@@ -993,6 +1020,8 @@ impl OptionsUi {
Opt::PadMoveDeadzone,
Opt::PadLookDeadzone,
Opt::PadGlyphs,
Opt::PadMenuNav,
Opt::PadKeyboard,
]));
rows
}
@@ -1560,6 +1589,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"
+8
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,
@@ -1388,6 +1395,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"
@@ -737,6 +743,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"
+35 -5
View File
@@ -556,11 +556,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;
@@ -999,7 +1016,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,
@@ -1168,8 +1190,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;
@@ -1186,7 +1216,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(
+74 -11
View File
@@ -14,27 +14,74 @@ 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 });
}
});
}
/// 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 +111,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 +179,24 @@ 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());
}
}