1use std::collections::VecDeque;
20use std::error::Error;
21use std::fmt::{self, Write as _};
22
23use nadir_core::{Color, Key};
24
25use crate::Ui;
26
27pub const CONSOLE_LINES: usize = 1000;
30
31pub const CONSOLE_HISTORY: usize = 100;
33
34const WARNING: Color = Color::rgb(255, 176, 64);
36
37const ERROR: Color = Color::rgb(255, 96, 96);
39
40const LINES_A_WHEEL: f32 = 3.0;
42
43const HELP: &str = "help";
45const HELP_USAGE: &str = "help [command]";
46const HELP_TEXT: &str = "lists the commands, or says what one does";
47
48#[non_exhaustive]
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub enum ConsoleError {
53 BadUsage(String),
56 UnclosedQuote,
58 UnknownCommand(String),
60 MissingArgument {
62 usage: String,
64 argument: String,
66 },
67 TooManyArguments {
69 usage: String,
71 },
72 InvalidArgument {
74 usage: String,
76 argument: String,
78 found: String,
80 expected: String,
82 },
83 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#[derive(Clone, Copy, Debug)]
118pub struct Args<'a> {
119 usage: &'a str,
120 words: &'a [String],
121}
122
123impl<'a> Args<'a> {
124 pub fn usage(&self) -> &'a str {
126 self.usage
127 }
128
129 pub fn len(&self) -> usize {
131 self.words.len()
132 }
133
134 pub fn is_empty(&self) -> bool {
136 self.words.is_empty()
137 }
138
139 pub fn get(&self, index: usize) -> Option<&'a str> {
141 self.words.get(index).map(String::as_str)
142 }
143
144 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 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 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
185pub struct ConsoleOut<'a> {
188 lines: &'a mut Lines,
189}
190
191impl ConsoleOut<'_> {
192 pub fn print(&mut self, text: impl fmt::Display) {
194 self.lines.push(Tone::Text, text);
195 }
196
197 pub fn print_colored(&mut self, color: Color, text: impl fmt::Display) {
199 self.lines.push(Tone::Color(color), text);
200 }
201}
202
203#[derive(Clone, Copy, Debug, PartialEq)]
205enum Tone {
206 Text,
207 Echo,
209 Warning,
210 Error,
211 Color(Color),
212}
213
214#[derive(Clone, Debug, PartialEq)]
216struct Line {
217 text: String,
218 tone: Tone,
219}
220
221#[derive(Debug, Default)]
223struct Lines {
224 lines: VecDeque<Line>,
225 scroll: usize,
227 scratch: String,
229}
230
231impl Lines {
232 fn push(&mut self, tone: Tone, text: impl fmt::Display) {
236 self.scratch.clear();
237 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#[derive(Clone, Debug)]
262struct Command<C> {
263 name: String,
264 usage: String,
265 help: String,
266 command: C,
267}
268
269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271enum Slot<'a> {
272 Word(&'a str),
274 Choice {
276 shown: &'a str,
277 choices: &'a str,
278 optional: bool,
279 },
280 Value { shown: &'a str, optional: bool },
282}
283
284fn 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
310fn choices(choices: &str) -> impl Iterator<Item = &str> {
312 choices.split('|').filter(|choice| !choice.is_empty())
313}
314
315fn 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
363fn 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#[derive(Clone, Debug, PartialEq, Eq)]
435enum Completion {
436 Nothing,
438 Line(String),
441 List(Vec<String>),
443}
444
445fn 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
500fn 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
515pub struct Console<C> {
547 commands: Vec<Command<C>>,
548 line: String,
549 history: VecDeque<String>,
550 browsing: Option<usize>,
552 draft: String,
554 lines: Lines,
555 wheel: f32,
557 shown_in: Option<u64>,
559 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 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 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 pub fn line(&self) -> &str {
618 &self.line
619 }
620
621 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 pub fn lines(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
630 self.lines.lines.iter().map(|line| line.text.as_str())
631 }
632
633 pub fn print(&mut self, text: impl fmt::Display) {
635 self.lines.push(Tone::Text, text);
636 }
637
638 pub fn print_error(&mut self, text: impl fmt::Display) {
640 self.lines.push(Tone::Error, text);
641 }
642
643 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 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 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 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 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 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 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 pub fn show<F>(&mut self, ui: &mut Ui<'_>, run: F)
806 where
807 F: FnMut(C, &Args<'_>, &mut ConsoleOut<'_>) -> Result<(), ConsoleError>,
808 {
809 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 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 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 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 let mut line = std::mem::take(&mut self.line);
875 self.run_line(&line, run);
876 line.clear();
877 self.line = line;
878 }
879 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 assert_eq!(words(r#"a"b c"d "" e"#).unwrap(), ["ab cd", "", "e"]);
916 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 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 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 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 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 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 assert_eq!(completed("Q"), Completion::Nothing);
1085 }
1086
1087 #[test]
1088 fn tab_completes_an_argument_from_the_usage() {
1089 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 assert_eq!(completed("profile dump "), Completion::Nothing);
1101 assert_eq!(completed("tp "), Completion::Nothing);
1102 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 assert_eq!(completed("quit "), Completion::Nothing);
1113 assert_eq!(completed("nope "), Completion::Nothing);
1114 assert_eq!(completed("help q"), Completion::Line("help quit ".into()));
1116 assert_eq!(completed("help quit "), Completion::Nothing);
1117 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 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 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 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 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 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}