Address creative inventory review on current main

This commit is contained in:
Cosmic
2026-10-14 12:11:53 -04:00
parent 767ed4cb47
commit e905c10400
5 changed files with 115 additions and 195 deletions
+20
View File
@@ -443,6 +443,26 @@ mod tests {
}));
}
#[test]
fn inventory_tab_can_return_to_category_and_search() {
let mut c = creative(90);
for (selected, inventory, search) in [
(2, true, false),
(0, false, false),
(1, false, true),
(2, true, false),
] {
c.search = "anvil".into();
c.scroll = 0.5;
c.select(selected);
assert_eq!(c.selected, selected);
assert_eq!(c.tab().inventory, inventory);
assert_eq!(c.tab().search, search);
assert!(c.search.is_empty());
assert_eq!(c.scroll, 0.0);
}
}
#[test]
fn hidden_tabs_are_skipped() {
let c = creative(0);
+95 -20
View File
@@ -588,6 +588,22 @@ pub struct Resources {
/// Enchantments, workstation recipes and brewing (game/stations.rs).
stations: horizon_client::stations::StationData,
}
/// Ctrl+Q reads the physical keyboard, independently of sprint key mappings.
fn drop_whole_stack(physical_keys: &HashSet<KeyCode>) -> bool {
physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight)
}
fn select_creative_tab(
creative: &mut Creative,
clicks: &mut horizon_client::container_screen::Clicks,
tab: usize,
) {
creative.select(tab);
*clicks = Default::default();
// Tabs are outside the panel; their release must not drop a carried stack.
clicks.skip_release();
}
struct Game<'a> {
res: &'a mut Resources,
collision: &'a BlockCollisionRegistry<'a>,
@@ -4170,8 +4186,7 @@ impl Game<'_> {
(Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap),
(None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap),
(None, KeyCode::KeyQ) => {
let all = self.physical_keys.contains(&KeyCode::ControlLeft)
|| self.physical_keys.contains(&KeyCode::ControlRight);
let all = drop_whole_stack(&self.physical_keys);
self.menu_click(Some(slot), i32::from(all), Input::Throw)
}
_ => false,
@@ -4274,16 +4289,21 @@ impl Game<'_> {
fn clicked_outside(&self, batch: &HudBatch) -> bool {
use horizon_client::container_screen::{Book, Image, clicked_outside};
let (ox, oy) = self.inventory_origin(batch);
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
let (shift, width, height) = if self.creative_inventory_open() {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
let image = Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height: self.screen_height() as i32,
height,
};
let book = self
.recipe_book_area(batch)
@@ -7421,7 +7441,7 @@ impl Game<'_> {
for (i, t) in tabs.iter().enumerate() {
let (tx, ty) = Creative::tab_position(t);
if cx >= ox + tx && cx < ox + tx + 26.0 && cy >= oy + ty && cy < oy + ty + 32.0 {
self.creative_screen.select(i);
select_creative_tab(&mut self.creative_screen, &mut self.inv_clicks, i);
self.inv_drag = None;
self.last_inv_click = None;
return;
@@ -7429,9 +7449,7 @@ impl Game<'_> {
}
if self.creative_inventory_open() {
if Self::creative_trash_hovered(&batch, self.cursor) {
if self.keys.contains(&KeyCode::ShiftLeft)
|| self.keys.contains(&KeyCode::ShiftRight)
{
if self.has_shift_down() {
self.inventory.fill(None);
self.armor.fill(None);
self.offhand = None;
@@ -7441,12 +7459,8 @@ impl Game<'_> {
self.carried = None;
}
self.inv_drag = None;
} else if self.slot_at(&batch, cx, cy).is_some()
|| !(cx >= ox
&& cx < ox + Creative::WIDTH
&& cy >= oy
&& cy < oy + Creative::HEIGHT)
{
self.inv_clicks = Default::default();
} else if self.slot_at(&batch, cx, cy).is_some() || self.clicked_outside(&batch) {
self.inventory_press(right);
}
return;
@@ -8002,8 +8016,7 @@ impl Game<'_> {
self.using = None;
}
KeyCode::KeyQ if self.screen == Screen::Playing => {
let all = self.physical_keys.contains(&KeyCode::ControlLeft)
|| self.physical_keys.contains(&KeyCode::ControlRight);
let all = drop_whole_stack(&self.physical_keys);
self.drop_held(all);
}
KeyCode::Digit1
@@ -8453,7 +8466,7 @@ impl ApplicationHandler for Game<'_> {
self.click_creative(button == MouseButton::Right);
}
Screen::Creative if self.creative_screen.tab().inventory => {
self.inventory_release();
self.inventory_mouse_release(button == MouseButton::Right);
}
Screen::Creative if button == MouseButton::Left => {
self.creative_screen.release();
@@ -9280,3 +9293,65 @@ pub fn run() -> Result<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_client::container_screen::{Button, Clicks, Release, Target};
use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys};
#[test]
fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() {
let mut creative = Creative::from_json(&serde_json::json!({
"schema": 2,
"tabs": [{"type": "CATEGORY"}, {"type": "INVENTORY"}]
}))
.unwrap();
for button in [Button::Left, Button::Right] {
let mut clicks = Clicks::default();
for tab in [1, 1, 0, 1] {
select_creative_tab(&mut creative, &mut clicks, tab);
assert_eq!(creative.selected, tab);
assert_eq!(creative.tab().inventory, tab == 1);
assert_eq!(
clicks.release(
&Target::<usize>::Outside,
button,
false,
false,
false,
false
),
Release::Nothing
);
}
}
}
#[test]
fn stack_drop_requires_physical_ctrl_even_with_sprint_latched() {
for sprint in [false, true] {
let mut toggles = ToggleKeys::default();
if sprint {
toggles.key(SPRINT, KeyAction::Press, false, true);
toggles.key(SPRINT, KeyAction::Release, false, true);
}
assert_eq!(toggles.is_down(SPRINT), sprint);
for held in 0..4 {
let mut physical_keys = HashSet::from([KeyCode::ShiftLeft, KeyCode::KeyQ]);
if held & 1 != 0 {
physical_keys.insert(KeyCode::ControlLeft);
}
if held & 2 != 0 {
physical_keys.insert(KeyCode::ControlRight);
}
assert_eq!(drop_whole_stack(&physical_keys), held != 0);
physical_keys.remove(&KeyCode::ControlLeft);
physical_keys.remove(&KeyCode::ControlRight);
assert!(!drop_whole_stack(&physical_keys));
assert_eq!(toggles.is_down(SPRINT), sprint);
}
}
}
}
@@ -1,58 +0,0 @@
"""Exercise the real creative-tab selection branch without a desktop window."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class CreativeInventoryTransitionTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the tab-selection probe")
def test_inventory_tab_stays_in_the_creative_screen(self):
source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
click = source.split("fn click_creative(&mut self, right: bool)", 1)[1]
branch = click.split("if cx >= ox + tx", 1)[1]
branch = branch.split("{", 1)[1].split("\n }\n", 1)[0]
program = """
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Screen { Creative, Inventory }
struct Tab { inventory: bool }
struct Creative { selected: usize, tabs: [Tab; 2] }
impl Creative { fn select(&mut self, i: usize) { self.selected = i; } }
struct Game { screen: Screen, creative_screen: Creative, inv_drag: Option<u8>, last_inv_click: Option<u8> }
impl Game {
fn click_tab(&mut self, i: usize) {
let t = &self.creative_screen.tabs[i];
SELECTION
}
}
#[test]
fn inventory_and_back_preserve_the_creative_screen() {
let mut game = Game { screen: Screen::Creative,
creative_screen: Creative { selected: 0, tabs: [Tab { inventory: false }, Tab { inventory: true }] },
inv_drag: Some(1), last_inv_click: Some(2) };
game.click_tab(1);
assert_eq!(game.screen, Screen::Creative);
assert_eq!(game.creative_screen.selected, 1);
assert!(game.inv_drag.is_none() && game.last_inv_click.is_none());
game.click_tab(0);
assert_eq!(game.screen, Screen::Creative);
assert_eq!(game.creative_screen.selected, 0);
}
""".replace("SELECTION", branch)
with tempfile.TemporaryDirectory(prefix="horizon-creative-tab-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
compiled = subprocess.run(
["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
capture_output=True, text=True, check=False,
)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
-55
View File
@@ -1,55 +0,0 @@
"""Drop modifiers must come from physical Ctrl, not the sprint key mapping."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class DropModifierPolicyTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the drop-policy probe")
def test_playing_and_inventory_drop_ignore_latched_sprint(self):
source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
inventory = source.split("fn inventory_hotkey(", 1)[1]
playing = source.split("KeyCode::KeyQ if self.screen == Screen::Playing =>", 1)[1]
expressions = [section.split("let all = ", 1)[1].split(";", 1)[0]
for section in (inventory, playing)]
program = """
use std::collections::HashSet;
#[derive(PartialEq, Eq, Hash)] enum KeyCode { ControlLeft, ControlRight }
struct Game { keys: HashSet<KeyCode>, physical_keys: HashSet<KeyCode> }
impl Game {
fn inventory_drop_all(&self) -> bool { INVENTORY }
fn playing_drop_all(&self) -> bool { PLAYING }
}
#[test]
fn sprint_and_control_are_independent() {
for sprint in [false, true] {
for held in 0..4 {
let ctrl = held != 0;
let mut game = Game { keys: HashSet::new(), physical_keys: HashSet::new() };
if held & 1 != 0 { game.physical_keys.insert(KeyCode::ControlLeft); }
if held & 2 != 0 { game.physical_keys.insert(KeyCode::ControlRight); }
if sprint { game.keys.insert(KeyCode::ControlLeft); }
assert_eq!(game.inventory_drop_all(), ctrl, "inventory: sprint={sprint}, ctrl={ctrl}");
assert_eq!(game.playing_drop_all(), ctrl, "playing: sprint={sprint}, ctrl={ctrl}");
}
}
}
""".replace("INVENTORY", expressions[0]).replace("PLAYING", expressions[1])
with tempfile.TemporaryDirectory(prefix="horizon-drop-policy-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
compiled = subprocess.run(
["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
capture_output=True, text=True, check=False,
)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
-62
View File
@@ -1,62 +0,0 @@
"""Compile the real frame hand-selection expression without opening a window."""
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class HandFramePolicyTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the frame-policy probe")
def test_inventory_screen_does_not_suppress_first_person_geometry(self):
source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
match = re.search(r"let hand = (if .*?);\s*let screen =", source, re.S)
self.assertIsNotNone(match, "frame hand-selection seam changed")
selection = match.group(1)
# Only geometry generation is stubbed; execute the actual frame guard.
program = """
#[derive(Clone, Copy, PartialEq, Eq)]
enum Screen { Playing, Creative, Inventory }
struct Game { screen: Screen, scoping: bool }
impl Game {
fn scoping(&self) -> bool { self.scoping }
fn hand_geometry(&mut self, _: f64) -> Vec<u8> { vec![1] }
fn hand_len(&mut self, title: bool) -> usize {
let alpha = 0.0;
let hand = SELECTION;
hand.len()
}
}
#[test]
fn creative_inventory_and_return_keep_the_hand() {
let mut game = Game { screen: Screen::Playing, scoping: false };
for screen in [Screen::Playing, Screen::Creative, Screen::Inventory, Screen::Playing] {
game.screen = screen;
assert_eq!(game.hand_len(false), 1);
}
}
#[test]
fn title_and_spyglass_still_hide_the_hand() {
let mut game = Game { screen: Screen::Inventory, scoping: false };
assert_eq!(game.hand_len(true), 0);
game.scoping = true;
assert_eq!(game.hand_len(false), 0);
}
""".replace("SELECTION", selection)
with tempfile.TemporaryDirectory(prefix="horizon-hand-policy-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
compiled = subprocess.run(
["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
capture_output=True, text=True, check=False,
)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()