use std::{
cell::Cell,
env,
io::{IsTerminal, stderr, stdout},
thread::{self, JoinHandle},
};
use crossfire::{
MTx,
mpsc::{self, List},
};
use crate::{
event::{Event, Name},
i18n::T,
job::Job,
plain,
text::one_line,
tty,
};
const ENV_UI: &str = "I18N_UI";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
#[default]
Auto,
Tty,
Plain,
}
impl Mode {
fn tty(self) -> bool {
match self {
Self::Tty => true,
Self::Plain => false,
Self::Auto => match env::var(ENV_UI).as_deref() {
Ok("tty") => true,
Ok("plain") => false,
_ => {
stderr().is_terminal()
&& stdout().is_terminal()
&& env::var_os("CI").is_none()
&& env::var("TERM").map_or(true, |term| term != "dumb")
}
},
}
}
}
pub struct Ui {
tx: MTx<List<Event>>,
reply: bool,
concurrency: u16,
next: Cell<u32>,
thread: Option<JoinHandle<()>>,
}
impl Ui {
pub fn new(mode: Mode, concurrency: u16) -> Self {
let (tx, rx) = mpsc::unbounded_blocking();
let tty = mode.tty();
let thread = thread::Builder::new()
.name("i18n_ui".into())
.spawn(move || {
if tty {
tty::run(&rx, concurrency);
} else {
plain::run(&rx);
}
})
.inspect_err(|e| eprintln!("{}", T.ui.no_ui(e.to_string())))
.ok();
Self {
tx,
reply: tty,
concurrency,
next: Cell::new(0),
thread,
}
}
fn send(&self, event: Event) {
let _ = self.tx.send(event);
}
pub fn plan(&self, job: usize, cache: usize) {
self.send(Event::Plan {
job,
concurrency: self.concurrency,
cache,
});
}
pub fn hit(&self) {
self.send(Event::Hit);
}
pub fn grow(&self) {
self.send(Event::Grow);
}
pub fn skip(&self) {
self.send(Event::Skip);
}
pub fn job(&self, from: &str, out: &str) -> Job {
let id = self.next.get();
self.next.set(id.wrapping_add(1));
self.send(Event::Start {
id,
name: Name {
from: one_line(from),
out: one_line(out),
},
});
Job::new(self.tx.clone(), id, self.reply)
}
pub fn log(&self, text: &str) {
self.send(Event::Log(one_line(text)));
}
}
impl Drop for Ui {
fn drop(&mut self) {
self.send(Event::Close);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}