Compare the chat screen's input and command suggestions with vanilla
horizon_client::chat::ChatScreen is now a port of vanilla's ChatScreen, EditBox and CommandSuggestions: the input's scrolling, cursor, selection, word moves and select all, history up and down, argument colouring, usage lines and parse errors, the suggestion list (sorting, hover, Tab and Shift+Tab cycling, clicks, wheel) and its tooltips, drawn as GUI calls the game paints. tools/test_chat_screen_parity.py drives a real ChatScreen on vanilla's client command tree (custom suggestions answered by the server dispatcher): 3000/3000 cases match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
//! The chat screen's input for tools/test_chat_screen_parity.py: reads one
|
||||
//! JSON case per line (GUI size, history, options, typed text, keys,
|
||||
//! clicks, mouse), runs `horizon_client::chat::ChatScreen` on the vanilla
|
||||
//! command tree and writes the input's state and the screen's GUI calls in
|
||||
//! the oracle's JSON form.
|
||||
//!
|
||||
//! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT
|
||||
use horizon_client::{
|
||||
chat::{ChatAction, ChatScreen, Commands},
|
||||
command::vanilla,
|
||||
hud::HudAtlas,
|
||||
lang,
|
||||
screen_draw::Measure,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fmt::Write as _, fs, path::PathBuf};
|
||||
use winit::keyboard::KeyCode as K;
|
||||
#[path = "pack_screen_fixture.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod pack_screen_fixture;
|
||||
#[path = "chat_screen_fixture/registries.rs"]
|
||||
mod registries;
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
let [root, registries, inputs, output] = args.as_slice() else {
|
||||
return Err("usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT".into());
|
||||
};
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
lang::set(lang::Language::load(&[root], lang::DEFAULT));
|
||||
let m = Measure(&atlas.font);
|
||||
let reg = registries::registries(&serde_json::from_slice(&fs::read(registries)?)?, 4);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::release_dispatcher(),
|
||||
registries: ®,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
|
||||
let history: Vec<String> = case["history"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|s| s.as_str().map(str::to_owned))
|
||||
.collect();
|
||||
let (w, h) = (int(&case["width"]), int(&case["height"]));
|
||||
let mut screen = ChatScreen::new(
|
||||
&m,
|
||||
&c,
|
||||
case["initial"].as_str().unwrap_or(""),
|
||||
history.len(),
|
||||
w,
|
||||
h,
|
||||
);
|
||||
screen.auto_suggestions = case["autoSuggest"] == true;
|
||||
let mut closed = false;
|
||||
for a in case["actions"].as_array().into_iter().flatten() {
|
||||
match a["type"].as_str().unwrap_or_default() {
|
||||
"type" => screen.type_text(&m, &c, a["text"].as_str().unwrap_or_default()),
|
||||
"click" => {
|
||||
screen.click(
|
||||
&m,
|
||||
&c,
|
||||
a["x"].as_f64().unwrap_or(0.0),
|
||||
a["y"].as_f64().unwrap_or(0.0),
|
||||
);
|
||||
}
|
||||
"key" => {
|
||||
let mut name = a["key"].as_str().unwrap_or_default();
|
||||
let (mut shift, mut ctrl) = (false, false);
|
||||
loop {
|
||||
if let Some(n) = name.strip_prefix("shift+") {
|
||||
shift = true;
|
||||
name = n;
|
||||
} else if let Some(n) = name.strip_prefix("ctrl+") {
|
||||
ctrl = true;
|
||||
name = n;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let key = match name {
|
||||
"backspace" => K::Backspace,
|
||||
"delete" => K::Delete,
|
||||
"home" => K::Home,
|
||||
"end" => K::End,
|
||||
"right" => K::ArrowRight,
|
||||
"left" => K::ArrowLeft,
|
||||
"down" => K::ArrowDown,
|
||||
"up" => K::ArrowUp,
|
||||
"tab" => K::Tab,
|
||||
"escape" => K::Escape,
|
||||
_ => K::KeyA,
|
||||
};
|
||||
if screen.key(&m, &c, &history, key, shift, ctrl) != ChatAction::None {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if closed {
|
||||
writeln!(out, "{}", json!({"closed": true}))?;
|
||||
continue;
|
||||
}
|
||||
// Options.getBackgroundColor(Integer.MIN_VALUE).
|
||||
let background = if case["chatOnly"] == true {
|
||||
i32::MIN
|
||||
} else {
|
||||
let a = (case["opacity"].as_f64().unwrap_or(0.0) as f32 * 255.0).floor() as i32;
|
||||
a << 24
|
||||
};
|
||||
let mouse = (int(&case["mouse"][0]), int(&case["mouse"][1]));
|
||||
let draws = screen.draw(&m, mouse, case["blink"].as_u64().unwrap_or(0), background);
|
||||
let input = &screen.input;
|
||||
writeln!(
|
||||
out,
|
||||
"{}",
|
||||
json!({"value": input.value, "cursor": input.cursor, "highlight": input.highlight, "display": input.display,
|
||||
"draws": pack_screen_fixture::encode(&draws)})
|
||||
)?;
|
||||
}
|
||||
fs::write(output, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! The registries VanillaCommandParseOracle exports (`registries` mode), as
|
||||
//! the command dispatcher reads them; shared by the command fixtures.
|
||||
use horizon_client::command::{Registries, args::RegistryIds};
|
||||
use serde_json::Value;
|
||||
|
||||
fn strings(v: &Value) -> Vec<String> {
|
||||
v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn registries(r: &Value, permission: u8) -> Registries {
|
||||
let mut reg = Registries {
|
||||
permission,
|
||||
..Registries::default()
|
||||
};
|
||||
reg.items = strings(&r["items"]);
|
||||
reg.item_tags = strings(&r["item_tags"]);
|
||||
reg.block_tags = strings(&r["block_tags"]);
|
||||
for (id, props) in r["blocks"].as_object().into_iter().flatten() {
|
||||
let props = props
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|p| (p[0].as_str().unwrap_or("").to_owned(), strings(&p[1])))
|
||||
.collect();
|
||||
reg.blocks.insert(id.clone(), props);
|
||||
}
|
||||
reg.summonable = strings(&r["summonable"]);
|
||||
reg.entity_types = strings(&r["entity_types"]);
|
||||
reg.effects = strings(&r["effects"]);
|
||||
reg.attributes = strings(&r["attributes"]);
|
||||
reg.sounds = strings(&r["sounds"]);
|
||||
reg.enchantments = strings(&r["enchantments"]);
|
||||
reg.structures = strings(&r["structures"]);
|
||||
reg.biomes = strings(&r["biomes"]);
|
||||
reg.damage_types = strings(&r["damage_types"]);
|
||||
reg.clocks = strings(&r["clocks"]);
|
||||
reg.timelines = strings(&r["timelines"]);
|
||||
reg.dimensions = strings(&r["dimensions"]);
|
||||
reg.players = strings(&r["players"]);
|
||||
reg.teams = strings(&r["teams"]);
|
||||
reg.objectives = strings(&r["objectives"]);
|
||||
reg.tracked = strings(&r["tracked"]);
|
||||
for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
|
||||
reg.by_registry.insert(
|
||||
name.clone(),
|
||||
RegistryIds {
|
||||
ids: strings(&entry["ids"]),
|
||||
tags: strings(&entry["tags"]),
|
||||
},
|
||||
);
|
||||
}
|
||||
reg.block_entities = strings(&r["block_entities"]).into_iter().collect();
|
||||
for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
|
||||
reg.block_tag_members.insert(tag.clone(), strings(members));
|
||||
}
|
||||
reg.templates = strings(&r["templates"]);
|
||||
reg.persistent_components = strings(&r["persistent_components"]);
|
||||
reg.learnable_recipes = strings(&r["learnable_recipes"]);
|
||||
for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
|
||||
reg.clock_time_markers
|
||||
.insert(clock.clone(), strings(markers));
|
||||
}
|
||||
for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
|
||||
reg.advancement_criteria
|
||||
.insert(id.clone(), strings(criteria));
|
||||
}
|
||||
reg.datapacks_enabled = strings(&r["datapacks_selected"]);
|
||||
let enabled = reg.datapacks_enabled.clone();
|
||||
reg.datapacks_disabled = strings(&r["datapacks_enableable"])
|
||||
.into_iter()
|
||||
.filter(|p| !enabled.contains(p))
|
||||
.collect();
|
||||
reg.advancements = reg.ids("minecraft:advancement").to_vec();
|
||||
reg.recipes = reg.ids("minecraft:recipe").to_vec();
|
||||
reg.loot_tables = reg.ids("minecraft:loot_table").to_vec();
|
||||
reg.predicates = reg.ids("minecraft:predicate").to_vec();
|
||||
reg.item_modifiers = reg.ids("minecraft:item_modifier").to_vec();
|
||||
reg
|
||||
}
|
||||
+478
-372
@@ -3,11 +3,13 @@
|
||||
//! (ChatScreen + EditBox + CommandSuggestions: history navigation, argument
|
||||
//! colouring, usage hints, parse errors and tab completion).
|
||||
use crate::{
|
||||
command::{Dispatcher, ParseResults, Registries, Suggestion},
|
||||
hud::{HudAtlas, HudBatch, rgba},
|
||||
command::{
|
||||
Dispatcher, ParseResults, Registries, Suggestion, SuggestionsBuilder, merge_suggestions,
|
||||
},
|
||||
hud::{HudAtlas, HudBatch},
|
||||
hud_layout::{self, GuiDraw, PoseOp},
|
||||
screen_draw::{self as d, Draw, Measure, TextField},
|
||||
text::{self, Style, Text},
|
||||
ui::{EditBox, char_len},
|
||||
};
|
||||
|
||||
/// GuiMessageTag.systemSinglePlayer's indicator colour.
|
||||
@@ -299,81 +301,151 @@ impl Chat {
|
||||
}
|
||||
}
|
||||
|
||||
/// CommandSuggestions.SuggestionsList.
|
||||
/// `CommandSuggestions.SuggestionsList`.
|
||||
#[derive(Clone, Debug)]
|
||||
struct SuggestionList {
|
||||
x: f32,
|
||||
width: f32,
|
||||
/// `rect`: x, y, width, height.
|
||||
rect: [i32; 4],
|
||||
original: String,
|
||||
list: Vec<Suggestion>,
|
||||
offset: usize,
|
||||
current: usize,
|
||||
original: String,
|
||||
last_mouse: (i32, i32),
|
||||
tab_cycles: bool,
|
||||
last_mouse: (f32, f32),
|
||||
}
|
||||
impl SuggestionList {
|
||||
fn contains(&self, x: i32, y: i32) -> bool {
|
||||
let [rx, ry, w, h] = self.rect;
|
||||
x >= rx && x <= rx + w && y >= ry && y <= ry + h
|
||||
}
|
||||
}
|
||||
|
||||
/// The open chat screen.
|
||||
pub struct ChatScreen {
|
||||
pub input: EditBox,
|
||||
history_pos: usize,
|
||||
history_buffer: String,
|
||||
parse: Option<ParseResults>,
|
||||
usage: Vec<Text>,
|
||||
usage_x: f32,
|
||||
suggestions: Option<SuggestionList>,
|
||||
pending: Vec<Suggestion>,
|
||||
pending_start: usize,
|
||||
keep_suggestions: bool,
|
||||
allow_suggestions: bool,
|
||||
pub auto_suggestions: bool,
|
||||
dirty: bool,
|
||||
/// What a key did on the chat screen.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ChatAction {
|
||||
None,
|
||||
/// Escape: the screen closes.
|
||||
Close,
|
||||
/// Enter: the message is sent and the screen closes.
|
||||
Submit(String),
|
||||
}
|
||||
const FILL: u32 = 0xD000_0000;
|
||||
fn fill_color() -> u32 {
|
||||
rgba(0, 0, 0, (FILL >> 24) as u8)
|
||||
|
||||
/// The dispatcher and registries the suggestions come from.
|
||||
pub struct Commands<'a> {
|
||||
pub dispatcher: &'a Dispatcher,
|
||||
pub registries: &'a Registries,
|
||||
}
|
||||
|
||||
/// The open chat screen: vanilla's `ChatScreen` with its `EditBox` and
|
||||
/// `CommandSuggestions` (argument colouring, usage lines, parse errors,
|
||||
/// the suggestion list, Tab completion, history).
|
||||
pub struct ChatScreen {
|
||||
pub input: TextField,
|
||||
width: i32,
|
||||
height: i32,
|
||||
history_buffer: String,
|
||||
history_pos: usize,
|
||||
parse: Option<ParseResults>,
|
||||
/// The completions at the cursor (`pendingSuggestions`): range start (bytes) and list.
|
||||
pending: Option<(usize, Vec<Suggestion>)>,
|
||||
suggestions: Option<SuggestionList>,
|
||||
usage: Vec<Text>,
|
||||
usage_position: i32,
|
||||
usage_width: i32,
|
||||
allow_suggestions: bool,
|
||||
keep_suggestions: bool,
|
||||
pub auto_suggestions: bool,
|
||||
}
|
||||
/// `CommandSuggestions`' fill colour.
|
||||
const FILL: i32 = -805306368;
|
||||
fn byte_at(s: &str, chars: usize) -> usize {
|
||||
s.char_indices().nth(chars).map_or(s.len(), |(i, _)| i)
|
||||
}
|
||||
fn chars_to(s: &str, byte: usize) -> usize {
|
||||
s[..byte.min(s.len())].chars().count()
|
||||
}
|
||||
/// `Mth.clamp(int)`: the minimum wins over a smaller maximum.
|
||||
fn clamp(v: i32, lo: i32, hi: i32) -> i32 {
|
||||
if v < lo { lo } else { v.min(hi) }
|
||||
}
|
||||
/// `CommandSuggestions.getLastWordIndex`: after the last whitespace run.
|
||||
fn last_word_index(s: &str) -> usize {
|
||||
let mut out = 0;
|
||||
let mut prev_space = false;
|
||||
for (i, c) in s.char_indices() {
|
||||
let space = matches!(c, ' ' | '\t' | '\n' | '\u{b}' | '\u{c}' | '\r');
|
||||
if prev_space && !space {
|
||||
out = i;
|
||||
}
|
||||
prev_space = space;
|
||||
}
|
||||
if prev_space { s.len() } else { out }
|
||||
}
|
||||
impl ChatScreen {
|
||||
pub fn new(initial: &str, history_len: usize, width: f32, height: f32) -> Self {
|
||||
let mut input = EditBox::new(4.0, height - 12.0, width - 4.0, 12.0);
|
||||
input.bordered = false;
|
||||
/// `ChatScreen.init`: the input at the bottom, focused, holding `initial`.
|
||||
pub fn new(
|
||||
m: &Measure,
|
||||
c: &Commands,
|
||||
initial: &str,
|
||||
history_len: usize,
|
||||
width: i32,
|
||||
height: i32,
|
||||
) -> Self {
|
||||
let mut input = TextField::new(4, height - 12, width - 4, 12);
|
||||
input.max_length = 256;
|
||||
input.set_value(initial);
|
||||
Self {
|
||||
input.bordered = false;
|
||||
input.focused = true;
|
||||
input.set_value(m, initial);
|
||||
let mut s = Self {
|
||||
input,
|
||||
history_pos: history_len,
|
||||
width,
|
||||
height,
|
||||
history_buffer: String::new(),
|
||||
history_pos: history_len,
|
||||
parse: None,
|
||||
usage: Vec::new(),
|
||||
usage_x: 0.0,
|
||||
pending: None,
|
||||
suggestions: None,
|
||||
pending: Vec::new(),
|
||||
pending_start: 0,
|
||||
keep_suggestions: false,
|
||||
usage: Vec::new(),
|
||||
usage_position: 0,
|
||||
usage_width: 0,
|
||||
allow_suggestions: false,
|
||||
keep_suggestions: false,
|
||||
auto_suggestions: true,
|
||||
dirty: true,
|
||||
}
|
||||
}
|
||||
/// Keep the input box at the bottom when the window resizes.
|
||||
pub fn resize(&mut self, width: f32, height: f32) {
|
||||
self.input.x = 4.0;
|
||||
self.input.y = height - 12.0;
|
||||
self.input.width = width - 4.0;
|
||||
};
|
||||
s.update_command_info(m, c);
|
||||
s
|
||||
}
|
||||
pub fn value(&self) -> &str {
|
||||
&self.input.value
|
||||
}
|
||||
/// ChatScreen.onEdited.
|
||||
pub fn edited(&mut self) {
|
||||
self.allow_suggestions = true;
|
||||
self.dirty = true;
|
||||
}
|
||||
/// CommandSuggestions.updateCommandInfo (run lazily before drawing/keys).
|
||||
pub fn update(&mut self, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries) {
|
||||
if !self.dirty {
|
||||
return;
|
||||
/// `ChatScreen.resize`: a new screen with the current text.
|
||||
pub fn resize(&mut self, m: &Measure, c: &Commands, width: i32, height: i32) {
|
||||
if (width, height) != (self.width, self.height) {
|
||||
let value = self.input.value.clone();
|
||||
let auto = self.auto_suggestions;
|
||||
*self = Self::new(m, c, &value, self.history_pos, width, height);
|
||||
self.auto_suggestions = auto;
|
||||
}
|
||||
self.dirty = false;
|
||||
}
|
||||
/// `ChatScreen.onEdited`.
|
||||
fn edited(&mut self, m: &Measure, c: &Commands) {
|
||||
self.allow_suggestions = true;
|
||||
self.update_command_info(m, c);
|
||||
}
|
||||
/// Typed text (`charTyped` per character).
|
||||
pub fn type_text(&mut self, m: &Measure, c: &Commands, text: &str) {
|
||||
for ch in text.chars() {
|
||||
if ch >= ' '
|
||||
&& ch != '\u{7f}'
|
||||
&& ch != '§'
|
||||
&& self.input.insert_text(m, &ch.to_string())
|
||||
{
|
||||
self.edited(m, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `CommandSuggestions.updateCommandInfo`.
|
||||
fn update_command_info(&mut self, m: &Measure, c: &Commands) {
|
||||
let command = self.input.value.clone();
|
||||
if self.parse.as_ref().is_some_and(|p| p.input != command) {
|
||||
self.parse = None;
|
||||
@@ -383,221 +455,234 @@ impl ChatScreen {
|
||||
self.suggestions = None;
|
||||
}
|
||||
self.usage.clear();
|
||||
self.pending.clear();
|
||||
let cursor_chars = self.input.cursor;
|
||||
let cursor = command
|
||||
.char_indices()
|
||||
.nth(cursor_chars)
|
||||
.map_or(command.len(), |(i, _)| i);
|
||||
if !command.starts_with('/') {
|
||||
return;
|
||||
}
|
||||
if self.parse.is_none() {
|
||||
self.parse = Some(d.parse_at(&command, 1, reg));
|
||||
}
|
||||
let Some(parse) = &self.parse else { return };
|
||||
if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) {
|
||||
let (range, list) = d.suggestions(parse, cursor, reg);
|
||||
self.pending = list;
|
||||
self.pending_start = range.0;
|
||||
// CommandSuggestions.updateUsageInfo.
|
||||
let mut trailing = false;
|
||||
if cursor == command.len() {
|
||||
if self.pending.is_empty() && !parse.errors.is_empty() {
|
||||
let mut literals = 0;
|
||||
for (_, e) in &parse.errors {
|
||||
if e.literal_incorrect {
|
||||
literals += 1;
|
||||
} else {
|
||||
self.usage.push(e.with_context().with_color(text::RED));
|
||||
}
|
||||
}
|
||||
if literals > 0 {
|
||||
let reader = crate::command::Reader {
|
||||
string: &parse.input,
|
||||
cursor: parse.cursor,
|
||||
};
|
||||
self.usage.push(
|
||||
crate::command::CommandError::tr_at(
|
||||
"command.unknown.argument",
|
||||
&[],
|
||||
&reader,
|
||||
)
|
||||
.with_context()
|
||||
.with_color(text::RED),
|
||||
);
|
||||
}
|
||||
} else if parse.can_read() {
|
||||
trailing = true;
|
||||
}
|
||||
let cursor = self.input.cursor;
|
||||
let cursor_b = byte_at(&command, cursor);
|
||||
if command.starts_with('/') {
|
||||
if self.parse.is_none() {
|
||||
self.parse = Some(c.dispatcher.parse_at(&command, 1, c.registries));
|
||||
}
|
||||
let (node, start, _) = parse.context.suggestion_context(cursor);
|
||||
if self.usage.is_empty() {
|
||||
let mut lines: Vec<Text> = d
|
||||
.smart_usage(node, reg.permission)
|
||||
.into_iter()
|
||||
.filter(|(n, _)| {
|
||||
!matches!(d.nodes[*n].kind, crate::command::NodeKind::Literal(_))
|
||||
})
|
||||
.map(|(_, u)| Text::colored(u, text::GRAY))
|
||||
.collect();
|
||||
if lines.is_empty()
|
||||
&& trailing
|
||||
&& let Some(e) = parse.error()
|
||||
{
|
||||
lines.push(e.with_context().with_color(text::RED));
|
||||
}
|
||||
self.usage = lines;
|
||||
}
|
||||
let usage_width = self
|
||||
.usage
|
||||
.iter()
|
||||
.map(|u| atlas.font.width_text(u))
|
||||
.fold(0.0, f32::max);
|
||||
let start_chars = char_len(&command[..start.min(command.len())]);
|
||||
self.usage_x = if self.usage.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
self.input.screen_x(atlas, start_chars).clamp(
|
||||
0.0,
|
||||
(self.input.screen_x(atlas, 0) + self.input.inner_width() - usage_width)
|
||||
.max(0.0),
|
||||
)
|
||||
};
|
||||
self.suggestions = None;
|
||||
if self.allow_suggestions && self.auto_suggestions {
|
||||
self.show_suggestions(atlas);
|
||||
if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) {
|
||||
let parse = self.parse.as_ref().expect("parsed above");
|
||||
let (range, list) = c.dispatcher.suggestions(parse, cursor_b, c.registries);
|
||||
self.pending = Some((range.0, list));
|
||||
self.update_usage_info(m, c);
|
||||
}
|
||||
} else if !command.chars().all(char::is_whitespace) {
|
||||
let partial = &command[..cursor_b];
|
||||
let mut builder = SuggestionsBuilder::new(partial, last_word_index(partial));
|
||||
builder.suggest_matching(c.registries.players.iter().map(String::as_str));
|
||||
let (range, list) = merge_suggestions(partial, builder.out);
|
||||
self.pending = Some((range.0, list));
|
||||
self.usage_width = 0;
|
||||
self.usage_position = 0;
|
||||
} else {
|
||||
self.pending = None;
|
||||
}
|
||||
}
|
||||
/// CommandSuggestions.showSuggestions.
|
||||
fn show_suggestions(&mut self, atlas: &HudAtlas) {
|
||||
if self.pending.is_empty() {
|
||||
/// `CommandSuggestions.updateUsageInfo`.
|
||||
fn update_usage_info(&mut self, m: &Measure, c: &Commands) {
|
||||
let Some(parse) = &self.parse else { return };
|
||||
let empty = self.pending.as_ref().is_none_or(|p| p.1.is_empty());
|
||||
let mut trailing = false;
|
||||
if self.input.cursor == self.input.value.chars().count() {
|
||||
if empty && !parse.errors.is_empty() {
|
||||
let mut literals = 0;
|
||||
for (_, e) in &parse.errors {
|
||||
if e.literal_incorrect {
|
||||
literals += 1;
|
||||
} else {
|
||||
self.usage.push(e.with_context());
|
||||
}
|
||||
}
|
||||
if literals > 0 {
|
||||
let reader = crate::command::Reader {
|
||||
string: &parse.input,
|
||||
cursor: parse.cursor,
|
||||
};
|
||||
self.usage.push(
|
||||
crate::command::CommandError::tr_at(
|
||||
"command.unknown.argument",
|
||||
&[],
|
||||
&reader,
|
||||
)
|
||||
.with_context(),
|
||||
);
|
||||
}
|
||||
} else if parse.can_read() {
|
||||
trailing = true;
|
||||
}
|
||||
}
|
||||
let cursor_b = byte_at(&self.input.value, self.input.cursor);
|
||||
let (node, start, _) = parse.context.suggestion_context(cursor_b);
|
||||
if self.usage.is_empty() {
|
||||
let entries: Vec<Text> = c
|
||||
.dispatcher
|
||||
.smart_usage(node, c.registries.permission)
|
||||
.into_iter()
|
||||
.filter(|(n, _)| {
|
||||
!matches!(
|
||||
c.dispatcher.nodes[*n].kind,
|
||||
crate::command::NodeKind::Literal(_)
|
||||
)
|
||||
})
|
||||
.map(|(_, u)| Text::colored(u, text::GRAY))
|
||||
.collect();
|
||||
if entries.is_empty()
|
||||
&& trailing
|
||||
&& let Some(e) = parse.error()
|
||||
{
|
||||
self.usage.push(e.with_context());
|
||||
}
|
||||
self.usage.extend(entries);
|
||||
}
|
||||
self.usage_width = self.usage.iter().map(|u| m.width(u)).max().unwrap_or(0);
|
||||
self.usage_position = if self.usage.is_empty() {
|
||||
0
|
||||
} else {
|
||||
let start = chars_to(&self.input.value, start);
|
||||
clamp(
|
||||
self.input.screen_x(m, start),
|
||||
0,
|
||||
self.input.screen_x(m, 0) + self.input.inner_width() - self.usage_width,
|
||||
)
|
||||
};
|
||||
self.suggestions = None;
|
||||
if self.allow_suggestions && self.auto_suggestions {
|
||||
self.show_suggestions(m);
|
||||
}
|
||||
}
|
||||
/// `CommandSuggestions.showSuggestions`.
|
||||
fn show_suggestions(&mut self, m: &Measure) {
|
||||
let Some((start, list)) = self.pending.clone() else {
|
||||
return;
|
||||
};
|
||||
if list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let width = list.iter().map(|s| m.width_str(&s.text)).max().unwrap_or(0);
|
||||
let value = self.input.value.clone();
|
||||
let width = self
|
||||
.pending
|
||||
.iter()
|
||||
.map(|s| atlas.font.width(&s.text))
|
||||
.fold(0.0, f32::max);
|
||||
let start_chars = char_len(&value[..self.pending_start.min(value.len())]);
|
||||
let x = self.input.screen_x(atlas, start_chars).clamp(
|
||||
0.0,
|
||||
(self.input.screen_x(atlas, 0) + self.input.inner_width() - width).max(0.0),
|
||||
let x = clamp(
|
||||
self.input.screen_x(m, chars_to(&value, start)),
|
||||
0,
|
||||
self.input.screen_x(m, 0) + self.input.inner_width() - width,
|
||||
);
|
||||
// Sort: suggestions starting with the last word first.
|
||||
let cursor = value
|
||||
.char_indices()
|
||||
.nth(self.input.cursor)
|
||||
.map_or(value.len(), |(i, _)| i);
|
||||
let partial = &value[..cursor];
|
||||
let last_word = partial.rfind(char::is_whitespace).map_or(0, |i| i + 1);
|
||||
let word = partial[last_word..].to_lowercase();
|
||||
let (mut first, partial_matches): (Vec<Suggestion>, Vec<Suggestion>) =
|
||||
self.pending.iter().cloned().partition(|s| {
|
||||
let y = self.height - 12;
|
||||
// sortSuggestions: those starting with the word at the cursor first.
|
||||
let partial = &value[..byte_at(&value, self.input.cursor)];
|
||||
let word = partial[last_word_index(partial)..].to_lowercase();
|
||||
let (mut first, rest): (Vec<Suggestion>, Vec<Suggestion>) =
|
||||
list.into_iter().partition(|s| {
|
||||
s.text.starts_with(&word) || s.text.starts_with(&format!("minecraft:{word}"))
|
||||
});
|
||||
first.extend(partial_matches);
|
||||
let mut list = SuggestionList {
|
||||
x: x - 1.0,
|
||||
width: width + 1.0,
|
||||
first.extend(rest);
|
||||
let n = first.len().min(10) as i32;
|
||||
let mut l = SuggestionList {
|
||||
rect: [x - 1, y - 3 - n * 12, width + 1, n * 12],
|
||||
original: value,
|
||||
list: first,
|
||||
offset: 0,
|
||||
current: 0,
|
||||
original: value,
|
||||
last_mouse: (0, 0),
|
||||
tab_cycles: false,
|
||||
last_mouse: (-1.0, -1.0),
|
||||
};
|
||||
self.select(&mut list, 0);
|
||||
self.suggestions = Some(list);
|
||||
self.select(&mut l, 0);
|
||||
self.suggestions = Some(l);
|
||||
}
|
||||
fn select(&mut self, list: &mut SuggestionList, index: isize) {
|
||||
let n = list.list.len() as isize;
|
||||
list.current = index.rem_euclid(n.max(1)) as usize;
|
||||
let applied = list.list[list.current].apply(&list.original);
|
||||
/// `SuggestionsList.select`: the grey completion after the text.
|
||||
fn select(&mut self, l: &mut SuggestionList, index: isize) {
|
||||
let n = l.list.len() as isize;
|
||||
let mut i = index;
|
||||
if i < 0 {
|
||||
i += n;
|
||||
}
|
||||
if i >= n {
|
||||
i -= n;
|
||||
}
|
||||
l.current = i as usize;
|
||||
let applied = l.list[l.current].apply(&l.original);
|
||||
self.input.suggestion = applied
|
||||
.strip_prefix(self.input.value.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
}
|
||||
fn cycle(&mut self, list: &mut SuggestionList, dir: isize) {
|
||||
self.select(list, list.current as isize + dir);
|
||||
let limit = 10;
|
||||
let max_offset = list.list.len().saturating_sub(limit);
|
||||
if list.current < list.offset {
|
||||
list.offset = list.current.min(max_offset);
|
||||
} else if list.current > list.offset + limit - 1 {
|
||||
list.offset = (list.current + 1).saturating_sub(limit).min(max_offset);
|
||||
fn cycle(&mut self, l: &mut SuggestionList, dir: isize) {
|
||||
self.select(l, l.current as isize + dir);
|
||||
let max = l.list.len().saturating_sub(10);
|
||||
if l.current < l.offset {
|
||||
l.offset = l.current.min(max);
|
||||
} else if l.current > l.offset + 9 {
|
||||
l.offset = (l.current as isize + 1 - 10).clamp(0, max as isize) as usize;
|
||||
}
|
||||
}
|
||||
fn use_suggestion(&mut self, list: &mut SuggestionList) {
|
||||
let s = list.list[list.current].clone();
|
||||
/// `SuggestionsList.useSuggestion`.
|
||||
fn use_suggestion(&mut self, m: &Measure, c: &Commands, l: &mut SuggestionList) {
|
||||
let s = l.list[l.current].clone();
|
||||
self.keep_suggestions = true;
|
||||
let applied = s.apply(&list.original);
|
||||
self.input.set_value(&applied);
|
||||
let end =
|
||||
char_len(&list.original[..s.range.0.min(list.original.len())]) + char_len(&s.text);
|
||||
self.input.set_cursor(end, false);
|
||||
self.dirty = true;
|
||||
self.select(list, list.current as isize);
|
||||
let value = s.apply(&l.original);
|
||||
self.suggestions = Some(l.clone());
|
||||
self.input.set_value(m, &value);
|
||||
self.edited(m, c);
|
||||
let end = chars_to(&l.original, s.range.0) + s.text.chars().count();
|
||||
self.input.set_cursor_and_highlight(m, end);
|
||||
self.select(l, l.current as isize);
|
||||
self.keep_suggestions = false;
|
||||
list.tab_cycles = true;
|
||||
l.tab_cycles = true;
|
||||
}
|
||||
/// Suggestion-list keys (CommandSuggestions.keyPressed). Returns true if handled.
|
||||
pub fn suggestion_key(
|
||||
/// `ChatScreen.keyPressed`.
|
||||
pub fn key(
|
||||
&mut self,
|
||||
atlas: &HudAtlas,
|
||||
d: &Dispatcher,
|
||||
reg: &Registries,
|
||||
m: &Measure,
|
||||
c: &Commands,
|
||||
history: &[String],
|
||||
key: winit::keyboard::KeyCode,
|
||||
shift: bool,
|
||||
) -> bool {
|
||||
ctrl: bool,
|
||||
) -> ChatAction {
|
||||
use winit::keyboard::KeyCode as K;
|
||||
self.update(atlas, d, reg);
|
||||
if let Some(mut list) = self.suggestions.take() {
|
||||
// CommandSuggestions.keyPressed.
|
||||
if let Some(mut l) = self.suggestions.take() {
|
||||
let handled = match key {
|
||||
K::ArrowUp => {
|
||||
self.cycle(&mut list, -1);
|
||||
list.tab_cycles = false;
|
||||
true
|
||||
}
|
||||
K::ArrowDown => {
|
||||
self.cycle(&mut list, 1);
|
||||
list.tab_cycles = false;
|
||||
K::ArrowUp | K::ArrowDown => {
|
||||
self.cycle(&mut l, if key == K::ArrowUp { -1 } else { 1 });
|
||||
l.tab_cycles = false;
|
||||
true
|
||||
}
|
||||
K::Tab => {
|
||||
if list.tab_cycles {
|
||||
self.cycle(&mut list, if shift { -1 } else { 1 });
|
||||
if l.tab_cycles {
|
||||
self.cycle(&mut l, if shift { -1 } else { 1 });
|
||||
}
|
||||
self.use_suggestion(&mut list);
|
||||
// Keep the list across the re-parse triggered by the edit.
|
||||
let keep = list.clone();
|
||||
self.keep_suggestions = true;
|
||||
self.update(atlas, d, reg);
|
||||
self.keep_suggestions = false;
|
||||
self.suggestions = Some(keep);
|
||||
return true;
|
||||
self.use_suggestion(m, c, &mut l);
|
||||
true
|
||||
}
|
||||
K::Escape => {
|
||||
self.input.suggestion = None;
|
||||
return true;
|
||||
return ChatAction::None;
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
self.suggestions = Some(list);
|
||||
return handled;
|
||||
self.suggestions = Some(l);
|
||||
if handled {
|
||||
return ChatAction::None;
|
||||
}
|
||||
} else if key == K::Tab {
|
||||
self.show_suggestions(m);
|
||||
return ChatAction::None;
|
||||
}
|
||||
if key == K::Tab {
|
||||
self.show_suggestions(atlas);
|
||||
return true;
|
||||
match key {
|
||||
K::Escape => return ChatAction::Close,
|
||||
K::Enter | K::NumpadEnter => return ChatAction::Submit(self.normalized()),
|
||||
K::ArrowUp => self.move_in_history(m, c, history, -1),
|
||||
K::ArrowDown => self.move_in_history(m, c, history, 1),
|
||||
_ => {
|
||||
if self.input.key(m, key, shift, ctrl) == Some(true) {
|
||||
self.edited(m, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
ChatAction::None
|
||||
}
|
||||
/// ChatScreen.moveInHistory.
|
||||
pub fn move_in_history(&mut self, recent: &[String], dir: isize) {
|
||||
let max = recent.len();
|
||||
/// `ChatScreen.moveInHistory`.
|
||||
fn move_in_history(&mut self, m: &Measure, c: &Commands, history: &[String], dir: isize) {
|
||||
let max = history.len();
|
||||
let new = (self.history_pos as isize + dir).clamp(0, max as isize) as usize;
|
||||
if new == self.history_pos {
|
||||
return;
|
||||
@@ -605,55 +690,70 @@ impl ChatScreen {
|
||||
if new == max {
|
||||
self.history_pos = max;
|
||||
let b = self.history_buffer.clone();
|
||||
self.input.set_value(&b);
|
||||
self.input.set_value(m, &b);
|
||||
self.edited(m, c);
|
||||
} else {
|
||||
if self.history_pos == max {
|
||||
self.history_buffer = self.input.value.clone();
|
||||
}
|
||||
self.input.set_value(&recent[new]);
|
||||
self.suggestions = None;
|
||||
self.input.set_value(m, &history[new]);
|
||||
self.edited(m, c);
|
||||
self.allow_suggestions = false;
|
||||
self.suggestions = None;
|
||||
self.history_pos = new;
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
/// Mouse wheel over the suggestion list.
|
||||
pub fn scroll_suggestions(&mut self, cursor: (f32, f32), height: f32, amount: f32) -> bool {
|
||||
let Some(list) = &mut self.suggestions else {
|
||||
return false;
|
||||
};
|
||||
let n = list.list.len().min(10);
|
||||
let top = height - 12.0 - 3.0 - n as f32 * 12.0;
|
||||
if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) {
|
||||
let max = list.list.len().saturating_sub(10) as isize;
|
||||
list.offset = (list.offset as isize - amount.signum() as isize).clamp(0, max) as usize;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// Click on a suggestion row.
|
||||
pub fn click(&mut self, cursor: (f32, f32), height: f32) -> bool {
|
||||
let Some(mut list) = self.suggestions.take() else {
|
||||
return false;
|
||||
};
|
||||
let n = list.list.len().min(10);
|
||||
let top = height - 12.0 - 3.0 - n as f32 * 12.0;
|
||||
if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) {
|
||||
let row = ((cursor.1 - top) / 12.0) as usize + list.offset;
|
||||
if row < list.list.len() {
|
||||
self.select(&mut list, row as isize);
|
||||
self.use_suggestion(&mut list);
|
||||
/// A left click (`ChatScreen.mouseClicked`): a suggestion, else the input.
|
||||
pub fn click(&mut self, m: &Measure, c: &Commands, x: f64, y: f64) -> bool {
|
||||
if let Some(mut l) = self.suggestions.take() {
|
||||
let (xi, yi) = (x as i32, y as i32);
|
||||
if l.contains(xi, yi) {
|
||||
let line = (yi - l.rect[1]) / 12 + l.offset as i32;
|
||||
if line >= 0 && (line as usize) < l.list.len() {
|
||||
self.select(&mut l, line as isize);
|
||||
self.use_suggestion(m, c, &mut l);
|
||||
}
|
||||
self.suggestions = Some(l);
|
||||
return true;
|
||||
}
|
||||
self.suggestions = Some(list);
|
||||
self.suggestions = Some(l);
|
||||
}
|
||||
if self.input.contains(x, y) {
|
||||
self.input.click(m, x, false);
|
||||
return true;
|
||||
}
|
||||
self.suggestions = Some(list);
|
||||
false
|
||||
}
|
||||
/// CommandSuggestions.formatText: argument colours over the input.
|
||||
fn formatted(&self) -> Option<Text> {
|
||||
let parse = self.parse.as_ref()?;
|
||||
let value = &self.input.value;
|
||||
/// The mouse wheel over the suggestion list (`SuggestionsList.mouseScrolled`).
|
||||
pub fn scroll(&mut self, mouse: (i32, i32), amount: f64) -> bool {
|
||||
let Some(l) = &mut self.suggestions else {
|
||||
return false;
|
||||
};
|
||||
if !l.contains(mouse.0, mouse.1) {
|
||||
return false;
|
||||
}
|
||||
let max = l.list.len().saturating_sub(10) as i32;
|
||||
l.offset = ((l.offset as f64 - amount.clamp(-1.0, 1.0)) as i32).clamp(0, max) as usize;
|
||||
true
|
||||
}
|
||||
/// `CommandSuggestions.formatText`: argument colours over the input.
|
||||
fn format(&self, value: &str, offset: usize) -> Text {
|
||||
let gray = Style::color(text::GRAY);
|
||||
let Some(parse) = &self.parse else {
|
||||
return Text::literal(value);
|
||||
};
|
||||
let full = &self.input.value;
|
||||
let chars = |b: usize| chars_to(full, b) as isize;
|
||||
let len = value.chars().count() as isize;
|
||||
let piece = |from: isize, to: isize| -> String {
|
||||
value
|
||||
.chars()
|
||||
.skip(from as usize)
|
||||
.take((to - from).max(0) as usize)
|
||||
.collect()
|
||||
};
|
||||
let mut out = Text::empty();
|
||||
let mut unformatted = 0isize;
|
||||
let styles = [
|
||||
text::AQUA,
|
||||
text::YELLOW,
|
||||
@@ -661,128 +761,134 @@ impl ChatScreen {
|
||||
text::LIGHT_PURPLE,
|
||||
text::GOLD,
|
||||
];
|
||||
let mut colors = vec![text::GRAY; value.len()];
|
||||
let ctx = parse.context.last_child();
|
||||
for (i, arg) in ctx.args.iter().enumerate() {
|
||||
let c = styles[i % styles.len()];
|
||||
for b in arg.range.0.min(value.len())..arg.range.1.min(value.len()) {
|
||||
colors[b] = c;
|
||||
for (i, arg) in parse.context.last_child().args.iter().enumerate() {
|
||||
let start = (chars(arg.range.0) - offset as isize).max(0);
|
||||
if start >= len {
|
||||
break;
|
||||
}
|
||||
let end = (chars(arg.range.1) - offset as isize).min(len);
|
||||
if end > 0 {
|
||||
out.push(Text::styled(piece(unformatted, start), gray.clone()));
|
||||
out.push(Text::styled(
|
||||
piece(start, end),
|
||||
Style::color(styles[i % styles.len()]),
|
||||
));
|
||||
unformatted = end;
|
||||
}
|
||||
}
|
||||
if parse.can_read() {
|
||||
for c in colors.iter_mut().skip(parse.cursor) {
|
||||
*c = text::RED;
|
||||
let start = (chars(parse.cursor) - offset as isize).max(0);
|
||||
if start < len {
|
||||
let remaining = (full.len() - parse.cursor.min(full.len())) as isize;
|
||||
let end = (start + full[parse.cursor.min(full.len())..].chars().count() as isize)
|
||||
.min(len);
|
||||
let _ = remaining;
|
||||
out.push(Text::styled(piece(unformatted, start), gray.clone()));
|
||||
out.push(Text::styled(piece(start, end), Style::color(text::RED)));
|
||||
unformatted = end;
|
||||
}
|
||||
}
|
||||
let mut out = Text::empty();
|
||||
for (i, ch) in value.char_indices() {
|
||||
out.push(Text::styled(ch.to_string(), Style::color(colors[i])));
|
||||
}
|
||||
Some(out)
|
||||
out.push(Text::styled(piece(unformatted, len), gray));
|
||||
out
|
||||
}
|
||||
/// ChatScreen.extractRenderState minus the chat lines.
|
||||
/// `ChatScreen.extractRenderState` without the chat lines: the input's
|
||||
/// background (`background`, `Options.getBackgroundColor`), the input,
|
||||
/// then the suggestion list or the usage lines.
|
||||
pub fn draw(
|
||||
&mut self,
|
||||
batch: &mut HudBatch,
|
||||
atlas: &HudAtlas,
|
||||
d: &Dispatcher,
|
||||
reg: &Registries,
|
||||
cursor: (f32, f32),
|
||||
background_opacity: f32,
|
||||
) {
|
||||
self.update(atlas, d, reg);
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
batch.fill(
|
||||
atlas,
|
||||
2.0,
|
||||
h - 14.0,
|
||||
w - 4.0,
|
||||
12.0,
|
||||
rgba(0, 0, 0, (background_opacity * 255.0) as u8),
|
||||
);
|
||||
let formatted = self.formatted();
|
||||
self.input.draw(batch, atlas, formatted.as_ref());
|
||||
let fill = fill_color();
|
||||
if let Some(mut list) = self.suggestions.take() {
|
||||
let limit = list.list.len().min(10);
|
||||
let top = h - 12.0 - 3.0 - limit as f32 * 12.0;
|
||||
let has_prev = list.offset > 0;
|
||||
let has_next = list.list.len() > list.offset + limit;
|
||||
let moved = list.last_mouse != cursor;
|
||||
list.last_mouse = cursor;
|
||||
if has_prev || has_next {
|
||||
batch.fill(atlas, list.x, top - 1.0, list.width, 1.0, fill);
|
||||
batch.fill(
|
||||
atlas,
|
||||
list.x,
|
||||
top + limit as f32 * 12.0,
|
||||
list.width,
|
||||
1.0,
|
||||
fill,
|
||||
);
|
||||
for x in (0..list.width as i32).step_by(2) {
|
||||
if has_prev {
|
||||
batch.fill(atlas, list.x + x as f32, top - 1.0, 1.0, 1.0, u32::MAX);
|
||||
}
|
||||
if has_next {
|
||||
batch.fill(
|
||||
atlas,
|
||||
list.x + x as f32,
|
||||
top + limit as f32 * 12.0,
|
||||
1.0,
|
||||
1.0,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut hovered_row = None;
|
||||
for i in 0..limit {
|
||||
let y = top + 12.0 * i as f32;
|
||||
batch.fill(atlas, list.x, y, list.width, 12.0, fill);
|
||||
if cursor.0 > list.x
|
||||
&& cursor.0 < list.x + list.width
|
||||
&& cursor.1 > y
|
||||
&& cursor.1 < y + 12.0
|
||||
{
|
||||
hovered_row = Some(i + list.offset);
|
||||
}
|
||||
}
|
||||
if moved && let Some(r) = hovered_row {
|
||||
self.select(&mut list, r as isize);
|
||||
}
|
||||
for i in 0..limit {
|
||||
let s = &list.list[i + list.offset];
|
||||
let color = if i + list.offset == list.current {
|
||||
rgba(255, 255, 0, 255)
|
||||
} else {
|
||||
rgba(0xAA, 0xAA, 0xAA, 255)
|
||||
};
|
||||
batch.text(
|
||||
atlas,
|
||||
&s.text,
|
||||
list.x + 1.0,
|
||||
top + 2.0 + 12.0 * i as f32,
|
||||
color,
|
||||
true,
|
||||
);
|
||||
}
|
||||
if hovered_row.is_some()
|
||||
&& let Some(tip) = &list.list[list.current].tooltip
|
||||
{
|
||||
crate::ui::tooltip(batch, atlas, &[Text::literal(tip.clone())], cursor);
|
||||
}
|
||||
self.suggestions = Some(list);
|
||||
m: &Measure,
|
||||
mouse: (i32, i32),
|
||||
blink_ms: u64,
|
||||
background: i32,
|
||||
) -> Vec<Draw> {
|
||||
let (w, h) = (self.width, self.height);
|
||||
let mut out = Vec::new();
|
||||
d::fill(&mut out, 2, h - 14, w - 2, h - 2, background);
|
||||
let format = |s: &str, o: usize| self.format(s, o);
|
||||
self.input.draw(&mut out, m, blink_ms, Some(&format));
|
||||
if let Some(mut l) = self.suggestions.take() {
|
||||
self.draw_list(&mut out, m, &mut l, mouse);
|
||||
self.suggestions = Some(l);
|
||||
} else {
|
||||
for (i, line) in self.usage.iter().enumerate() {
|
||||
let y = h - 27.0 - 12.0 * i as f32;
|
||||
let width = atlas.font.width_text(line);
|
||||
batch.fill(atlas, self.usage_x - 1.0, y, width + 2.0, 12.0, fill);
|
||||
batch.text_styled(atlas, line, self.usage_x, y + 2.0, u32::MAX, true);
|
||||
let y = h - 27 - 12 * i as i32;
|
||||
d::fill(
|
||||
&mut out,
|
||||
self.usage_position - 1,
|
||||
y,
|
||||
self.usage_position + self.usage_width + 1,
|
||||
y + 12,
|
||||
FILL,
|
||||
);
|
||||
d::text(&mut out, line.clone(), self.usage_position, y + 2, -1, true);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// ChatScreen.normalizeChatMessage.
|
||||
fn draw_list(
|
||||
&mut self,
|
||||
out: &mut Vec<Draw>,
|
||||
m: &Measure,
|
||||
l: &mut SuggestionList,
|
||||
mouse: (i32, i32),
|
||||
) {
|
||||
let limit = l.list.len().min(10);
|
||||
let [rx, ry, rw, rh] = l.rect;
|
||||
let has_prev = l.offset > 0;
|
||||
let has_next = l.list.len() > l.offset + limit;
|
||||
let moved = l.last_mouse != mouse;
|
||||
if moved {
|
||||
l.last_mouse = mouse;
|
||||
}
|
||||
if has_prev || has_next {
|
||||
d::fill(out, rx, ry - 1, rx + rw, ry, FILL);
|
||||
d::fill(out, rx, ry + rh, rx + rw, ry + rh + 1, FILL);
|
||||
if has_prev {
|
||||
for x in (0..rw).step_by(2) {
|
||||
d::fill(out, rx + x, ry - 1, rx + x + 1, ry, -1);
|
||||
}
|
||||
}
|
||||
if has_next {
|
||||
for x in (0..rw).step_by(2) {
|
||||
d::fill(out, rx + x, ry + rh, rx + x + 1, ry + rh + 1, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut hovered = false;
|
||||
for i in 0..limit {
|
||||
let y = ry + 12 * i as i32;
|
||||
d::fill(out, rx, y, rx + rw, y + 12, FILL);
|
||||
if mouse.0 > rx && mouse.0 < rx + rw && mouse.1 > y && mouse.1 < y + 12 {
|
||||
if moved {
|
||||
self.select(l, (i + l.offset) as isize);
|
||||
}
|
||||
hovered = true;
|
||||
}
|
||||
let s = &l.list[i + l.offset];
|
||||
let color = if i + l.offset == l.current {
|
||||
-256
|
||||
} else {
|
||||
-5592406
|
||||
};
|
||||
d::text(
|
||||
out,
|
||||
Text::literal(s.text.clone()),
|
||||
rx + 1,
|
||||
ry + 2 + 12 * i as i32,
|
||||
color,
|
||||
true,
|
||||
);
|
||||
}
|
||||
if hovered && let Some(tip) = &l.list[l.current].tooltip {
|
||||
out.push(Draw::Tooltip {
|
||||
lines: vec![Text::literal(tip.clone())],
|
||||
x: mouse.0,
|
||||
y: mouse.1,
|
||||
});
|
||||
}
|
||||
let _ = m;
|
||||
}
|
||||
/// `ChatScreen.normalizeChatMessage`.
|
||||
pub fn normalized(&self) -> String {
|
||||
let collapsed = self
|
||||
.input
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
//! (game rules, the world clock, difficulty), bound to the game.
|
||||
use super::{Dim, Game, Screen};
|
||||
use horizon_client::{
|
||||
chat::{Chat, ChatScreen, SYSTEM_INDICATOR},
|
||||
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
|
||||
command::{Registries, vanilla},
|
||||
gamerules::GameRules,
|
||||
hud::{HudBatch, rgba},
|
||||
screen_draw::Measure,
|
||||
text::Text,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
@@ -63,6 +64,8 @@ impl TimeMarker {
|
||||
pub struct UiState {
|
||||
pub chat: Chat,
|
||||
pub chat_screen: Option<ChatScreen>,
|
||||
/// When the chat screen opened (its input took the focus: the cursor blink).
|
||||
pub chat_opened: Option<std::time::Instant>,
|
||||
pub registries: Registries,
|
||||
pub rules: GameRules,
|
||||
pub clock: WorldClock,
|
||||
@@ -368,9 +371,22 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.map_or([1280, 720], |r| [r.config.width, r.config.height]);
|
||||
let b = HudBatch::new(size);
|
||||
let mut screen = ChatScreen::new(initial, self.ui.chat.recent.len(), b.width, b.height);
|
||||
screen.auto_suggestions = true;
|
||||
let m = Measure(&self.res.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::game_dispatcher(),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
let mut screen = ChatScreen::new(
|
||||
&m,
|
||||
&c,
|
||||
initial,
|
||||
self.ui.chat.recent.len(),
|
||||
b.width as i32,
|
||||
b.height as i32,
|
||||
);
|
||||
screen.auto_suggestions = self.settings.auto_suggestions;
|
||||
self.ui.chat_screen = Some(screen);
|
||||
self.ui.chat_opened = Some(std::time::Instant::now());
|
||||
self.screen = Screen::Chat;
|
||||
self.keys.clear();
|
||||
self.left = false;
|
||||
@@ -413,63 +429,59 @@ impl Game<'_> {
|
||||
self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight);
|
||||
let shift =
|
||||
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
|
||||
match key {
|
||||
// ChatScreen.keyPressed: the chat scrolls a page.
|
||||
KeyCode::PageUp | KeyCode::PageDown
|
||||
if !self
|
||||
.ui
|
||||
.chat_screen
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.suggestions_visible()) =>
|
||||
{
|
||||
let n = self.ui.chat.lines_per_page(true) as i32 - 1;
|
||||
self.ui
|
||||
.chat
|
||||
.scroll_by(if key == KeyCode::PageUp { n } else { -n }, true);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(mut screen) = self.ui.chat_screen.take() else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let d = vanilla::game_dispatcher();
|
||||
if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) {
|
||||
self.ui.chat_screen = Some(screen);
|
||||
return;
|
||||
}
|
||||
let mut close = false;
|
||||
let mut submit = None;
|
||||
match key {
|
||||
KeyCode::Escape => close = true,
|
||||
KeyCode::Enter | KeyCode::NumpadEnter => {
|
||||
submit = Some(screen.normalized());
|
||||
close = true;
|
||||
}
|
||||
KeyCode::ArrowUp => screen.move_in_history(&self.ui.chat.recent, -1),
|
||||
KeyCode::ArrowDown => screen.move_in_history(&self.ui.chat.recent, 1),
|
||||
KeyCode::PageUp => {
|
||||
let n = self.ui.chat.lines_per_page(true) as i32 - 1;
|
||||
self.ui.chat.scroll_by(n, true);
|
||||
}
|
||||
KeyCode::PageDown => {
|
||||
let n = self.ui.chat.lines_per_page(true) as i32 - 1;
|
||||
self.ui.chat.scroll_by(-n, true);
|
||||
}
|
||||
_ => {
|
||||
if screen.input.key(key, ctrl, shift) {
|
||||
screen.edited();
|
||||
} else if let Some(text) = typed_text
|
||||
&& !ctrl
|
||||
{
|
||||
let typed: String = text.chars().filter(|c| !c.is_control()).collect();
|
||||
if !typed.is_empty() {
|
||||
screen.input.insert_text(&typed);
|
||||
screen.edited();
|
||||
}
|
||||
let m = Measure(&self.res.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::game_dispatcher(),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) {
|
||||
ChatAction::Close => self.close_chat(),
|
||||
ChatAction::Submit(message) => {
|
||||
self.close_chat();
|
||||
if !message.is_empty() {
|
||||
self.handle_chat_input(&message);
|
||||
}
|
||||
}
|
||||
}
|
||||
if close {
|
||||
self.close_chat();
|
||||
} else {
|
||||
self.ui.chat_screen = Some(screen);
|
||||
}
|
||||
if let Some(message) = submit
|
||||
&& !message.is_empty()
|
||||
{
|
||||
self.handle_chat_input(&message);
|
||||
ChatAction::None => {
|
||||
// charTyped: the text the key typed.
|
||||
if let Some(text) = typed_text
|
||||
&& !ctrl
|
||||
{
|
||||
screen.type_text(&m, &c, text);
|
||||
}
|
||||
self.ui.chat_screen = Some(screen);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Text typed into the chat box (control socket `chat`).
|
||||
pub(super) fn chat_type(&mut self, text: &str) {
|
||||
let m = Measure(&self.res.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::game_dispatcher(),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
screen.input.insert_text(text);
|
||||
screen.edited();
|
||||
screen.type_text(&m, &c, text);
|
||||
}
|
||||
}
|
||||
/// ChatScreen.handleChatInput: history, then a command or a chat line.
|
||||
@@ -494,8 +506,10 @@ impl Game<'_> {
|
||||
let height = self.renderer.as_ref().map_or(720.0, |r| {
|
||||
HudBatch::new([r.config.width, r.config.height]).height
|
||||
});
|
||||
let _ = height;
|
||||
let mouse = (cursor.0.floor() as i32, cursor.1.floor() as i32);
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut()
|
||||
&& screen.scroll_suggestions(cursor, height, amount)
|
||||
&& screen.scroll(mouse, amount as f64)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -508,12 +522,14 @@ impl Game<'_> {
|
||||
let height = self.renderer.as_ref().map_or(720.0, |r| {
|
||||
HudBatch::new([r.config.width, r.config.height]).height
|
||||
});
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut()
|
||||
&& !screen.click(cursor, height)
|
||||
&& screen.input.y <= cursor.1
|
||||
{
|
||||
let i = screen.input.index_at(&self.res.atlas, cursor.0);
|
||||
screen.input.set_cursor(i, false);
|
||||
let _ = height;
|
||||
let m = Measure(&self.res.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::game_dispatcher(),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64);
|
||||
}
|
||||
}
|
||||
/// Chat lines over the HUD (focused while the chat screen is open).
|
||||
@@ -530,16 +546,25 @@ impl Game<'_> {
|
||||
let Some(mut screen) = self.ui.chat_screen.take() else {
|
||||
return;
|
||||
};
|
||||
screen.resize(batch.width, batch.height);
|
||||
let bg = self.ui.chat.options.background_opacity as f32;
|
||||
screen.draw(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
vanilla::game_dispatcher(),
|
||||
&self.ui.registries,
|
||||
self.cursor,
|
||||
bg,
|
||||
);
|
||||
let m = Measure(&self.res.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::game_dispatcher(),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
screen.resize(&m, &c, batch.width as i32, batch.height as i32);
|
||||
// Options.getBackgroundColor(Integer.MIN_VALUE).
|
||||
let background = if self.settings.file.bool("backgroundForChatOnly") {
|
||||
i32::MIN
|
||||
} else {
|
||||
self.settings.text_background(0.0) as i32
|
||||
};
|
||||
let mouse = (self.cursor.0.floor() as i32, self.cursor.1.floor() as i32);
|
||||
let blink = self
|
||||
.ui
|
||||
.chat_opened
|
||||
.map_or(0, |t| t.elapsed().as_millis() as u64);
|
||||
let draws = screen.draw(&m, mouse, blink, background);
|
||||
horizon_client::screen_draw::paint(batch, &self.res.atlas, &draws);
|
||||
self.ui.chat_screen = Some(screen);
|
||||
}
|
||||
/// Advance the overworld clock (ServerClockManager.tick) when
|
||||
|
||||
@@ -599,6 +599,87 @@ impl TextField {
|
||||
}
|
||||
self.display = display.clamp(0, len as isize) as usize;
|
||||
}
|
||||
/// `getWordPosition(dir, from)`: past the next space run, or back to the
|
||||
/// start of the word.
|
||||
pub fn word_position(&self, dir: isize, from: usize) -> usize {
|
||||
let v: Vec<char> = self.value.chars().collect();
|
||||
let mut at = from;
|
||||
if dir > 0 {
|
||||
at = v
|
||||
.iter()
|
||||
.skip(at)
|
||||
.position(|c| *c == ' ')
|
||||
.map_or(v.len(), |p| p + at);
|
||||
while at < v.len() && v[at] == ' ' {
|
||||
at += 1;
|
||||
}
|
||||
} else {
|
||||
while at > 0 && v[at - 1] == ' ' {
|
||||
at -= 1;
|
||||
}
|
||||
while at > 0 && v[at - 1] != ' ' {
|
||||
at -= 1;
|
||||
}
|
||||
}
|
||||
at
|
||||
}
|
||||
/// `keyPressed` of a focused, editable box: `Some(changed)` when handled.
|
||||
pub fn key(
|
||||
&mut self,
|
||||
m: &Measure,
|
||||
key: winit::keyboard::KeyCode,
|
||||
shift: bool,
|
||||
ctrl: bool,
|
||||
) -> Option<bool> {
|
||||
use winit::keyboard::KeyCode as K;
|
||||
let len = chars(&self.value);
|
||||
match key {
|
||||
K::Backspace | K::Delete => {
|
||||
let dir = if key == K::Backspace { -1 } else { 1 };
|
||||
if !ctrl {
|
||||
return Some(self.delete_chars(m, dir));
|
||||
}
|
||||
// deleteWords.
|
||||
if self.value.is_empty() {
|
||||
return Some(false);
|
||||
}
|
||||
if self.highlight != self.cursor {
|
||||
return Some(self.insert_text(m, ""));
|
||||
}
|
||||
let to = self.word_position(dir, self.cursor);
|
||||
return Some(self.delete_chars(m, to as isize - self.cursor as isize));
|
||||
}
|
||||
K::Home => self.move_cursor_to(m, 0, shift),
|
||||
K::End => self.move_cursor_to(m, len, shift),
|
||||
K::ArrowRight | K::ArrowLeft => {
|
||||
let dir = if key == K::ArrowRight { 1 } else { -1 };
|
||||
let to = if ctrl {
|
||||
self.word_position(dir, self.cursor)
|
||||
} else {
|
||||
(self.cursor as isize + dir).clamp(0, len as isize) as usize
|
||||
};
|
||||
self.move_cursor_to(m, to, shift);
|
||||
}
|
||||
K::KeyA if ctrl && !shift => {
|
||||
self.move_cursor_to(m, len, false);
|
||||
self.set_highlight(m, 0);
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
/// `getScreenX`: where a character index is drawn, from the box's left.
|
||||
pub fn screen_x(&self, m: &Measure, index: usize) -> i32 {
|
||||
if index > chars(&self.value) {
|
||||
return self.x;
|
||||
}
|
||||
self.x + m.width_str(&sub(&self.value, 0, index))
|
||||
}
|
||||
/// `setCursorPosition` then `setHighlightPos`.
|
||||
pub fn set_cursor_and_highlight(&mut self, m: &Measure, pos: usize) {
|
||||
self.set_cursor(m, pos);
|
||||
self.set_highlight(m, pos);
|
||||
}
|
||||
/// `onClick`: the cursor where the mouse is (`findClickedPositionInText`).
|
||||
pub fn click(&mut self, m: &Measure, x: f64, extend: bool) {
|
||||
let pos = (x.floor() as i32 - self.text_x()).min(self.inner_width());
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.brigadier.tree.RootCommandNode;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.InputType;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.OptionInstance;
|
||||
import net.minecraft.client.Options;
|
||||
import net.minecraft.client.gui.Hud;
|
||||
import net.minecraft.client.gui.components.CommandSuggestions;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Renderable;
|
||||
import net.minecraft.client.gui.components.ChatComponent;
|
||||
import net.minecraft.client.gui.screens.ChatScreen;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.input.CharacterEvent;
|
||||
import net.minecraft.client.input.KeyEvent;
|
||||
import net.minecraft.client.input.MouseButtonEvent;
|
||||
import net.minecraft.client.input.MouseButtonInfo;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.client.multiplayer.ClientSuggestionProvider;
|
||||
import net.minecraft.client.multiplayer.chat.ChatAbilities;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.commands.CommandBuildContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundCommandsPacket;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.ReloadableServerRegistries;
|
||||
import net.minecraft.server.ServerScoreboard;
|
||||
import net.minecraft.server.dedicated.DedicatedServer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.server.permissions.PermissionLevel;
|
||||
import net.minecraft.server.permissions.PermissionSet;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.util.ArrayListDeque;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.joml.Matrix3x2fStack;
|
||||
|
||||
/**
|
||||
* Original oracle for the chat screen's input: a real ChatScreen (its
|
||||
* EditBox and CommandSuggestions) on a client command tree made as the game
|
||||
* makes it (the server's tree filtered for an operator, sent through
|
||||
* ClientboundCommandsPacket), with suggestions a node asks the server for
|
||||
* answered by the server's dispatcher (as
|
||||
* ServerGamePacketListenerImpl.handleCustomCommandSuggestions does). The
|
||||
* case's sent-message history, typed characters, keys and clicks drive it;
|
||||
* then ChatScreen.extractRenderState without the chat lines (the input's
|
||||
* background, the EditBox, the suggestion list or usage) is recorded.
|
||||
*
|
||||
* Input lines: case JSON. Output lines: {value, cursor, highlight, display, draws} or {closed} or {error}.
|
||||
*/
|
||||
public final class VanillaChatScreenOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
static CommandDispatcher<CommandSourceStack> server;
|
||||
static CommandSourceStack source;
|
||||
static RegistryAccess access;
|
||||
static HolderLookup.Provider lookup;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T alloc(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
|
||||
VanillaPackScreenOracle.put(target, owner, name, value);
|
||||
}
|
||||
|
||||
static Object get(Object target, Class<?> owner, String name) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f.get(target);
|
||||
}
|
||||
|
||||
static <T> OptionInstance<T> option(T value) throws Exception {
|
||||
@SuppressWarnings("unchecked") OptionInstance<T> o = alloc(OptionInstance.class);
|
||||
put(o, OptionInstance.class, "value", value);
|
||||
return o;
|
||||
}
|
||||
|
||||
/** The client's suggestion provider; what it asks the server is answered at once. */
|
||||
public static final class Provider extends ClientSuggestionProvider {
|
||||
private Provider() { super(null, null, null); }
|
||||
@Override public Collection<String> getOnlinePlayerNames() { return new ArrayList<>(List.of(VanillaCommandParseOracle.PLAYERS)); }
|
||||
@Override public Collection<String> getCustomTabSuggestions() { return getOnlinePlayerNames(); }
|
||||
@Override public Collection<String> getSelectedEntities() { return List.of(); }
|
||||
@Override public Collection<String> getAllTeams() { return new ArrayList<>(List.of(VanillaCommandParseOracle.TEAMS)); }
|
||||
@Override public java.util.stream.Stream<Identifier> getAvailableSounds() { return BuiltInRegistries.SOUND_EVENT.keySet().stream(); }
|
||||
@Override public java.util.stream.Stream<Identifier> getAvailablePostEffects() { return source.getAvailablePostEffects(); }
|
||||
/** ClientPacketListener's: the player's (an operator's) and ALLOW_RESTRICTED_COMMANDS. */
|
||||
@Override public PermissionSet permissions() {
|
||||
try {
|
||||
Field allow = ClientPacketListener.class.getDeclaredField("ALLOW_RESTRICTED_COMMANDS");
|
||||
allow.setAccessible(true);
|
||||
return LevelBasedPermissionSet.forLevel(PermissionLevel.byId(4)).union((PermissionSet) allow.get(null));
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
@Override public Collection<SharedSuggestionProvider.TextCoordinates> getRelevantCoordinates() { return source.getRelevantCoordinates(); }
|
||||
@Override public Collection<SharedSuggestionProvider.TextCoordinates> getAbsoluteCoordinates() { return source.getAbsoluteCoordinates(); }
|
||||
@Override public Set<ResourceKey<Level>> levels() { return source.levels(); }
|
||||
@Override public RegistryAccess registryAccess() { return access; }
|
||||
@Override public FeatureFlagSet enabledFeatures() { return FeatureFlags.VANILLA_SET; }
|
||||
@Override public <E> CompletableFuture<Suggestions> suggestRegistryElements(ResourceKey<? extends Registry<E>> key,
|
||||
SharedSuggestionProvider.ElementSuggestionType elements, SuggestionsBuilder builder, CommandContext<?> context, java.util.function.Predicate<E> filter) {
|
||||
return source.suggestRegistryElements(key, elements, builder, context, filter);
|
||||
}
|
||||
@Override public CompletableFuture<Suggestions> customSuggestion(CommandContext<?> context) {
|
||||
StringReader reader = new StringReader(context.getInput());
|
||||
if (reader.canRead() && reader.peek() == '/') reader.skip();
|
||||
return CompletableFuture.completedFuture(server.getCompletionSuggestions(server.parse(reader, source)).join());
|
||||
}
|
||||
}
|
||||
|
||||
/** Recent messages only; the chat lines are compared by the HUD harness. */
|
||||
public static final class Chat extends ChatComponent {
|
||||
private Chat() { super(null); }
|
||||
@Override public void resetChatScroll() { }
|
||||
@Override public void discardDraft() { }
|
||||
@Override public void saveAsDraft(String text) { }
|
||||
@Override public void captureClickableText(net.minecraft.client.gui.ActiveTextCollector output, int screenHeight, int ticks,
|
||||
ChatComponent.DisplayMode mode) { }
|
||||
}
|
||||
|
||||
public static final class NoNarrator extends net.minecraft.client.GameNarrator {
|
||||
private NoNarrator() { super(null); }
|
||||
@Override public void saySystemNow(Component message) { }
|
||||
@Override public void saySystemNow(String message) { }
|
||||
}
|
||||
|
||||
/** VanillaCommandParseOracle's server state: the dispatcher and an operator's source. */
|
||||
static void server() throws Exception {
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
var dims = RegistryDataLoader.load(resources, java.util.stream.Stream.concat(context.stream(), world.listRegistries()).toList(), RegistryDataLoader.DIMENSION_REGISTRIES, Runnable::run).join();
|
||||
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world, dims);
|
||||
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
|
||||
var managers = net.minecraft.server.ReloadableServerResources.loadResources(
|
||||
resources, worldLayers, staticTags, FeatureFlags.VANILLA_SET, Commands.CommandSelection.INTEGRATED,
|
||||
LevelBasedPermissionSet.GAMEMASTER, Runnable::run, Runnable::run).join();
|
||||
lookup = loaded.lookupWithUpdatedTags();
|
||||
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
|
||||
access = loaded.layers().compositeAccess();
|
||||
Commands commands = new Commands(Commands.CommandSelection.INTEGRATED, CommandBuildContext.simple(lookup, FeatureFlags.VANILLA_SET));
|
||||
server = commands.getDispatcher();
|
||||
MinecraftServer mcs = alloc(DedicatedServer.class);
|
||||
put(mcs, MinecraftServer.class, "registries", loaded.layers());
|
||||
Class<?> reloadable = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources");
|
||||
var reloadableCtor = reloadable.getDeclaredConstructor(net.minecraft.server.packs.resources.CloseableResourceManager.class, net.minecraft.server.ReloadableServerResources.class);
|
||||
reloadableCtor.setAccessible(true);
|
||||
put(mcs, MinecraftServer.class, "resources", reloadableCtor.newInstance(resources, managers));
|
||||
put(mcs, MinecraftServer.class, "functionManager", new net.minecraft.server.ServerFunctionManager(mcs, managers.getFunctionLibrary()));
|
||||
put(mcs, MinecraftServer.class, "packRepository", repo);
|
||||
put(mcs, MinecraftServer.class, "commandStorage", new net.minecraft.world.level.storage.CommandStorage(null));
|
||||
var stopwatchesCtor = net.minecraft.world.Stopwatches.class.getDeclaredConstructor();
|
||||
stopwatchesCtor.setAccessible(true);
|
||||
put(mcs, MinecraftServer.class, "stopwatches", stopwatchesCtor.newInstance());
|
||||
put(mcs, MinecraftServer.class, "customBossEvents", new net.minecraft.server.bossevents.CustomBossEvents());
|
||||
put(mcs, MinecraftServer.class, "randomSequences", new net.minecraft.world.RandomSequences());
|
||||
put(mcs, MinecraftServer.class, "scheduledEvents", new net.minecraft.world.level.timers.TimerQueue<MinecraftServer>());
|
||||
var clocks = net.minecraft.world.clock.ServerClockManager.TYPE.constructor().get();
|
||||
clocks.init(mcs);
|
||||
put(mcs, MinecraftServer.class, "clockManager", clocks);
|
||||
var templates = alloc(net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager.class);
|
||||
put(templates, net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager.class, "sources",
|
||||
List.of(VanillaCommandParseOracle.templateSource(lookup, resources)));
|
||||
put(mcs, MinecraftServer.class, "structureTemplateManager", templates);
|
||||
var level = alloc(net.minecraft.server.level.ServerLevel.class);
|
||||
put(level, Level.class, "dimensionTypeRegistration",
|
||||
access.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD));
|
||||
put(level, net.minecraft.server.level.ServerLevel.class, "server", mcs);
|
||||
PlayerList playerList = alloc(net.minecraft.server.dedicated.DedicatedPlayerList.class);
|
||||
put(playerList, PlayerList.class, "players", new ArrayList<>());
|
||||
put(mcs, MinecraftServer.class, "playerList", playerList);
|
||||
ServerScoreboard scoreboard = new ServerScoreboard(mcs);
|
||||
put(mcs, MinecraftServer.class, "scoreboard", scoreboard);
|
||||
for (String team : VanillaCommandParseOracle.TEAMS) scoreboard.addPlayerTeam(team);
|
||||
for (String objective : VanillaCommandParseOracle.OBJECTIVES)
|
||||
scoreboard.addObjective(objective, net.minecraft.world.scores.criteria.ObjectiveCriteria.DUMMY, Component.literal(objective),
|
||||
net.minecraft.world.scores.criteria.ObjectiveCriteria.RenderType.INTEGER, true, null);
|
||||
for (String tracked : VanillaCommandParseOracle.TRACKED)
|
||||
scoreboard.getOrCreatePlayerScore(net.minecraft.world.scores.ScoreHolder.forNameOnly(tracked), scoreboard.getObjective("kills"));
|
||||
source = new VanillaCommandParseOracle.Src(mcs, level, LevelBasedPermissionSet.forLevel(PermissionLevel.byId(4)), access, lookup);
|
||||
}
|
||||
|
||||
/** Commands.sendCommands for an operator, then ClientPacketListener.handleCommands. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static CommandDispatcher<ClientSuggestionProvider> clientTree() throws Exception {
|
||||
RootCommandNode<CommandSourceStack> root = new RootCommandNode<>();
|
||||
Map<com.mojang.brigadier.tree.CommandNode<CommandSourceStack>, com.mojang.brigadier.tree.CommandNode<CommandSourceStack>> converted = new HashMap<>();
|
||||
converted.put(server.getRoot(), root);
|
||||
Method fill = Commands.class.getDeclaredMethod("fillUsableCommands", com.mojang.brigadier.tree.CommandNode.class, com.mojang.brigadier.tree.CommandNode.class, Object.class, Map.class);
|
||||
fill.setAccessible(true);
|
||||
fill.invoke(null, server.getRoot(), root, source, converted);
|
||||
Field inspector = Commands.class.getDeclaredField("COMMAND_NODE_INSPECTOR");
|
||||
inspector.setAccessible(true);
|
||||
var packet = new ClientboundCommandsPacket(root, (ClientboundCommandsPacket.NodeInspector<CommandSourceStack>) inspector.get(null));
|
||||
Field builder = ClientPacketListener.class.getDeclaredField("COMMAND_NODE_BUILDER");
|
||||
builder.setAccessible(true);
|
||||
return new CommandDispatcher<>(packet.getRoot(CommandBuildContext.simple(access, FeatureFlags.VANILLA_SET),
|
||||
(ClientboundCommandsPacket.NodeBuilder<ClientSuggestionProvider>) builder.get(null)));
|
||||
}
|
||||
|
||||
/** A key by name: [SDL scancode, keycode], with "shift+" and "ctrl+" modifiers. */
|
||||
static KeyEvent key(String name) {
|
||||
int mods = 0;
|
||||
while (true) {
|
||||
if (name.startsWith("shift+")) { mods |= 1; name = name.substring(6); }
|
||||
else if (name.startsWith("ctrl+")) { mods |= 64; name = name.substring(5); }
|
||||
else break;
|
||||
}
|
||||
int[] k = switch (name) {
|
||||
case "backspace" -> new int[] {42, 8};
|
||||
case "delete" -> new int[] {76, 127};
|
||||
case "home" -> new int[] {74, 1073741898};
|
||||
case "end" -> new int[] {77, 1073741901};
|
||||
case "right" -> new int[] {79, 1073741903};
|
||||
case "left" -> new int[] {80, 1073741904};
|
||||
case "down" -> new int[] {81, 1073741905};
|
||||
case "up" -> new int[] {82, 1073741906};
|
||||
case "tab" -> new int[] {43, 9};
|
||||
case "escape" -> new int[] {41, 27};
|
||||
case "a" -> new int[] {4, 97};
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
};
|
||||
return new KeyEvent(k[0], k[1], mods);
|
||||
}
|
||||
|
||||
static JsonObject run(JsonObject c, Minecraft mc, VanillaPackScreenOracle.StubGui gui) throws Exception {
|
||||
int width = c.get("width").getAsInt(), height = c.get("height").getAsInt();
|
||||
gui.width = width;
|
||||
gui.height = height;
|
||||
gui.current = null;
|
||||
var chat = alloc(Chat.class);
|
||||
var recent = new ArrayListDeque<String>(100);
|
||||
for (var s : c.getAsJsonArray("history")) recent.add(s.getAsString());
|
||||
put(chat, ChatComponent.class, "recentChat", recent);
|
||||
var hud = alloc(Hud.class);
|
||||
put(hud, Hud.class, "chat", chat);
|
||||
put(gui, net.minecraft.client.gui.Gui.class, "hud", hud);
|
||||
var options = alloc(Options.class);
|
||||
put(options, Options.class, "autoSuggestions", option(c.get("autoSuggest").getAsBoolean()));
|
||||
put(options, Options.class, "backgroundForChatOnly", option(c.get("chatOnly").getAsBoolean()));
|
||||
put(options, Options.class, "textBackgroundOpacity", option(c.get("opacity").getAsDouble()));
|
||||
put(options, Options.class, "saveChatDrafts", option(false));
|
||||
var window = alloc(com.mojang.blaze3d.platform.Window.class);
|
||||
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledWidth", width);
|
||||
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledHeight", height);
|
||||
put(mc, Minecraft.class, "window", window);
|
||||
put(mc, Minecraft.class, "options", options);
|
||||
var screen = new ChatScreen(c.get("initial").getAsString(), false);
|
||||
gui.setScreen(screen);
|
||||
var info = new MouseButtonInfo(1, 0);
|
||||
for (var a : c.getAsJsonArray("actions")) {
|
||||
var o = a.getAsJsonObject();
|
||||
Screen s = gui.current;
|
||||
if (s != screen) break;
|
||||
switch (o.get("type").getAsString()) {
|
||||
case "type" -> o.get("text").getAsString().codePoints().forEach(cp -> screen.charTyped(new CharacterEvent(cp)));
|
||||
case "key" -> screen.keyPressed(key(o.get("key").getAsString()));
|
||||
case "click" -> {
|
||||
var event = new MouseButtonEvent(o.get("x").getAsDouble(), o.get("y").getAsDouble(), info);
|
||||
screen.mouseClicked(event, false);
|
||||
screen.mouseReleased(event);
|
||||
}
|
||||
default -> throw new IllegalArgumentException(o.toString());
|
||||
}
|
||||
}
|
||||
var result = new JsonObject();
|
||||
if (gui.current != screen) {
|
||||
result.addProperty("closed", true);
|
||||
return result;
|
||||
}
|
||||
var input = (EditBox) get(screen, ChatScreen.class, "input");
|
||||
put(input, EditBox.class, "focusedTime", Util.getMillis() - c.get("blink").getAsLong());
|
||||
var g = alloc(VanillaPackScreenOracle.Capture.class);
|
||||
g.draws = new JsonArray();
|
||||
g.stack = new Matrix3x2fStack(16);
|
||||
g.width = width;
|
||||
g.height = height;
|
||||
int mx = c.getAsJsonArray("mouse").get(0).getAsInt(), my = c.getAsJsonArray("mouse").get(1).getAsInt();
|
||||
// ChatScreen.extractRenderState without ChatComponent's lines.
|
||||
g.fill(2, height - 14, width - 2, height - 2, options.getBackgroundColor(Integer.MIN_VALUE));
|
||||
@SuppressWarnings("unchecked")
|
||||
var renderables = (List<Renderable>) get(screen, Screen.class, "renderables");
|
||||
for (var r : renderables) r.extractRenderState(g, mx, my, 1.0F);
|
||||
((CommandSuggestions) get(screen, ChatScreen.class, "commandSuggestions")).extractRenderState(g, mx, my);
|
||||
result.addProperty("value", input.getValue());
|
||||
result.addProperty("cursor", input.getCursorPosition());
|
||||
result.addProperty("highlight", (int) get(input, EditBox.class, "highlightPos"));
|
||||
result.addProperty("display", (int) get(input, EditBox.class, "displayPos"));
|
||||
result.add("draws", g.draws);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
VanillaPackScreenOracle.unsafe = unsafe;
|
||||
VanillaPackScreenOracle.allocate = allocate;
|
||||
server();
|
||||
var font = ParityFont.create(ParityFont.resources());
|
||||
VanillaPackScreenOracle.font = font;
|
||||
Minecraft mc = alloc(Minecraft.class);
|
||||
put(mc, Minecraft.class, "font", font);
|
||||
put(mc, Minecraft.class, "fontFilterFishy", font);
|
||||
put(mc, Minecraft.class, "lastInputType", InputType.MOUSE);
|
||||
put(mc, Minecraft.class, "textInputManager", new VanillaPackScreenOracle.NoTextInput());
|
||||
put(mc, Minecraft.class, "soundManager", alloc(VanillaPackScreenOracle.NoSound.class));
|
||||
put(mc, Minecraft.class, "keyboardHandler", alloc(VanillaPackScreenOracle.NoKeyboard.class));
|
||||
put(mc, Minecraft.class, "narrator", alloc(NoNarrator.class));
|
||||
var gui = alloc(VanillaPackScreenOracle.StubGui.class);
|
||||
put(mc, Minecraft.class, "gui", gui);
|
||||
var connection = alloc(ClientPacketListener.class);
|
||||
put(connection, ClientPacketListener.class, "commands", clientTree());
|
||||
var provider = alloc(Provider.class);
|
||||
put(provider, ClientSuggestionProvider.class, "minecraft", mc);
|
||||
put(connection, ClientPacketListener.class, "suggestionsProvider", provider);
|
||||
var player = alloc(LocalPlayer.class);
|
||||
put(player, LocalPlayer.class, "connection", connection);
|
||||
put(player, LocalPlayer.class, "chatAbilities", ChatAbilities.NO_RESTRICTIONS);
|
||||
put(mc, Minecraft.class, "player", player);
|
||||
Field instance = Minecraft.class.getDeclaredField("instance");
|
||||
instance.setAccessible(true);
|
||||
instance.set(null, mc);
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
if (line.isBlank()) continue;
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
JsonObject result;
|
||||
try {
|
||||
result = run(c, mc, gui);
|
||||
} catch (Throwable error) {
|
||||
Throwable cause = error;
|
||||
while (cause.getCause() != null) cause = cause.getCause();
|
||||
var sw = new java.io.StringWriter();
|
||||
cause.printStackTrace(new java.io.PrintWriter(sw));
|
||||
result = new JsonObject();
|
||||
result.addProperty("error", sw.toString().lines().limit(10).reduce("", (a, b) -> a + b + " | "));
|
||||
}
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,13 @@ public final class VanillaPackScreenOracle {
|
||||
o.add("lines", a);
|
||||
o.addProperty("x", x); o.addProperty("y", y);
|
||||
}
|
||||
@Override public void setTooltipForNextFrame(Font font, List<? extends FormattedCharSequence> lines, int x, int y, Identifier style) {
|
||||
var o = add("tooltip");
|
||||
var a = new JsonArray();
|
||||
for (var l : lines) a.add(runs(l));
|
||||
o.add("lines", a);
|
||||
o.addProperty("x", x); o.addProperty("y", y);
|
||||
}
|
||||
}
|
||||
|
||||
/** The window's text input area: not tracked. */
|
||||
@@ -232,6 +239,7 @@ public final class VanillaPackScreenOracle {
|
||||
current.removed();
|
||||
}
|
||||
current = screen;
|
||||
if (screen == null) return;
|
||||
screen.added();
|
||||
show(screen, width, height);
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the chat screen's input with the vanilla client's.
|
||||
|
||||
Each case opens the chat screen (empty or with "/", a GUI size, the sent
|
||||
message history, automatic suggestions on or off, the chat background
|
||||
option) and types, presses keys (editing, selection, word moves, select
|
||||
all, history up and down, Tab and Shift+Tab through suggestions, Escape)
|
||||
and clicks (on the suggestion list, on the input). The Java oracle
|
||||
(VanillaChatScreenOracle) drives a real ChatScreen, whose CommandSuggestions
|
||||
parse with vanilla's client command tree and ask the server's dispatcher
|
||||
for the suggestions a node leaves to it; examples/chat_screen_fixture runs
|
||||
horizon_client::chat::ChatScreen on Horizon's dispatcher. After the actions
|
||||
the input's value, cursor, selection and scroll and the screen's GUI calls
|
||||
(the input background, the EditBox with its argument colouring, cursor,
|
||||
selection and suggestion text, then the suggestion list or the usage lines)
|
||||
must agree.
|
||||
|
||||
test_chat_screen_parity.py [--count N] [--detail N]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import interaction_lab as lib, lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import test_model_baking_parity as baking
|
||||
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
TEXTS = ['/give @p minecraft:dia', '/tp ', '/gamemode cr', 'hello world', '/effect give @s ', '/execute as @a run ',
|
||||
'/time set da', '/xyz', '/give Steve stone 64 extra', '/tell Al', '/scoreboard objectives add k dummy',
|
||||
'/summon minecraft:zom', '/setblock ~ ~1 ~ minecraft:oak_stairs[facing=', '/team join r', '/kill @e[type=',
|
||||
'/', 'a', ' ', 'S', '@', '~ ', 'minecraft:', '/weather ', '/say this is a long message that goes on and on and on '
|
||||
'until it no longer fits the chat box', '/particle ', '/enchant @s sharp', '/difficulty ', '/gamerule ',
|
||||
'/attribute @s ', '/fill 0 0 0 1 1 1 stone repl', '/clear @p diamond 3', '/locate structure vil']
|
||||
KEYS = ['tab', 'tab', 'tab', 'shift+tab', 'up', 'down', 'left', 'right', 'home', 'end', 'backspace', 'backspace',
|
||||
'ctrl+backspace', 'delete', 'ctrl+left', 'ctrl+right', 'shift+left', 'shift+right', 'shift+home', 'ctrl+a', 'escape']
|
||||
HISTORY = ['/time set day', 'hi', '/give @p diamond 64', '/gamemode creative', 'a longer message in the history', '/tp ~ ~10 ~']
|
||||
|
||||
|
||||
def cases(count):
|
||||
rng = random.Random(0x43484154)
|
||||
out = []
|
||||
for _ in range(count):
|
||||
width, height = rng.choice([(320, 240), (427, 240), (480, 270), (640, 360), (854, 480), (240, 180)])
|
||||
actions = []
|
||||
for _ in range(rng.choice([1, 2, 3, 5, 8, 12])):
|
||||
r = rng.random()
|
||||
if r < 0.45:
|
||||
actions.append({'type': 'type', 'text': rng.choice(TEXTS)})
|
||||
elif r < 0.85:
|
||||
key = rng.choice(KEYS)
|
||||
if key == 'escape' and rng.random() < 0.7:
|
||||
key = 'tab'
|
||||
actions.append({'type': 'key', 'key': key})
|
||||
else:
|
||||
x = rng.randint(0, width // 2)
|
||||
y = rng.choice([rng.randint(height - 15 - 120, height - 15), rng.randint(height - 14, height - 1)])
|
||||
actions.append({'type': 'click', 'x': x, 'y': y})
|
||||
mouse = rng.choice([(rng.randint(0, width - 1), rng.randint(0, height - 1)),
|
||||
(rng.randint(0, width // 2), rng.randint(height - 15 - 120, height - 15)), (0, 0)])
|
||||
out.append({'width': width, 'height': height, 'initial': rng.choice(['', '', '', '/']),
|
||||
'history': rng.sample(HISTORY, rng.randint(0, len(HISTORY))), 'autoSuggest': rng.random() < 0.85,
|
||||
'chatOnly': rng.random() < 0.7, 'opacity': rng.choice([0.0, 0.5, 1.0]), 'actions': actions,
|
||||
'mouse': list(mouse), 'blink': rng.choice([0, 100, 400, 650])})
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--count', type=int, default=3000)
|
||||
parser.add_argument('--detail', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = lab.LOCAL / 'chat-screen-parity'; build.mkdir(parents=True, exist_ok=True)
|
||||
chosen = cases(args.count)
|
||||
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
|
||||
classes = build / 'classes'; classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
|
||||
if result.returncode:
|
||||
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
|
||||
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaPackScreenOracle', 'VanillaCommandParseOracle',
|
||||
'VanillaChatScreenOracle'))], 'compile-java')
|
||||
java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies]
|
||||
run([*java, 'dev.horizonlab.parity.VanillaCommandParseOracle', 'registries', build], 'registries')
|
||||
run([*java, 'dev.horizonlab.parity.VanillaChatScreenOracle', inputs, build / 'vanilla.jsonl'], 'vanilla')
|
||||
lib.cargo_example('horizon-client', 'chat_screen_fixture', lib.RESOURCES, build / 'registries.json', inputs, build / 'rust.jsonl')
|
||||
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
|
||||
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
|
||||
assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen))
|
||||
errors = [v['error'] for v in vanilla if 'error' in v]
|
||||
bad = [(c, v, r) for c, v, r in zip(chosen, vanilla, rust) if 'error' not in v and v != r]
|
||||
for e in sorted(set(errors))[:5]:
|
||||
print('ORACLE ERROR', e[:1500])
|
||||
for c, v, r in bad[:args.detail]:
|
||||
print('MISMATCH', json.dumps({k: c[k] for k in c if k != 'history'})[:1500])
|
||||
for k in ('closed', 'value', 'cursor', 'highlight', 'display'):
|
||||
if v.get(k) != r.get(k):
|
||||
print(f' {k}: vanilla {v.get(k)!r} | horizon {r.get(k)!r}')
|
||||
a, b = v.get('draws', []), r.get('draws', [])
|
||||
i = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or a[i] != b[i]), None)
|
||||
if i is not None:
|
||||
print(f' call {i}: vanilla {json.dumps(a[i]) if i < len(a) else None}')
|
||||
print(f' call {i}: horizon {json.dumps(b[i]) if i < len(b) else None}')
|
||||
print(f'{len(chosen) - len(bad) - len(errors)}/{len(chosen)} chat screens match; {len(errors)} oracle errors')
|
||||
if bad or errors:
|
||||
sys.exit(1)
|
||||
print('chat screen parity ok')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user