diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 6156a041d..7c51a40f1 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -386,6 +386,12 @@ pub struct ChatScreen { parse: Option, /// The completions at the cursor (`pendingSuggestions`): range start (bytes) and list. pending: Option<(usize, Vec)>, + /// Completions waiting for the server's (an `ask_server` node at the + /// cursor): `pendingSuggestions` is not done until they come. + awaiting: Option, + /// The request to send (`ServerboundCommandSuggestionPacket`): id and + /// the command up to the cursor. + request: Option<(i32, String)>, suggestions: Option, usage: Vec, usage_position: i32, @@ -394,6 +400,16 @@ pub struct ChatScreen { keep_suggestions: bool, pub auto_suggestions: bool, } +/// Local completions waiting for the server's reply to request `id`. +struct Awaiting { + id: i32, + /// The command up to the cursor, as sent. + truncated: String, + local: Vec, +} +/// `ClientSuggestionProvider.pendingSuggestionsId`: one counter for the +/// connection, so a reply to an older request never matches. +static SUGGESTION_ID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); /// `CommandSuggestions`' fill colour. const FILL: i32 = -805306368; fn byte_at(s: &str, chars: usize) -> usize { @@ -442,6 +458,8 @@ impl ChatScreen { history_pos: history_len, parse: None, pending: None, + awaiting: None, + request: None, suggestions: None, usage: Vec::new(), usage_position: 0, @@ -518,24 +536,84 @@ impl ChatScreen { } if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) { let parse = self.parse.as_ref().expect("parsed above"); - let (range, list) = c - .dispatcher - .client_suggestions(parse, cursor_b, c.registries); - self.pending = Some((range.0, list)); - self.update_usage_info(m, c); + let (range, list, ask) = + c.dispatcher + .client_suggestions_asking(parse, cursor_b, c.registries); + if ask { + // ClientSuggestionProvider.customSuggestion: the + // suggestions are done when the server answers. + let id = SUGGESTION_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let truncated = command[..cursor_b].to_owned(); + self.request = Some((id, truncated.clone())); + self.awaiting = Some(Awaiting { + id, + truncated, + local: list, + }); + self.pending = None; + } else { + self.awaiting = None; + 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.awaiting = None; self.pending = Some((range.0, list)); self.usage_width = 0; self.usage_position = 0; } else { + self.awaiting = None; self.pending = None; } } + /// The completion request to send to the server, if one is waiting. + pub fn take_request(&mut self) -> Option<(i32, String)> { + self.request.take() + } + /// `ClientSuggestionProvider.completeCustomSuggestions`: the server's + /// completions for request `id`, with `range` in UTF-16 units of the + /// command sent. They join the local ones (`Suggestions.merge`) and the + /// pending suggestions are done. + pub fn server_suggestions( + &mut self, + m: &Measure, + c: &Commands, + id: i32, + range: (usize, usize), + list: Vec<(String, Option)>, + ) { + let Some(awaiting) = self.awaiting.take_if(|a| a.id == id) else { + return; + }; + let input = &awaiting.truncated; + let byte = |units: usize| { + let mut n = 0; + input + .char_indices() + .find(|(_, ch)| { + let past = n >= units; + n += ch.len_utf16(); + past + }) + .map_or(input.len(), |(i, _)| i) + }; + let range = (byte(range.0), byte(range.0 + range.1)); + let mut all = awaiting.local; + all.extend(list.into_iter().map(|(text, tooltip)| Suggestion { + range, + text, + tooltip, + int_value: None, + })); + let (range, list) = merge_suggestions(input, all); + self.pending = Some((range.0, list)); + self.update_usage_info(m, c); + } /// `CommandSuggestions.updateUsageInfo`. fn update_usage_info(&mut self, m: &Measure, c: &Commands) { let Some(parse) = &self.parse else { return }; diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index 3cbac071b..e1bf2feda 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -230,3 +230,58 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() { screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); assert_eq!(screen.value(), "/coords"); } + +#[test] +fn ask_server_nodes_wait_for_the_servers_completions() { + // ClientSuggestionProvider.customSuggestion: an `ask_server` node at the + // cursor sends the command so far, and the list is done with the reply. + let font = font(); + let m = Measure(&font); + let registries = Registries { + permission: 4, + ..Registries::default() + }; + let mut d = crate::command::vanilla::game_dispatcher().clone(); + let child = |d: &crate::command::Dispatcher, n: usize, name: &str| { + d.nodes[n] + .children + .iter() + .copied() + .find(|&c| d.nodes[c].name() == name) + .expect(name) + }; + let id = child(&d, child(&d, child(&d, 0, "bossbar"), "get"), "id"); + d.nodes[id].suggests = Some(crate::command::Suggests::AskServer); + let c = Commands { + dispatcher: &d, + registries: ®istries, + }; + let tab = |screen: &mut ChatScreen| { + screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, "/bossbar get pt"); + let (request, sent) = screen.take_request().expect("the server is asked"); + assert_eq!(sent, "/bossbar get pt"); + assert_eq!(screen.take_request(), None); + // Nothing to complete until the reply. + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt"); + // A reply to an older request is dropped; the range is in UTF-16 units. + let reply = |text: &str| vec![(text.to_owned(), None)]; + screen.server_suggestions(&m, &c, request - 1, (13, 2), reply("pt6:old")); + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt"); + screen.server_suggestions(&m, &c, request, (13, 2), reply("pt6:check")); + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt6:check"); + // Without the server's provider the local list is done at once. + let local = crate::command::vanilla::game_dispatcher(); + let c = Commands { + dispatcher: local, + registries: ®istries, + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, "/bossbar get pt"); + assert_eq!(screen.take_request(), None); +} diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 8fcb30830..e9aeaae51 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -312,6 +312,9 @@ pub enum Suggests { /// ScoreboardCommand.suggestTriggers: trigger objectives some of the /// parsed `targets` have no score in, or a locked one. EnableTriggers, + /// SuggestionProviders.ASK_SERVER: the server completes the node + /// (ClientSuggestionProvider.customSuggestion); nothing locally. + AskServer, } impl Node { pub fn name(&self) -> &str { @@ -691,7 +694,7 @@ impl Suggests { Suggests::Triggers => { builder.suggest_matching(reg.trigger_objectives.iter().map(String::as_str)) } - Suggests::Nothing => {} + Suggests::Nothing | Suggests::AskServer => {} } } } @@ -955,7 +958,8 @@ impl Dispatcher { cursor: usize, reg: &Registries, ) -> (Range, Vec) { - self.suggestions_within(parse, cursor, reg, u8::MAX) + let (range, list, _) = self.suggestions_within(parse, cursor, reg, u8::MAX); + (range, list) } /// The suggestions the player's chat shows: the client's tree only holds /// the nodes the player may use (Commands.sendCommands prunes by canUse). @@ -965,6 +969,18 @@ impl Dispatcher { cursor: usize, reg: &Registries, ) -> (Range, Vec) { + let (range, list, _) = self.suggestions_within(parse, cursor, reg, reg.permission); + (range, list) + } + /// [`Self::client_suggestions`], and whether a node at the cursor asks + /// the server (`ask_server`): its completions come with the server's + /// reply, to be merged with these. + pub fn client_suggestions_asking( + &self, + parse: &ParseResults, + cursor: usize, + reg: &Registries, + ) -> (Range, Vec, bool) { self.suggestions_within(parse, cursor, reg, reg.permission) } fn suggestions_within( @@ -973,15 +989,17 @@ impl Dispatcher { cursor: usize, reg: &Registries, permission: u8, - ) -> (Range, Vec) { + ) -> (Range, Vec, bool) { let (parent, start, context) = parse.context.suggestion_context(cursor); let start = start.min(cursor); let truncated = &parse.input[..cursor.min(parse.input.len())]; let mut all = Vec::new(); + let mut ask = false; for &child in &self.nodes[parent].children { if self.nodes[child].permission > permission { continue; } + ask |= matches!(self.nodes[child].suggests, Some(Suggests::AskServer)); let mut builder = SuggestionsBuilder::new(truncated, start); match &self.nodes[child].kind { NodeKind::Literal(l) => { @@ -997,7 +1015,8 @@ impl Dispatcher { } all.extend(builder.out); } - merge_suggestions(truncated, all) + let (range, list) = merge_suggestions(truncated, all); + (range, list, ask) } fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option { let n = &self.nodes[node]; diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-client/src/command/network.rs index 32f446f5c..8fed97db0 100644 --- a/crates/horizon-client/src/command/network.rs +++ b/crates/horizon-client/src/command/network.rs @@ -83,10 +83,9 @@ pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher { } _ => NodeKind::Root, }; - let suggests = match local_node { - Some(l) => l.suggests.clone(), - None => node.suggestions.as_deref().and_then(provider), - }; + // The server's providers, as the client knows them + // (ArgumentNodeStub.build): its own custom ones arrive as `ask_server`. + let suggests = node.suggestions.as_deref().and_then(provider); nodes[index(i)] = Some(Node { kind: if i == root { NodeKind::Root } else { kind }, children: node.children.iter().filter_map(valid).map(index).collect(), @@ -104,10 +103,10 @@ pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher { d } -/// SuggestionProviders by id (`ask_server` asks the server; the client's -/// own argument suggestions stand in for it). +/// SuggestionProviders by id (`SuggestionProviders.getProvider`). fn provider(id: &str) -> Option { match id { + "minecraft:ask_server" => Some(Suggests::AskServer), "minecraft:summonable_entities" => Some(Suggests::SummonableEntities), _ => None, } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index b19cd9d01..cb8a3a0b5 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -533,6 +533,23 @@ impl Game<'_> { } } } + /// The server's completions for an `ask_server` request + /// (ClientPacketListener.handleCommandSuggestions). + pub(super) fn chat_server_suggestions( + &mut self, + id: i32, + range: (usize, usize), + list: Vec<(String, Option)>, + ) { + let m = Measure(&self.atlas.font); + let c = Commands { + dispatcher: chat_tree(&self.remote, &self.mods), + registries: &self.ui.registries, + }; + if let Some(screen) = self.ui.chat_screen.as_mut() { + screen.server_suggestions(&m, &c, id, range, list); + } + } /// Text typed into the chat box (control socket `chat`). pub(super) fn chat_type(&mut self, text: &str) { let m = Measure(&self.atlas.font); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 991bc42b2..b15793003 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -558,8 +558,58 @@ impl Game<'_> { break; } } + self.send_suggestion_request(); Ok(()) } + /// ClientSuggestionProvider.customSuggestion: the chat's completion + /// request for an `ask_server` node goes to the server. + fn send_suggestion_request(&mut self) { + if self.remote.is_none() { + return; + } + let Some((id, command)) = self.ui.chat_screen.as_mut().and_then(|s| s.take_request()) + else { + return; + }; + let mut w = horizon_protocol::buf::Writer::new(); + w.varint(id); + w.string(&command); + self.send(S::Unknown( + horizon_protocol::ids::play::serverbound::COMMAND_SUGGESTION, + w.data, + )); + } + /// ClientboundCommandSuggestionsPacket: id, range start and length, then + /// each suggestion's text and optional tooltip. + fn handle_command_suggestions(&mut self, data: &[u8]) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + let mut r = horizon_protocol::buf::Reader::new(data); + let decoded = (|| { + let id = r.varint()?; + let start = r.varint()?; + let length = r.varint()?; + let n = r.count(usize::MAX)?; + let mut list = Vec::with_capacity(n.min(1000)); + for _ in 0..n { + let text = r.string(32767)?; + let tooltip = if r.bool()? { + Some(plain(&r.nbt()?, &lang)) + } else { + None + }; + list.push((text, tooltip)); + } + horizon_protocol::Result::Ok((id, start, length, list)) + })(); + if let Ok((id, start, length, list)) = decoded { + let range = (start.max(0) as usize, length.max(0) as usize); + self.chat_server_suggestions(id, range, list); + } + } fn set_registries(&mut self, registries: Arc) { let biomes: Vec = registries .registries @@ -1641,6 +1691,11 @@ impl Game<'_> { self.capture(true); } } + C::Unknown(id, data) + if id == horizon_protocol::ids::play::clientbound::COMMAND_SUGGESTIONS => + { + self.handle_command_suggestions(&data); + } C::Commands(p) => { let tree = horizon_client::command::network::from_packet( &p, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index b1e7ec098..13b1d48aa 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -732,11 +732,29 @@ def check_commands(host, guest, out): screen = guest('state').get('screen') guest('command', command='gamemode survival') guest.wait(10) + # A node the tree marks ask_server (a bossbar id): the guest asks the + # server, which completes it from its own bossbars. + host('command', command='bossbar add pt6:check "Check"') + host.wait(5) + guest.raw('key', 'slash', 'tap') + guest.wait(3) + guest.raw('type', 'bossbar get pt') + guest.wait(10) + guest.raw('key', 'tab', 'tap') + guest.wait(2) + asked = chat_input(guest) + for _ in range(3): + if guest('screen').get('screen') != 'chat': + break + guest.raw('key', 'esc', 'tap') + guest.wait(3) + host('command', command='bossbar remove pt6:check') assert literal == '/gamemode', f'Tab after /gamem: {literal!r}' assert argument == '/gamemode creative', f'Tab after /gamemode cr: {argument!r}' assert mode == 'creative', f'the completed command did not run: {mode}' assert screen in (None, 'playing'), f'the chat did not close: {screen}' - return {'literal': literal, 'argument': argument, 'mode': mode} + assert asked == '/bossbar get pt6:check', f'Tab after /bossbar get pt: {asked!r}' + return {'literal': literal, 'argument': argument, 'mode': mode, 'ask_server': asked} def centre(rect):