Skip to main content

nadir_debug/
console.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The console: a command line, with history and Tab completion, under a
16//! log of what the commands printed and what the game logged
17//! (`debug-tools.md`, "Console commands").
18
19use std::collections::VecDeque;
20use std::error::Error;
21use std::fmt::{self, Write as _};
22
23use nadir_core::{Color, Key};
24
25use crate::Ui;
26
27/// How many lines the console's log keeps: as many as the engine's log
28/// ring (`nadir_core::log::RING_CAPACITY`).
29pub const CONSOLE_LINES: usize = 1000;
30
31/// How many command lines the console's history keeps.
32pub const CONSOLE_HISTORY: usize = 100;
33
34/// The color of a warning: the stats overlay's amber.
35const WARNING: Color = Color::rgb(255, 176, 64);
36
37/// The color of an error.
38const ERROR: Color = Color::rgb(255, 96, 96);
39
40/// The log's lines a line of the wheel scrolls, as a window's rows.
41const LINES_A_WHEEL: f32 = 3.0;
42
43/// The console's own command, and what it says of itself.
44const HELP: &str = "help";
45const HELP_USAGE: &str = "help [command]";
46const HELP_TEXT: &str = "lists the commands, or says what one does";
47
48/// Why the console did not run a line, or a command failed: the console
49/// prints it in red.
50#[non_exhaustive]
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub enum ConsoleError {
53    /// A command registered with a usage that does not start with its
54    /// name: empty, a placeholder, a quote, or `help`, the console's own.
55    BadUsage(String),
56    /// A line with a quote that is not closed.
57    UnclosedQuote,
58    /// A line whose first word is no command's.
59    UnknownCommand(String),
60    /// A line short of an argument its command's usage needs.
61    MissingArgument {
62        /// The command's usage.
63        usage: String,
64        /// The argument, as the usage writes it: `<x>`.
65        argument: String,
66    },
67    /// A line with more arguments than its command's usage has.
68    TooManyArguments {
69        /// The command's usage.
70        usage: String,
71    },
72    /// An argument that is not what its command takes.
73    InvalidArgument {
74        /// The command's usage.
75        usage: String,
76        /// The argument, as the usage writes it, or `argument 2`.
77        argument: String,
78        /// What was typed.
79        found: String,
80        /// What it takes: `a number`.
81        expected: String,
82    },
83    /// A command that ran and failed, and why.
84    Failed(String),
85}
86
87impl fmt::Display for ConsoleError {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            Self::BadUsage(usage) => write!(
91                f,
92                "`{usage}` is no usage: it starts with the command's name, which is not `{HELP}`"
93            ),
94            Self::UnclosedQuote => f.write_str("a quote is not closed"),
95            Self::UnknownCommand(name) => write!(f, "no command `{name}`: `{HELP}` lists them"),
96            Self::MissingArgument { usage, argument } => {
97                write!(f, "{argument} is missing: {usage}")
98            }
99            Self::TooManyArguments { usage } => write!(f, "too many arguments: {usage}"),
100            Self::InvalidArgument {
101                usage,
102                argument,
103                found,
104                expected,
105            } => write!(f, "{argument}: `{found}` is not {expected}: {usage}"),
106            Self::Failed(why) => f.write_str(why),
107        }
108    }
109}
110
111impl Error for ConsoleError {}
112
113/// A command's arguments, the words typed after its name, checked against
114/// its usage: each word the usage names typed as it is, each choice one of
115/// the choices, as the usage spells it, each required argument there, and
116/// no more than the usage has.
117#[derive(Clone, Copy, Debug)]
118pub struct Args<'a> {
119    usage: &'a str,
120    words: &'a [String],
121}
122
123impl<'a> Args<'a> {
124    /// The command's usage: `tp <x> <y>`.
125    pub fn usage(&self) -> &'a str {
126        self.usage
127    }
128
129    /// How many arguments were typed.
130    pub fn len(&self) -> usize {
131        self.words.len()
132    }
133
134    /// Whether none were.
135    pub fn is_empty(&self) -> bool {
136        self.words.is_empty()
137    }
138
139    /// The argument at `index`, from 0, if it was typed.
140    pub fn get(&self, index: usize) -> Option<&'a str> {
141        self.words.get(index).map(String::as_str)
142    }
143
144    /// The argument at `index`.
145    ///
146    /// # Errors
147    ///
148    /// [`ConsoleError::MissingArgument`] if it was not typed.
149    pub fn str(&self, index: usize) -> Result<&'a str, ConsoleError> {
150        self.get(index)
151            .ok_or_else(|| ConsoleError::MissingArgument {
152                usage: self.usage.to_string(),
153                argument: self.argument(index),
154            })
155    }
156
157    /// The argument at `index` as a number, which must be finite.
158    ///
159    /// # Errors
160    ///
161    /// [`ConsoleError::MissingArgument`] if it was not typed, and
162    /// [`ConsoleError::InvalidArgument`] if it is no finite number.
163    pub fn f32(&self, index: usize) -> Result<f32, ConsoleError> {
164        let word = self.str(index)?;
165        match word.parse::<f32>() {
166            Ok(value) if value.is_finite() => Ok(value),
167            _ => Err(ConsoleError::InvalidArgument {
168                usage: self.usage.to_string(),
169                argument: self.argument(index),
170                found: word.to_string(),
171                expected: "a number".to_string(),
172            }),
173        }
174    }
175
176    /// The argument at `index` as the usage writes it, or its number.
177    fn argument(&self, index: usize) -> String {
178        match self.usage.split_whitespace().nth(index + 1).map(slot) {
179            Some(Slot::Choice { shown, .. } | Slot::Value { shown, .. }) => shown.to_string(),
180            _ => format!("argument {}", index + 1),
181        }
182    }
183}
184
185/// Where a command prints: lines added to the console's log, in the
186/// text's color unless it says another.
187pub struct ConsoleOut<'a> {
188    lines: &'a mut Lines,
189}
190
191impl ConsoleOut<'_> {
192    /// Prints `text`, a line for each of its lines.
193    pub fn print(&mut self, text: impl fmt::Display) {
194        self.lines.push(Tone::Text, text);
195    }
196
197    /// Prints `text` in `color`, a line for each of its lines.
198    pub fn print_colored(&mut self, color: Color, text: impl fmt::Display) {
199        self.lines.push(Tone::Color(color), text);
200    }
201}
202
203/// How a line is colored.
204#[derive(Clone, Copy, Debug, PartialEq)]
205enum Tone {
206    Text,
207    /// A line typed, as the console echoes it.
208    Echo,
209    Warning,
210    Error,
211    Color(Color),
212}
213
214/// A line of the log.
215#[derive(Clone, Debug, PartialEq)]
216struct Line {
217    text: String,
218    tone: Tone,
219}
220
221/// The log's lines, the newest last, and how far it is scrolled.
222#[derive(Debug, Default)]
223struct Lines {
224    lines: VecDeque<Line>,
225    /// How many lines up from the newest the view is: 0 sticks to it.
226    scroll: usize,
227    /// What a push formats into.
228    scratch: String,
229}
230
231impl Lines {
232    /// Adds `text`, a line for each of its lines, the oldest lines going
233    /// past [`CONSOLE_LINES`], their strings reused. A view scrolled up
234    /// stays on the lines it shows.
235    fn push(&mut self, tone: Tone, text: impl fmt::Display) {
236        self.scratch.clear();
237        // Writing to a `String` fails only if a `Display` impl does; what
238        // it wrote is printed.
239        let _ = write!(self.scratch, "{text}");
240        for part in self.scratch.split('\n') {
241            let part = part.strip_suffix('\r').unwrap_or(part);
242            let mut text = if self.lines.len() >= CONSOLE_LINES {
243                self.lines
244                    .pop_front()
245                    .map(|line| line.text)
246                    .unwrap_or_default()
247            } else {
248                String::new()
249            };
250            text.clear();
251            text.push_str(part);
252            self.lines.push_back(Line { text, tone });
253            if self.scroll > 0 {
254                self.scroll += 1;
255            }
256        }
257    }
258}
259
260/// A command registered: its name, the first word of its usage.
261#[derive(Clone, Debug)]
262struct Command<C> {
263    name: String,
264    usage: String,
265    help: String,
266    command: C,
267}
268
269/// A word of a usage after the command's name.
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271enum Slot<'a> {
272    /// A word typed as it is: `dump` of `profile dump [path]`.
273    Word(&'a str),
274    /// One of words: `<error|warn>`, or `[on|off]` if it may be left out.
275    Choice {
276        shown: &'a str,
277        choices: &'a str,
278        optional: bool,
279    },
280    /// A value: `<x>`, or `[path]` if it may be left out.
281    Value { shown: &'a str, optional: bool },
282}
283
284/// The slot a usage's word is: a placeholder starts with `<` or `[`, or
285/// ends with `>` or `]` (`[x y]` is two), and is a choice if it holds `|`.
286fn slot(word: &str) -> Slot<'_> {
287    let open = word.starts_with(['<', '[']);
288    let close = word.ends_with(['>', ']']);
289    if !open && !close {
290        return Slot::Word(word);
291    }
292    let optional = word.starts_with('[') || word.ends_with(']');
293    let inner = word
294        .trim_start_matches(['<', '['])
295        .trim_end_matches(['>', ']']);
296    if inner.contains('|') {
297        Slot::Choice {
298            shown: word,
299            choices: inner,
300            optional,
301        }
302    } else {
303        Slot::Value {
304            shown: word,
305            optional,
306        }
307    }
308}
309
310/// The choices of a choice's slot.
311fn choices(choices: &str) -> impl Iterator<Item = &str> {
312    choices.split('|').filter(|choice| !choice.is_empty())
313}
314
315/// Splits `line` into its words, into `words`: whitespace between words;
316/// a double quote groups what is up to the next, spaces too, and in it
317/// `\"` is a quote and `\\` a backslash, any other backslash kept as it is
318/// (`"C:\My Traces\t.json"`). Outside quotes a backslash is itself. `""`
319/// is an empty word.
320///
321/// # Errors
322///
323/// [`ConsoleError::UnclosedQuote`] for a quote not closed.
324fn split(line: &str, words: &mut Vec<String>) -> Result<(), ConsoleError> {
325    words.clear();
326    let mut word = String::new();
327    let mut in_word = false;
328    let mut quoted = false;
329    let mut chars = line.chars().peekable();
330    while let Some(c) = chars.next() {
331        if quoted {
332            match c {
333                '"' => quoted = false,
334                '\\' if matches!(chars.peek(), Some('"' | '\\')) => {
335                    if let Some(escaped) = chars.next() {
336                        word.push(escaped);
337                    }
338                }
339                _ => word.push(c),
340            }
341        } else if c == '"' {
342            quoted = true;
343            in_word = true;
344        } else if c.is_whitespace() {
345            if in_word {
346                words.push(std::mem::take(&mut word));
347                in_word = false;
348            }
349        } else {
350            word.push(c);
351            in_word = true;
352        }
353    }
354    if quoted {
355        return Err(ConsoleError::UnclosedQuote);
356    }
357    if in_word {
358        words.push(word);
359    }
360    Ok(())
361}
362
363/// Checks `words`, a line's arguments, against `usage`, and spells each
364/// choice as the usage does.
365///
366/// # Errors
367///
368/// A word that is not the usage's, a choice that is none of its choices,
369/// a required argument missing, or more arguments than the usage has.
370fn check(usage: &str, words: &mut [String]) -> Result<(), ConsoleError> {
371    let mut slots = 0;
372    for (index, word) in usage.split_whitespace().skip(1).enumerate() {
373        slots += 1;
374        let invalid = |found: &str, expected: String| ConsoleError::InvalidArgument {
375            usage: usage.to_string(),
376            argument: match slot(word) {
377                Slot::Word(_) => format!("argument {}", index + 1),
378                Slot::Choice { shown, .. } | Slot::Value { shown, .. } => shown.to_string(),
379            },
380            found: found.to_string(),
381            expected,
382        };
383        match (words.get_mut(index), slot(word)) {
384            (None, Slot::Word(word)) => {
385                return Err(ConsoleError::MissingArgument {
386                    usage: usage.to_string(),
387                    argument: format!("`{word}`"),
388                });
389            }
390            (
391                None,
392                Slot::Choice {
393                    shown,
394                    optional: false,
395                    ..
396                }
397                | Slot::Value {
398                    shown,
399                    optional: false,
400                },
401            ) => {
402                return Err(ConsoleError::MissingArgument {
403                    usage: usage.to_string(),
404                    argument: shown.to_string(),
405                });
406            }
407            (None, _) | (Some(_), Slot::Value { .. }) => {}
408            (Some(typed), Slot::Word(word)) => {
409                if typed.as_str() != word {
410                    return Err(invalid(typed, format!("`{word}`")));
411                }
412            }
413            (Some(typed), Slot::Choice { choices: all, .. }) => {
414                let Some(choice) = choices(all).find(|choice| choice.eq_ignore_ascii_case(typed))
415                else {
416                    let list = choices(all).collect::<Vec<_>>().join(", ");
417                    return Err(invalid(typed, format!("one of {list}")));
418                };
419                if typed != choice {
420                    *typed = choice.to_string();
421                }
422            }
423        }
424    }
425    if words.len() > slots {
426        return Err(ConsoleError::TooManyArguments {
427            usage: usage.to_string(),
428        });
429    }
430    Ok(())
431}
432
433/// What Tab does to a line.
434#[derive(Clone, Debug, PartialEq, Eq)]
435enum Completion {
436    /// Nothing matches, or the word cannot be completed (it is quoted).
437    Nothing,
438    /// The line, its last word completed: in full, with a space after it,
439    /// or as far as its matches agree.
440    Line(String),
441    /// The matches, which agree no further than what was typed.
442    List(Vec<String>),
443}
444
445/// Completes the last word of `line`, or the next if it ends with
446/// whitespace: the first word from the commands' names; another from its
447/// slot in the command's usage (a word, or a choice's choices; a value has
448/// none); `help`'s from the names.
449fn complete<C>(commands: &[Command<C>], line: &str) -> Completion {
450    let start = line
451        .char_indices()
452        .rfind(|(_, c)| c.is_whitespace())
453        .map_or(0, |(at, c)| at + c.len_utf8());
454    let (head, typed) = line.split_at(start);
455    if typed.contains('"') {
456        return Completion::Nothing;
457    }
458    let mut words = Vec::new();
459    if split(head, &mut words).is_err() {
460        return Completion::Nothing;
461    }
462    let names =
463        || std::iter::once(HELP).chain(commands.iter().map(|command| command.name.as_str()));
464    let mut matches: Vec<&str> = match words.split_first() {
465        None => names().collect(),
466        Some((name, before)) if name == HELP => {
467            if before.is_empty() {
468                names().collect()
469            } else {
470                Vec::new()
471            }
472        }
473        Some((name, before)) => commands
474            .iter()
475            .find(|command| command.name == *name)
476            .and_then(|command| command.usage.split_whitespace().nth(before.len() + 1))
477            .map_or_else(Vec::new, |word| match slot(word) {
478                Slot::Word(word) => vec![word],
479                Slot::Choice { choices: all, .. } => choices(all).collect(),
480                Slot::Value { .. } => Vec::new(),
481            }),
482    };
483    matches.retain(|candidate| candidate.starts_with(typed));
484    matches.sort_unstable();
485    matches.dedup();
486    match matches.as_slice() {
487        [] => Completion::Nothing,
488        [only] => Completion::Line(format!("{head}{only} ")),
489        [first, rest @ ..] => {
490            let common = common_prefix(first, rest);
491            if common.len() > typed.len() {
492                Completion::Line(format!("{head}{common}"))
493            } else {
494                Completion::List(matches.iter().map(|m| (*m).to_string()).collect())
495            }
496        }
497    }
498}
499
500/// How much of `first` every one of `rest` starts with.
501fn common_prefix<'a>(first: &'a str, rest: &[&str]) -> &'a str {
502    let mut end = first.len();
503    for other in rest {
504        let same = first
505            .char_indices()
506            .zip(other.chars())
507            .take_while(|((_, a), b)| a == b)
508            .last()
509            .map_or(0, |((at, c), _)| at + c.len_utf8());
510        end = end.min(same);
511    }
512    &first[..end]
513}
514
515/// A console: a command line under a log, in a window of its own. A
516/// command is registered with its usage, which names it and its arguments,
517/// a line of help, and `command`, the caller's value for it (an enum of the
518/// caller's commands, or a function), which the console hands back with the
519/// arguments when a line names it, for the caller to run.
520///
521/// - **Lines** are words split by whitespace, a double quote grouping
522///   words (`spawn "big rock"`), `\"` and `\\` in it a quote and a
523///   backslash. The first word names the command; `help` is the console's
524///   own, which lists the commands or says what one does.
525/// - **Usages** write each argument after the name: a word to type as it
526///   is (`profile dump [path]`), a value (`<x>`, or `[path]` if it may be
527///   left out), or a choice (`<error|warn|info>`). The console checks a
528///   line against its command's usage before the command runs: each word
529///   typed, each choice one of its own (ignoring case, then spelt as the
530///   usage spells it), each required argument there, no more arguments than
531///   the usage has. [`Args`] gives them, and reads a value as a number.
532/// - **Completion:** Tab completes the line's last word, or the next after
533///   a space: the first from the commands' names, the others from their
534///   slots in the usage, a word or a choice's choices. One match is put in
535///   whole, a space after it; several as far as they agree, or, if they
536///   agree no further, listed in the log, a match a line. A value has no
537///   completions.
538/// - **History:** each line run is kept, the last [`CONSOLE_HISTORY`] of
539///   them, one the same as the line before it once; Up goes back through
540///   them, and Down forward, to the line being typed.
541/// - **The log** keeps the last [`CONSOLE_LINES`] lines: each line run,
542///   after `>`, what the commands printed ([`ConsoleOut`]), their errors in
543///   red, and what the caller adds ([`Console::log_record`]): the engine's
544///   log records, warnings in amber and errors in red. A line too long for
545///   the window is cut at its edge.
546pub struct Console<C> {
547    commands: Vec<Command<C>>,
548    line: String,
549    history: VecDeque<String>,
550    /// The line of the history shown, while Up and Down go through it.
551    browsing: Option<usize>,
552    /// The line being typed, kept while the history is shown.
553    draft: String,
554    lines: Lines,
555    /// The wheel's lines not yet scrolled: a fraction of one.
556    wheel: f32,
557    /// The UI's frame the console was last shown in.
558    shown_in: Option<u64>,
559    /// Whether the command line had the keyboard then.
560    keyboard: bool,
561    words: Vec<String>,
562}
563
564impl<C> Default for Console<C> {
565    fn default() -> Self {
566        Self::new()
567    }
568}
569
570impl<C> Console<C> {
571    /// A console with no commands but `help`, an empty line and log.
572    pub fn new() -> Self {
573        Self {
574            commands: Vec::new(),
575            line: String::new(),
576            history: VecDeque::new(),
577            browsing: None,
578            draft: String::new(),
579            lines: Lines::default(),
580            wheel: 0.0,
581            shown_in: None,
582            keyboard: false,
583            words: Vec::new(),
584        }
585    }
586
587    /// Registers `command` under `usage`, whose first word is its name, with
588    /// `help`, a line of what it does; it replaces a command of that name.
589    /// `help` lists the commands in the order they were first registered.
590    ///
591    /// # Errors
592    ///
593    /// [`ConsoleError::BadUsage`] if the usage's first word is not a name:
594    /// there is none, it is a placeholder or a choice, it has a quote, or
595    /// it is `help`.
596    pub fn register(&mut self, usage: &str, help: &str, command: C) -> Result<(), ConsoleError> {
597        let usage = usage.trim();
598        let name = usage.split_whitespace().next().unwrap_or_default();
599        let bad = name.is_empty() || name == HELP || name.contains(['"', '<', '>', '[', ']', '|']);
600        if bad {
601            return Err(ConsoleError::BadUsage(usage.to_string()));
602        }
603        let registered = Command {
604            name: name.to_string(),
605            usage: usage.to_string(),
606            help: help.trim().to_string(),
607            command,
608        };
609        match self.commands.iter_mut().find(|known| known.name == name) {
610            Some(known) => *known = registered,
611            None => self.commands.push(registered),
612        }
613        Ok(())
614    }
615
616    /// The line being typed.
617    pub fn line(&self) -> &str {
618        &self.line
619    }
620
621    /// Sets the line being typed, as if typed: its caret goes to its end.
622    pub fn set_line(&mut self, line: &str) {
623        self.line.clear();
624        self.line.push_str(line);
625        self.browsing = None;
626    }
627
628    /// The log's lines, the oldest first.
629    pub fn lines(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
630        self.lines.lines.iter().map(|line| line.text.as_str())
631    }
632
633    /// Prints `text` in the log, a line for each of its lines.
634    pub fn print(&mut self, text: impl fmt::Display) {
635        self.lines.push(Tone::Text, text);
636    }
637
638    /// Prints `text` in red, a line for each of its lines.
639    pub fn print_error(&mut self, text: impl fmt::Display) {
640        self.lines.push(Tone::Error, text);
641    }
642
643    /// Adds a record of the engine's log, as `nadir_core::log::since` gives
644    /// it (`<time> <LEVEL> <target>: <message>`), a line for each of its
645    /// lines: in amber for `WARN`, in red for `ERROR`.
646    pub fn log_record(&mut self, record: &str) {
647        let tone = match record.split(' ').nth(1) {
648            Some("ERROR") => Tone::Error,
649            Some("WARN") => Tone::Warning,
650            _ => Tone::Text,
651        };
652        self.lines.push(tone, record);
653    }
654
655    /// Up: shows the line run before the one shown, keeping the line being
656    /// typed for [`Console::newer`] to come back to.
657    pub fn older(&mut self) {
658        let index = match self.browsing {
659            Some(index) => index.saturating_sub(1),
660            None if self.history.is_empty() => return,
661            None => {
662                self.draft.clear();
663                self.draft.push_str(&self.line);
664                self.history.len() - 1
665            }
666        };
667        self.browsing = Some(index);
668        self.line.clear();
669        self.line.push_str(&self.history[index]);
670    }
671
672    /// Down: shows the line run after the one shown, or past the last, the
673    /// line that was being typed.
674    pub fn newer(&mut self) {
675        let Some(index) = self.browsing else {
676            return;
677        };
678        self.line.clear();
679        if index + 1 < self.history.len() {
680            self.browsing = Some(index + 1);
681            self.line.push_str(&self.history[index + 1]);
682        } else {
683            self.browsing = None;
684            self.line.push_str(&self.draft);
685        }
686    }
687
688    /// Tab: completes the line's last word, or lists what it could be, as
689    /// [`Console`] says.
690    pub fn complete(&mut self) {
691        match complete(&self.commands, &self.line) {
692            Completion::Nothing => {}
693            Completion::Line(line) => {
694                self.line = line;
695                self.browsing = None;
696            }
697            Completion::List(matches) => self.lines.push(Tone::Text, matches.join("\n")),
698        }
699    }
700}
701
702impl<C: Copy> Console<C> {
703    /// Runs `line` as if it were typed and Enter pressed, but leaves the
704    /// line being typed as it is: brings the log to its newest lines, so
705    /// that what follows is in view, echoes the line in the log, after `>`,
706    /// keeps it in the history, and, if it names a command and its
707    /// arguments fit the command's usage, calls `run` with the command, its
708    /// arguments and where to print. An error, the line's or the one `run`
709    /// returns, is printed in red. A line of only whitespace does nothing.
710    pub fn run_line<F>(&mut self, line: &str, mut run: F)
711    where
712        F: FnMut(C, &Args<'_>, &mut ConsoleOut<'_>) -> Result<(), ConsoleError>,
713    {
714        let line = line.trim();
715        if line.is_empty() {
716            return;
717        }
718        self.lines.scroll = 0;
719        self.lines.push(Tone::Echo, format_args!("> {line}"));
720        if self.history.back().is_none_or(|last| last != line) {
721            if self.history.len() >= CONSOLE_HISTORY {
722                self.history.pop_front();
723            }
724            self.history.push_back(line.to_string());
725        }
726        self.browsing = None;
727        self.draft.clear();
728        if let Err(error) = self.dispatch(line, &mut run) {
729            self.lines.push(Tone::Error, &error);
730        }
731    }
732
733    /// Splits, checks and runs `line`.
734    fn dispatch<F>(&mut self, line: &str, run: &mut F) -> Result<(), ConsoleError>
735    where
736        F: FnMut(C, &Args<'_>, &mut ConsoleOut<'_>) -> Result<(), ConsoleError>,
737    {
738        let mut words = std::mem::take(&mut self.words);
739        let result = split(line, &mut words).and_then(|()| {
740            let Some((name, rest)) = words.split_first_mut() else {
741                return Ok(());
742            };
743            if name == HELP {
744                check(HELP_USAGE, rest)?;
745                return self.help(rest.first().map(String::as_str));
746            }
747            let Some(command) = self.commands.iter().find(|command| command.name == *name) else {
748                return Err(ConsoleError::UnknownCommand(name.clone()));
749            };
750            check(&command.usage, rest)?;
751            let args = Args {
752                usage: &command.usage,
753                words: rest,
754            };
755            let mut out = ConsoleOut {
756                lines: &mut self.lines,
757            };
758            run(command.command, &args, &mut out)
759        });
760        self.words = words;
761        result
762    }
763
764    /// `help`: every command's usage and help, in columns, or `name`'s.
765    fn help(&mut self, name: Option<&str>) -> Result<(), ConsoleError> {
766        let all = std::iter::once((HELP_USAGE, HELP_TEXT)).chain(
767            self.commands
768                .iter()
769                .map(|command| (command.usage.as_str(), command.help.as_str())),
770        );
771        let Some(name) = name else {
772            let width = all
773                .clone()
774                .map(|(usage, _)| usage.chars().count())
775                .max()
776                .unwrap_or(0);
777            for (usage, help) in all {
778                self.lines
779                    .push(Tone::Text, format_args!("{usage:<width$}  {help}"));
780            }
781            return Ok(());
782        };
783        let (usage, help) = all
784            .clone()
785            .find(|(usage, _)| usage.split_whitespace().next() == Some(name))
786            .ok_or_else(|| ConsoleError::UnknownCommand(name.to_string()))?;
787        self.lines.push(Tone::Text, format_args!("{usage}  {help}"));
788        Ok(())
789    }
790
791    /// Fills a window with the console: the log, as many of its lines as
792    /// fit, the newest at the bottom; and the command line under it, across
793    /// the window. The command line takes the keyboard when the console is
794    /// shown after a frame it was not, none of that frame's typing or keys
795    /// reaching it: a key that showed the console, typing its character as
796    /// it is pressed, is not typed. With it, Enter runs the line, as
797    /// [`Console::run_line`] does, and empties it; Tab completes; Up and
798    /// Down go through the history; PageUp and PageDown scroll the log a
799    /// page, as the wheel over it does by three lines. Each is handled after
800    /// the typing before it and before what follows, as the input ends a
801    /// frame at each ([`DebugInput`](crate::DebugInput)). A log scrolled up
802    /// stays on its lines as new ones come, until a line is run, and one at
803    /// its bottom shows the newest. The rows fit the window, which does not
804    /// scroll once its size is settled.
805    pub fn show<F>(&mut self, ui: &mut Ui<'_>, run: F)
806    where
807        F: FnMut(C, &Args<'_>, &mut ConsoleOut<'_>) -> Result<(), ConsoleError>,
808    {
809        // Shown after a frame it was not: the keys of this frame were
810        // pressed before the line had the keyboard, and are not its.
811        let frame = ui.frame_number();
812        let opened = self.shown_in.is_none_or(|shown| shown + 1 != frame);
813        if opened {
814            ui.focus_next();
815        }
816        self.shown_in = Some(frame);
817
818        // As many rows as fit in the window, the command line one of them,
819        // with no slack: a row that does not fit whole would scroll it.
820        let step = ui.row_step();
821        let rows = if step > 0.0 {
822            (ui.room() / step).floor().max(0.0) as usize
823        } else {
824            0
825        };
826        let page = rows.saturating_sub(1);
827        let count = self.lines.lines.len();
828        // The page keys, before the log is drawn, while the command line
829        // has had the keyboard.
830        if self.keyboard && !opened {
831            let by = page.max(1);
832            if ui.key_pressed(Key::PageUp) {
833                self.lines.scroll += by;
834            }
835            if ui.key_pressed(Key::PageDown) {
836                self.lines.scroll = self.lines.scroll.saturating_sub(by);
837            }
838        }
839        let wheel = ui.wheel_over(page as f32 * step);
840        self.wheel += wheel * LINES_A_WHEEL;
841        let lines = self.wheel.trunc();
842        self.wheel -= lines;
843        // A turn that is not finite scrolls this frame at most, and leaves
844        // no remainder to spoil the next.
845        if !self.wheel.is_finite() {
846            self.wheel = 0.0;
847        }
848        let scroll = self.lines.scroll as f32 + lines;
849        let top = count.saturating_sub(page);
850        self.lines.scroll = (scroll.max(0.0) as usize).min(top);
851
852        let end = count - self.lines.scroll;
853        let start = end.saturating_sub(page);
854        ui.skip_rows(page - (end - start));
855        let style = ui.style();
856        for line in self.lines.lines.range(start..end) {
857            let color = match line.tone {
858                Tone::Text => style.text,
859                Tone::Echo => style.accent,
860                Tone::Warning => WARNING,
861                Tone::Error => ERROR,
862                Tone::Color(color) => color,
863            };
864            ui.label_colored(color, &line.text);
865        }
866
867        let (response, keyboard) = ui.text_line("##nadir::console::line", &mut self.line);
868        self.keyboard = keyboard;
869        if response.changed {
870            self.browsing = None;
871        }
872        if response.submitted {
873            // The line's buffer is kept for the next line.
874            let mut line = std::mem::take(&mut self.line);
875            self.run_line(&line, run);
876            line.clear();
877            self.line = line;
878        }
879        // After the line's edits, which came before them: the input ends a
880        // frame at each of these keys.
881        if keyboard && !opened {
882            if ui.key_pressed(Key::Tab) {
883                self.complete();
884            }
885            if ui.key_pressed(Key::Up) {
886                self.older();
887            }
888            if ui.key_pressed(Key::Down) {
889                self.newer();
890            }
891        }
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898
899    fn words(line: &str) -> Result<Vec<String>, ConsoleError> {
900        let mut words = vec!["left over".to_string()];
901        split(line, &mut words).map(|()| words)
902    }
903
904    #[test]
905    fn a_line_splits_at_whitespace_and_a_quote_groups_words() {
906        assert_eq!(words("").unwrap(), Vec::<String>::new());
907        assert_eq!(words("  \t ").unwrap(), Vec::<String>::new());
908        assert_eq!(words("tp 10 -2.5").unwrap(), ["tp", "10", "-2.5"]);
909        assert_eq!(words("  tp\t10   20  ").unwrap(), ["tp", "10", "20"]);
910        assert_eq!(
911            words(r#"spawn "big rock" 1"#).unwrap(),
912            ["spawn", "big rock", "1"]
913        );
914        // A quote groups inside a word, and `""` is an empty word.
915        assert_eq!(words(r#"a"b c"d "" e"#).unwrap(), ["ab cd", "", "e"]);
916        // In quotes, `\"` is a quote and `\\` a backslash; other
917        // backslashes are kept, as outside quotes.
918        assert_eq!(
919            words(r#"say "a \"b\" c\\" C:\x\y "C:\My Traces\t.json""#).unwrap(),
920            ["say", r#"a "b" c\"#, r"C:\x\y", r"C:\My Traces\t.json"]
921        );
922        assert_eq!(words("é ü").unwrap(), ["é", "ü"]);
923    }
924
925    #[test]
926    fn a_quote_not_closed_is_an_error() {
927        assert_eq!(words(r#"say "hello"#), Err(ConsoleError::UnclosedQuote));
928        assert_eq!(words(r#"say "a\""#), Err(ConsoleError::UnclosedQuote));
929        assert_eq!(words(r#"""#), Err(ConsoleError::UnclosedQuote));
930    }
931
932    #[test]
933    fn a_usage_s_words_are_words_values_and_choices() {
934        assert_eq!(slot("dump"), Slot::Word("dump"));
935        assert_eq!(
936            slot("<x>"),
937            Slot::Value {
938                shown: "<x>",
939                optional: false
940            }
941        );
942        assert_eq!(
943            slot("[path]"),
944            Slot::Value {
945                shown: "[path]",
946                optional: true
947            }
948        );
949        // `[x y]` is two optional values.
950        assert!(matches!(slot("[x"), Slot::Value { optional: true, .. }));
951        assert!(matches!(slot("y]"), Slot::Value { optional: true, .. }));
952        assert_eq!(
953            slot("<error|warn>"),
954            Slot::Choice {
955                shown: "<error|warn>",
956                choices: "error|warn",
957                optional: false
958            }
959        );
960        assert_eq!(choices("a||b|").collect::<Vec<_>>(), ["a", "b"]);
961    }
962
963    fn checked(usage: &str, line: &str) -> Result<Vec<String>, ConsoleError> {
964        let mut words = words(line).expect("the line splits");
965        check(usage, &mut words).map(|()| words)
966    }
967
968    #[test]
969    fn arguments_are_checked_against_the_usage() {
970        let tp = "tp <x> <y>";
971        assert_eq!(checked(tp, "1 2").unwrap(), ["1", "2"]);
972        assert_eq!(
973            checked(tp, "1"),
974            Err(ConsoleError::MissingArgument {
975                usage: tp.into(),
976                argument: "<y>".into()
977            })
978        );
979        assert_eq!(
980            checked(tp, "1 2 3"),
981            Err(ConsoleError::TooManyArguments { usage: tp.into() })
982        );
983        let dump = "profile dump [path]";
984        assert_eq!(checked(dump, "dump").unwrap(), ["dump"]);
985        assert_eq!(checked(dump, "dump t.json").unwrap(), ["dump", "t.json"]);
986        assert_eq!(
987            checked(dump, ""),
988            Err(ConsoleError::MissingArgument {
989                usage: dump.into(),
990                argument: "`dump`".into()
991            })
992        );
993        assert_eq!(
994            checked(dump, "dupm").unwrap_err().to_string(),
995            "argument 1: `dupm` is not `dump`: profile dump [path]"
996        );
997        // A choice, ignoring case, spelt as the usage spells it.
998        let level = "log level <target> <error|warn|info>";
999        assert_eq!(
1000            checked(level, "level nadir_render WARN").unwrap(),
1001            ["level", "nadir_render", "warn"]
1002        );
1003        assert_eq!(
1004            checked(level, "level nadir_render loud")
1005                .unwrap_err()
1006                .to_string(),
1007            "<error|warn|info>: `loud` is not one of error, warn, info: \
1008             log level <target> <error|warn|info>"
1009        );
1010        // Optional values may be left out, from the end.
1011        let spawn = "spawn <prefab> [x] [y]";
1012        assert_eq!(checked(spawn, "rock").unwrap(), ["rock"]);
1013        assert_eq!(checked(spawn, "rock 1 2").unwrap(), ["rock", "1", "2"]);
1014        assert!(checked("quit", "now").is_err());
1015        assert_eq!(checked("quit", "").unwrap(), Vec::<String>::new());
1016    }
1017
1018    #[test]
1019    fn args_read_values_and_name_them_by_the_usage() {
1020        let words = ["1.5".to_string(), "x".to_string(), "inf".to_string()];
1021        let args = Args {
1022            usage: "move <dx> <dy> [dz]",
1023            words: &words,
1024        };
1025        assert_eq!((args.len(), args.is_empty()), (3, false));
1026        assert_eq!(args.f32(0), Ok(1.5));
1027        assert_eq!(args.str(1), Ok("x"));
1028        assert_eq!(
1029            args.f32(1).unwrap_err().to_string(),
1030            "<dy>: `x` is not a number: move <dx> <dy> [dz]"
1031        );
1032        assert!(args.f32(2).is_err(), "a number that is not finite");
1033        assert_eq!(args.get(3), None);
1034        assert_eq!(
1035            args.str(3).unwrap_err().to_string(),
1036            "argument 4 is missing: move <dx> <dy> [dz]"
1037        );
1038    }
1039
1040    fn console() -> Console<u8> {
1041        let mut console = Console::new();
1042        for (usage, id) in [
1043            ("tp <x> <y>", 1),
1044            ("timescale <scale>", 2),
1045            ("profile dump [path]", 3),
1046            ("log level <target> <error|warn|info|debug|trace>", 4),
1047            ("level <name>", 5),
1048            ("quit", 6),
1049        ] {
1050            console
1051                .register(usage, "does a thing", id)
1052                .expect("a usage");
1053        }
1054        console
1055    }
1056
1057    fn completed(line: &str) -> Completion {
1058        complete(&console().commands, line)
1059    }
1060
1061    fn list(words: &[&str]) -> Completion {
1062        Completion::List(words.iter().map(|word| (*word).to_string()).collect())
1063    }
1064
1065    #[test]
1066    fn tab_completes_a_command_s_name() {
1067        // One match: whole, and a space after it.
1068        assert_eq!(completed("q"), Completion::Line("quit ".into()));
1069        assert_eq!(completed("  ti"), Completion::Line("  timescale ".into()));
1070        assert_eq!(completed("he"), Completion::Line("help ".into()));
1071        assert_eq!(completed("le"), Completion::Line("level ".into()));
1072        assert_eq!(completed("lo"), Completion::Line("log ".into()));
1073        // Several: as far as they agree, then listed.
1074        assert_eq!(completed("p"), Completion::Line("profile ".into()));
1075        assert_eq!(completed("ti"), Completion::Line("timescale ".into()));
1076        assert_eq!(completed("l"), list(&["level", "log"]));
1077        assert_eq!(
1078            completed(""),
1079            list(&["help", "level", "log", "profile", "quit", "timescale", "tp"])
1080        );
1081        assert_eq!(completed("t"), list(&["timescale", "tp"]));
1082        assert_eq!(completed("x"), Completion::Nothing);
1083        // A name is matched as typed.
1084        assert_eq!(completed("Q"), Completion::Nothing);
1085    }
1086
1087    #[test]
1088    fn tab_completes_an_argument_from_the_usage() {
1089        // A word of the usage, after the name.
1090        assert_eq!(
1091            completed("profile "),
1092            Completion::Line("profile dump ".into())
1093        );
1094        assert_eq!(
1095            completed("profile d"),
1096            Completion::Line("profile dump ".into())
1097        );
1098        assert_eq!(completed("profile x"), Completion::Nothing);
1099        // A value has no completions.
1100        assert_eq!(completed("profile dump "), Completion::Nothing);
1101        assert_eq!(completed("tp "), Completion::Nothing);
1102        // A choice's choices.
1103        assert_eq!(
1104            completed("log level nadir_render "),
1105            list(&["debug", "error", "info", "trace", "warn"])
1106        );
1107        assert_eq!(
1108            completed("log level nadir_render w"),
1109            Completion::Line("log level nadir_render warn ".into())
1110        );
1111        // Past the usage, or after an unknown command, nothing.
1112        assert_eq!(completed("quit "), Completion::Nothing);
1113        assert_eq!(completed("nope "), Completion::Nothing);
1114        // `help`'s argument is a command's name.
1115        assert_eq!(completed("help q"), Completion::Line("help quit ".into()));
1116        assert_eq!(completed("help quit "), Completion::Nothing);
1117        // A word in quotes, or after a quote not closed, is not completed.
1118        assert_eq!(completed(r#"profile "d"#), Completion::Nothing);
1119        assert_eq!(completed(r#"level "a b"#), Completion::Nothing);
1120        assert_eq!(
1121            completed(r#"spawn "a b" "#),
1122            Completion::Nothing,
1123            "no command spawn here"
1124        );
1125    }
1126
1127    #[test]
1128    fn the_common_prefix_ends_on_a_character() {
1129        assert_eq!(common_prefix("abc", &["abd", "abx"]), "ab");
1130        assert_eq!(common_prefix("abc", &[]), "abc");
1131        assert_eq!(common_prefix("éa", &["éb"]), "é");
1132        assert_eq!(common_prefix("éa", &["eb"]), "");
1133    }
1134
1135    #[test]
1136    fn a_usage_must_start_with_a_name() {
1137        let mut console = console();
1138        for usage in [
1139            "", "   ", "<x>", "[x]", "\"say\"", "a|b", "help", "help [x]",
1140        ] {
1141            assert_eq!(
1142                console.register(usage, "", 9),
1143                Err(ConsoleError::BadUsage(usage.trim().into())),
1144                "{usage:?}"
1145            );
1146        }
1147        // One of a name already registered replaces it, in its place.
1148        console
1149            .register("  quit  now? ", " ends ", 7)
1150            .expect("a usage");
1151        let quit = console.commands.iter().find(|c| c.name == "quit").unwrap();
1152        assert_eq!(
1153            (quit.usage.as_str(), quit.help.as_str(), quit.command),
1154            ("quit  now?", "ends", 7)
1155        );
1156        assert_eq!(console.commands.len(), 6);
1157    }
1158
1159    /// Runs `line`, recording what ran.
1160    fn run(console: &mut Console<u8>, line: &str) -> Vec<(u8, Vec<String>)> {
1161        let mut ran = Vec::new();
1162        console.run_line(line, |command, args, out| {
1163            ran.push((
1164                command,
1165                (0..args.len())
1166                    .filter_map(|i| args.get(i))
1167                    .map(String::from)
1168                    .collect(),
1169            ));
1170            if command == 2 {
1171                let scale = args.f32(0)?;
1172                out.print(format_args!("scale {scale}\nok"));
1173            }
1174            if command == 6 {
1175                return Err(ConsoleError::Failed("not now".into()));
1176            }
1177            Ok(())
1178        });
1179        ran
1180    }
1181
1182    #[test]
1183    fn a_line_run_is_echoed_and_its_command_called_with_its_arguments() {
1184        let mut console = console();
1185        assert_eq!(
1186            run(&mut console, "  tp 1 2 "),
1187            [(1, vec!["1".into(), "2".into()])]
1188        );
1189        assert_eq!(
1190            run(&mut console, "log level nadir_render DEBUG"),
1191            [(
1192                4,
1193                vec!["level".into(), "nadir_render".into(), "debug".into()]
1194            )]
1195        );
1196        assert_eq!(run(&mut console, "timescale 0.5").len(), 1);
1197        assert_eq!(run(&mut console, "timescale fast").len(), 1);
1198        // Not run: a line that does not fit, an unknown command, a quote
1199        // not closed, whitespace.
1200        assert!(run(&mut console, "tp 1").is_empty());
1201        assert!(run(&mut console, "warp 1 2").is_empty());
1202        assert!(run(&mut console, "level \"x").is_empty());
1203        assert!(run(&mut console, "   ").is_empty());
1204        assert_eq!(run(&mut console, "quit").len(), 1);
1205        assert_eq!(
1206            console.lines().collect::<Vec<_>>(),
1207            [
1208                "> tp 1 2",
1209                "> log level nadir_render DEBUG",
1210                "> timescale 0.5",
1211                "scale 0.5",
1212                "ok",
1213                "> timescale fast",
1214                "<scale>: `fast` is not a number: timescale <scale>",
1215                "> tp 1",
1216                "<y> is missing: tp <x> <y>",
1217                "> warp 1 2",
1218                "no command `warp`: `help` lists them",
1219                "> level \"x",
1220                "a quote is not closed",
1221                "> quit",
1222                "not now",
1223            ]
1224        );
1225        let tones: Vec<Tone> = console.lines.lines.iter().map(|line| line.tone).collect();
1226        assert_eq!(tones[0], Tone::Echo);
1227        assert_eq!(tones[3], Tone::Text);
1228        assert_eq!(tones[6], Tone::Error);
1229        assert_eq!(tones[14], Tone::Error);
1230    }
1231
1232    #[test]
1233    fn help_lists_the_commands_in_columns_or_says_what_one_does() {
1234        let mut console = Console::new();
1235        console
1236            .register("tp <x> <y>", "moves the player", 1u8)
1237            .unwrap();
1238        console.register("quit", "ends the game", 2).unwrap();
1239        assert!(run(&mut console, "help").is_empty());
1240        assert!(run(&mut console, "help tp").is_empty());
1241        assert!(run(&mut console, "help help").is_empty());
1242        assert!(run(&mut console, "help nope").is_empty());
1243        assert!(run(&mut console, "help tp quit").is_empty());
1244        assert_eq!(
1245            console.lines().collect::<Vec<_>>(),
1246            [
1247                "> help",
1248                "help [command]  lists the commands, or says what one does",
1249                "tp <x> <y>      moves the player",
1250                "quit            ends the game",
1251                "> help tp",
1252                "tp <x> <y>  moves the player",
1253                "> help help",
1254                "help [command]  lists the commands, or says what one does",
1255                "> help nope",
1256                "no command `nope`: `help` lists them",
1257                "> help tp quit",
1258                "too many arguments: help [command]",
1259            ]
1260        );
1261    }
1262
1263    #[test]
1264    fn up_and_down_go_through_the_history_back_to_the_line_typed() {
1265        let mut console = console();
1266        console.older();
1267        assert_eq!(console.line(), "", "no history yet");
1268        for line in ["tp 1 2", "quit", "quit", "  tp 1 2", "level a"] {
1269            run(&mut console, line);
1270        }
1271        // `quit` twice in a row is kept once.
1272        assert_eq!(console.history, ["tp 1 2", "quit", "tp 1 2", "level a"]);
1273        console.set_line("half typ");
1274        console.older();
1275        assert_eq!(console.line(), "level a");
1276        console.older();
1277        console.older();
1278        console.older();
1279        assert_eq!(console.line(), "tp 1 2");
1280        console.older();
1281        assert_eq!(console.line(), "tp 1 2", "the oldest stays");
1282        console.newer();
1283        assert_eq!(console.line(), "quit");
1284        console.newer();
1285        console.newer();
1286        console.newer();
1287        assert_eq!(console.line(), "half typ", "back to what was typed");
1288        console.newer();
1289        assert_eq!(console.line(), "half typ");
1290        // The history keeps the last lines only.
1291        for n in 0..CONSOLE_HISTORY + 5 {
1292            run(&mut console, &format!("level {n}"));
1293        }
1294        assert_eq!(console.history.len(), CONSOLE_HISTORY);
1295        assert_eq!(console.history[0], "level 5");
1296    }
1297
1298    #[test]
1299    fn tab_completes_the_console_s_line_or_lists_the_matches() {
1300        let mut console = console();
1301        console.set_line("t");
1302        console.complete();
1303        assert_eq!(console.line(), "t");
1304        let listed: Vec<&str> = console.lines().collect();
1305        assert_eq!(listed, ["timescale", "tp"], "a match a line");
1306        console.set_line("prof");
1307        console.complete();
1308        assert_eq!(console.line(), "profile ");
1309        console.complete();
1310        assert_eq!(console.line(), "profile dump ");
1311    }
1312
1313    #[test]
1314    fn the_log_keeps_its_last_lines_colors_records_and_reuses_its_strings() {
1315        let mut console: Console<u8> = Console::new();
1316        console.log_record("2026-11-14T10:00:00.000Z WARN  game: low\nlower");
1317        console.log_record("2026-11-14T10:00:00.000Z ERROR game: boom");
1318        console.log_record("2026-11-14T10:00:00.000Z INFO  game: fine");
1319        console.print_error("bad\r\nworse");
1320        let tones: Vec<Tone> = console.lines.lines.iter().map(|line| line.tone).collect();
1321        assert_eq!(
1322            tones,
1323            [
1324                Tone::Warning,
1325                Tone::Warning,
1326                Tone::Error,
1327                Tone::Text,
1328                Tone::Error,
1329                Tone::Error
1330            ]
1331        );
1332        assert_eq!(console.lines().nth(1), Some("lower"));
1333        assert_eq!(console.lines().nth(5), Some("worse"));
1334        for n in 0..CONSOLE_LINES {
1335            console.print(format_args!("line {n}, long enough to keep"));
1336        }
1337        assert_eq!(console.lines().len(), CONSOLE_LINES);
1338        assert_eq!(console.lines().next(), Some("line 0, long enough to keep"));
1339        let oldest = console.lines.lines[0].text.as_ptr();
1340        console.print("short");
1341        assert_eq!(console.lines().last(), Some("short"));
1342        assert_eq!(console.lines.lines[CONSOLE_LINES - 1].text.as_ptr(), oldest);
1343    }
1344}