use super::terminal::{clean, wrap};
use crate::assets::{quoted, render};
use std::io::{self, IsTerminal, Write};
const WORDS: &str = include_str!(concat!(env!("NEOSIAN_ASSETS"), "/prompts/login.yaml"));
const PLAIN_WIDTH: usize = 80;
const WIDTH: std::ops::RangeInclusive<usize> = 20..=100;
pub const NAME: usize = 320;
pub fn say(key: &str) -> String {
quoted(WORDS, key).unwrap_or_else(|| panic!("login.yaml carries {key}"))
}
pub fn fill(key: &str, variables: &[(&str, &str)]) -> String {
render(&say(key), variables)
}
pub fn lost(_: io::Error) -> String {
"cannot display login progress".into()
}
pub fn host(text: &str) -> String {
clean(text, NAME, false)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Style {
pub color: bool,
pub width: usize,
}
impl Style {
pub const PLAIN: Self = Self {
color: false,
width: PLAIN_WIDTH,
};
pub fn stderr() -> Self {
let tty = io::stderr().is_terminal();
let columns = if tty {
console::Term::stderr()
.size_checked()
.map(|(_, c)| usize::from(c))
} else {
None
};
let set = |key: &str| std::env::var_os(key).filter(|v| !v.is_empty());
let dumb = std::env::var_os("TERM").is_some_and(|t| t == "dumb");
Self::detect(tty, columns, set("NO_COLOR").is_some() || dumb)
}
fn detect(tty: bool, columns: Option<usize>, refuse_color: bool) -> Self {
Self {
color: tty && cfg!(unix) && !refuse_color,
width: match columns {
Some(c) if tty && c > 0 => c.clamp(*WIDTH.start(), *WIDTH.end()),
_ => PLAIN_WIDTH,
},
}
}
fn paint(self, code: &str, text: &str) -> String {
if self.color {
format!("\u{1b}[{code}m{text}\u{1b}[0m")
} else {
text.to_owned()
}
}
}
#[derive(Clone, Copy)]
pub enum Mark {
Ok,
Warn,
Fail,
}
impl Mark {
fn text(self) -> (&'static str, &'static str) {
match self {
Self::Ok => ("ok", "32"),
Self::Warn => ("!", "33"),
Self::Fail => ("x", "31"),
}
}
}
pub struct View<W: Write> {
out: W,
style: Style,
step: Option<String>,
written: bool,
}
impl<W: Write> View<W> {
pub fn new(out: W, style: Style) -> Self {
Self {
out,
style,
step: None,
written: false,
}
}
pub fn step(&mut self, title: &str) -> io::Result<()> {
if self.step.as_deref() == Some(title) {
return Ok(());
}
if self.written {
writeln!(self.out)?;
}
writeln!(self.out, "{}", self.style.paint("1", title))?;
self.step = Some(title.to_owned());
self.written = true;
Ok(())
}
pub fn line(&mut self, text: &str) -> io::Result<()> {
self.lines("", 0, text)
}
pub fn say(&mut self, text: &str) -> io::Result<()> {
self.lines(" ", 2, text)
}
pub fn mark(&mut self, mark: Mark, text: &str) -> io::Result<()> {
let (word, code) = mark.text();
let lead = format!(
" {}{}",
self.style.paint(code, word),
" ".repeat(4 - word.len())
);
self.lines(&lead, 6, text)
}
pub fn fail(&mut self, text: &str) -> io::Result<()> {
let text = clean(text, 4096, false);
if self.step.is_some() {
self.mark(Mark::Fail, &text)
} else {
self.line(&text)
}
}
pub fn pair(&mut self, label: &str, pad: usize, text: &str) -> io::Result<()> {
let lead = format!(" {label:<pad$} ");
self.lines(&lead, pad + 4, text)
}
pub fn list(&mut self, items: &[String]) -> io::Result<()> {
for (n, item) in items.iter().enumerate() {
let lead = format!(" {}. ", n + 1);
let indent = lead.len();
self.lines(&lead, indent, item)?;
}
Ok(())
}
pub fn quote(&mut self, text: &str) -> io::Result<()> {
let text = clean(text, 8192, true);
for paragraph in text.lines() {
for line in wrap(paragraph, self.room(4)) {
writeln!(self.out, " | {line}")?;
}
}
self.written = true;
Ok(())
}
pub fn prompt(&mut self, question: &str) -> io::Result<()> {
write!(self.out, " {question} ")?;
self.written = true;
self.out.flush()
}
pub fn nested(&mut self) -> Nested<'_, W> {
self.written = true;
Nested {
out: &mut self.out,
line: Vec::new(),
fresh: true,
}
}
pub fn flush(&mut self) -> io::Result<()> {
self.out.flush()
}
fn room(&self, indent: usize) -> usize {
self.style.width.saturating_sub(indent).max(10)
}
fn lines(&mut self, lead: &str, indent: usize, text: &str) -> io::Result<()> {
let pad = " ".repeat(indent);
for (n, line) in wrap(text, self.room(indent)).iter().enumerate() {
writeln!(self.out, "{}{line}", if n == 0 { lead } else { &pad })?;
}
self.written = true;
Ok(())
}
}
pub struct Nested<'a, W: Write> {
out: &'a mut W,
line: Vec<u8>,
fresh: bool,
}
impl<W: Write> Nested<'_, W> {
fn emit(&mut self, end: bool) -> io::Result<()> {
let text = clean(&String::from_utf8_lossy(&self.line), usize::MAX, false);
self.line.clear();
if self.fresh && !(text.is_empty() && end) {
write!(self.out, " ")?;
}
write!(self.out, "{text}")?;
self.fresh = end;
if end {
writeln!(self.out)?;
}
Ok(())
}
}
impl<W: Write> Write for Nested<'_, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
for byte in buf {
if *byte == b'\n' {
self.emit(true)?;
} else {
self.line.push(*byte);
}
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
if !self.line.is_empty() {
self.emit(false)?;
}
self.out.flush()
}
}
impl<W: Write> Drop for Nested<'_, W> {
fn drop(&mut self) {
let _ = self.flush();
}
}
#[cfg(test)]
mod tests;