//! Chat: the message list (ChatComponent: wrapping, 100-line history, //! 200-tick fade, scrolling, system message indicator) and the chat screen //! (ChatScreen + EditBox + CommandSuggestions: history navigation, argument //! colouring, usage hints, parse errors and tab completion). use crate::{ 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, ClickEvent, Style, Text}, }; #[cfg(test)] #[path = "chat_tests.rs"] mod tests; /// GuiMessageTag.systemSinglePlayer's indicator colour. pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; /// The chat options (doubles, as vanilla keeps them). #[derive(Clone, Copy, Debug)] pub struct ChatOptions { pub opacity: f64, pub background_opacity: f64, pub scale: f64, pub width: f64, pub height_focused: f64, pub height_unfocused: f64, pub line_spacing: f64, /// Chat Colors (`chatColors`): legacy `§` codes format the text, or are /// left out. pub colors: bool, } impl Default for ChatOptions { fn default() -> Self { Self { colors: true, opacity: 1.0, background_opacity: 0.5, scale: 1.0, width: 1.0, height_focused: 1.0, height_unfocused: 70.0 / 160.0, line_spacing: 0.0, } } } impl ChatOptions { /// ChatComponent.getWidth/getHeight. pub fn width_px(&self) -> i32 { (self.width * 280.0 + 40.0).floor() as i32 } pub fn height_px(&self, focused: bool) -> i32 { ((if focused { self.height_focused } else { self.height_unfocused }) * 160.0 + 20.0) .floor() as i32 } /// `getLineHeight`. pub fn line_height(&self) -> i32 { (9.0 * (self.line_spacing + 1.0)) as i32 } } #[derive(Clone, Debug)] struct Message { added: u64, content: Text, indicator: Option, } /// A wrapped line (`GuiMessage.Line`). #[derive(Clone, Debug)] struct Line { added: u64, content: Text, indicator: Option, } /// `ChatComponent.AlphaCalculator.timeBased`: opaque for 180 ticks, then /// fading out quadratically over 20. fn time_alpha(ticks: u64, added: u64) -> f32 { let delta = ticks as i64 - added as i64; let mut t = delta as f64 / 200.0; t = 1.0 - t; t *= 10.0; t = t.clamp(0.0, 1.0); t *= t; t as f32 } #[derive(Default)] pub struct Chat { messages: Vec, /// Wrapped lines, newest first. lines: Vec, /// Sent messages and commands (ChatComponent.recentChat). pub recent: Vec, scroll: usize, new_since_scroll: bool, pub options: ChatOptions, /// Messages printed to stdout as `[CHAT]` (vanilla logs them). pub log: bool, /// Messages added since the start, for the control socket's events. pub received: u64, } impl Chat { pub fn lines_per_page(&self, focused: bool) -> usize { (self.options.height_px(focused) / self.options.line_height().max(1)) as usize } /// The wrapping width, `Mth.floor(getWidth() / getScale())`. fn max_width(&self) -> i32 { (f64::from(self.options.width_px()) / self.options.scale).floor() as i32 } /// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. pub fn add( &mut self, atlas: &HudAtlas, content: Text, indicator: Option, ticks: u64, focused: bool, ) { // ChatComponent.logChatMessage: every message is in the log. crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain())); if self.log { println!("[CHAT] {}", content.plain()); } let message = Message { added: ticks, content, indicator, }; self.add_lines(atlas, &message, focused); self.messages.insert(0, message); self.messages.truncate(100); self.received += 1; } fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { let width = self.max_width(); let content = self.displayed(&message.content); for line in atlas.font.wrap_components(&content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); } self.lines.insert( 0, Line { added: message.added, content: line, indicator: message.indicator, }, ); } self.lines.truncate(100); } /// What a message's lines wrap (ComponentRenderUtils.wrapComponents): /// without Chat Colors its `§` codes are stripped (stripColor); with /// them the font draws them as formatting. fn displayed(&self, content: &Text) -> Text { if self.options.colors { content.resolve_legacy() } else { content.strip_legacy() } } /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). pub fn rescale(&mut self, atlas: &HudAtlas) { self.scroll = 0; self.new_since_scroll = false; self.lines.clear(); let messages: Vec = self.messages.iter().rev().cloned().collect(); for m in &messages { self.add_lines(atlas, m, false); } } pub fn clear(&mut self) { self.messages.clear(); self.lines.clear(); self.scroll = 0; } pub fn add_recent(&mut self, message: &str) { if self.recent.last().map(String::as_str) != Some(message) { if self.recent.len() >= 100 { self.recent.remove(0); } self.recent.push(message.to_owned()); } } pub fn reset_scroll(&mut self) { self.scroll = 0; self.new_since_scroll = false; } pub fn scroll_by(&mut self, dir: i32, focused: bool) { let max = self .lines .len() .saturating_sub(self.lines_per_page(focused)) as i32; let pos = (self.scroll as i32 + dir).min(max); if pos <= 0 { self.scroll = 0; self.new_since_scroll = false; } else { self.scroll = pos as usize; } } /// `ChatComponent.extractRenderState` (background mode unless `focused`) /// on a screen `height` GUI pixels tall at `Hud.tickCount` `ticks`. pub fn layout(&self, height: i32, ticks: u64, focused: bool) -> Vec { let total = self.lines.len(); if total == 0 { return Vec::new(); } let o = &self.options; let scale = o.scale as f32; let max_width = hud_layout::ceil(o.width_px() as f32 / scale); let chat_bottom = hud_layout::floor((height - 40) as f32 / scale); let text_opacity = o.opacity as f32 * 0.9 + 0.1; let background_opacity = o.background_opacity as f32; let entry_height = o.line_height(); let bottom_to_text = (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32; let alpha_of = |line: &Line| { if focused { 1.0 } else { time_alpha(ticks, line.added) } }; let visible = total .saturating_sub(self.scroll) .min(self.lines_per_page(focused)); let lines: Vec<(usize, &Line, f32)> = (0..visible) .rev() .map(|i| (i, &self.lines[i + self.scroll])) .map(|(i, line)| (i, line, alpha_of(line))) .filter(|(_, _, alpha)| *alpha > 1.0e-5) .collect(); let mut out = vec![GuiDraw::Push(vec![ PoseOp::Scale(scale, scale), PoseOp::Translate(4.0, 0.0), ])]; for &(i, _, alpha) in &lines { let bottom = chat_bottom - i as i32 * entry_height; out.push(hud_layout::fill( -4, bottom - entry_height, max_width + 4 + 4, bottom, hud_layout::as8(alpha * background_opacity) << 24, )); } for &(i, line, alpha) in &lines { let bottom = chat_bottom - i as i32 * entry_height; let opacity = alpha * text_opacity; let color = hud_layout::white(opacity); if color >> 24 != 0 { out.push(GuiDraw::Text { text: line.content.clone(), x: 0, y: bottom - bottom_to_text, color, shadow: true, }); } if let Some(indicator) = line.indicator { let color = hud_layout::as8(opacity) << 24 | indicator & 0xFF_FFFF; out.push(hud_layout::fill( -4, bottom - entry_height, -2, bottom, color, )); } } if focused { let count = lines.len() as i32; let chat_height = count * entry_height; let virtual_height = total as i32 * entry_height; let y = self.scroll as i32 * chat_height / total as i32 - chat_bottom; let height = chat_height * chat_height / virtual_height; if virtual_height != chat_height { let alpha: u32 = if y > 0 { 170 } else { 96 }; let color = if self.new_since_scroll { 0xCC3333 } else { 0x3333AA }; let x = max_width + 4; out.push(hud_layout::fill( x, -y, x + 2, -y - height, alpha << 24 | color, )); out.push(hud_layout::fill( x + 2, -y, x + 1, -y - height, alpha << 24 | 0xCCCCCC, )); } } out.push(GuiDraw::Pop); out } /// Draws [`Chat::layout`] into the HUD batch. pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) { let draws = self.layout(batch.height as i32, ticks, focused); hud_layout::paint(batch, atlas, &draws); } /// The click action under a GUI-space cursor while chat is focused. pub fn click_at( &self, font: &crate::font::Font, height: i32, x: f64, y: f64, ) -> Option { self.style_at(font, height, x, y)?.click } /// The hover text under a GUI-space cursor while chat is focused /// (ChatScreen.render's `renderComponentHoverEffect`). pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option { self.style_at(font, height, x, y)?.hover.map(|h| *h) } /// ChatComponent.getClickedComponentStyleAt. fn style_at( &self, font: &crate::font::Font, height: i32, x: f64, y: f64, ) -> Option { let scale = self.options.scale as f32; let mut x = x / f64::from(scale) - 4.0; let bottom = hud_layout::floor((height - 40) as f32 / scale); let from_bottom = f64::from(bottom) - y / f64::from(scale); if x < 0.0 || x >= f64::from(self.max_width()) || from_bottom <= 0.0 { return None; } let row = (from_bottom / f64::from(self.options.line_height())).ceil() as usize - 1; if row >= self.lines_per_page(true) { return None; } let line = self.lines.get(self.scroll + row)?; let content = line.content.resolve_legacy(); for (c, style) in content.chars() { x -= f64::from(font.advance(c, style)); if x < 0.0 { return Some(style.clone()); } } None } /// Plain text of the newest messages (for tests and the control socket). pub fn recent_lines(&self, n: usize) -> Vec { self.messages .iter() .take(n) .map(|m| m.content.plain()) .collect() } /// The newest messages as components, styles included (control socket). pub fn recent_components(&self, n: usize) -> Vec { self.messages .iter() .take(n) .map(|m| m.content.component()) .collect() } } /// `CommandSuggestions.SuggestionsList`. #[derive(Clone, Debug)] struct SuggestionList { /// `rect`: x, y, width, height. rect: [i32; 4], original: String, list: Vec, offset: usize, current: usize, last_mouse: (i32, i32), tab_cycles: bool, } 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 } } /// 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), } /// 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, /// 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, usage_width: i32, allow_suggestions: bool, 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 { 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 { /// `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.bordered = false; input.focused = true; input.set_value(m, initial); let mut s = Self { input, width, height, history_buffer: String::new(), history_pos: history_len, parse: None, pending: None, awaiting: None, request: None, suggestions: None, usage: Vec::new(), usage_position: 0, usage_width: 0, allow_suggestions: false, keep_suggestions: false, auto_suggestions: true, }; s.update_command_info(m, c); s } pub fn value(&self) -> &str { &self.input.value } /// Replace the input for a suggest-command link and refresh completions. pub fn suggest_command(&mut self, m: &Measure, c: &Commands, command: &str) { self.input.set_value(m, command); self.edited(m, c); } /// `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; } } /// `ChatScreen.onEdited`. fn edited(&mut self, m: &Measure, c: &Commands) { self.allow_suggestions = true; self.update_command_info(m, c); } /// Ctrl+A/C/V/X in the input box. pub fn shortcut( &mut self, m: &Measure, c: &Commands, shortcut: crate::clipboard::EditShortcut, clipboard: &mut dyn crate::clipboard::Clipboard, ) { if self.input.shortcut(m, shortcut, clipboard) { self.edited(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; } if !self.keep_suggestions { self.input.suggestion = None; self.suggestions = None; } self.usage.clear(); 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)); } if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) { let parse = self.parse.as_ref().expect("parsed above"); 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 }; 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 = 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 x = clamp( self.input.screen_x(m, chars_to(&value, start)), 0, self.input.screen_x(m, 0) + self.input.inner_width() - width, ); 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, Vec) = list.into_iter().partition(|s| { s.text.starts_with(&word) || s.text.starts_with(&format!("minecraft:{word}")) }); 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, last_mouse: (0, 0), tab_cycles: false, }; self.select(&mut l, 0); self.suggestions = Some(l); } /// `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()) .map(str::to_owned); } 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; } } /// `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 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; l.tab_cycles = true; } /// `ChatScreen.keyPressed`. pub fn key( &mut self, m: &Measure, c: &Commands, history: &[String], key: winit::keyboard::KeyCode, shift: bool, ctrl: bool, ) -> ChatAction { use winit::keyboard::KeyCode as K; // CommandSuggestions.keyPressed. if let Some(mut l) = self.suggestions.take() { let handled = match key { K::ArrowUp | K::ArrowDown => { self.cycle(&mut l, if key == K::ArrowUp { -1 } else { 1 }); l.tab_cycles = false; true } K::Tab => { if l.tab_cycles { self.cycle(&mut l, if shift { -1 } else { 1 }); } self.use_suggestion(m, c, &mut l); true } K::Escape => { self.input.suggestion = None; return ChatAction::None; } _ => false, }; self.suggestions = Some(l); if handled { return ChatAction::None; } } else if key == K::Tab { self.show_suggestions(m); return ChatAction::None; } 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); } } } ChatAction::None } /// `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; } if new == max { self.history_pos = max; let b = self.history_buffer.clone(); 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(m, &history[new]); self.edited(m, c); self.allow_suggestions = false; self.suggestions = None; self.history_pos = new; } } /// 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(l); } if self.input.contains(x, y) { self.input.click(m, x, false); return true; } false } /// 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, text::GREEN, text::LIGHT_PURPLE, text::GOLD, ]; 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() { 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; } } out.push(Text::styled(piece(unformatted, len), gray)); out } /// `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, m: &Measure, mouse: (i32, i32), blink_ms: u64, background: i32, ) -> Vec { 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 - 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 } fn draw_list( &mut self, out: &mut Vec, 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 .value .split_whitespace() .collect::>() .join(" "); collapsed.chars().take(256).collect() } pub fn suggestions_visible(&self) -> bool { self.suggestions.is_some() } }