use std::{
borrow::Cow,
io::{self, Stderr, stderr},
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
process::exit,
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
use crossfire::{RecvTimeoutError, Rx, mpsc::List};
use crossterm::terminal::size;
use itoa::Buffer as ItoaBuffer;
use ratatui::{
Terminal, TerminalOptions, Viewport,
backend::CrosstermBackend,
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::Widget,
};
use crate::{
board::{Act, Board, Ended, RetryState, Run, sec},
event::Event,
i18n::T,
plain,
text::{ARROW, count, dur, dur_col, eta, fit, fit_end, percent, summary, tail, tenth_sec, width},
};
type Term = Terminal<CrosstermBackend<Stderr>>;
const FRAME: Duration = Duration::from_millis(80);
const SPIN_LI: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const BODY_ROW: u16 = 2;
const FOOT_ROW: u16 = 2;
const HISTORY_ROW: u16 = 2;
const TERM_ROW: u16 = 24;
const THINK_MARK: &str = " │ ";
const REPLY_MARK: &str = " › ";
const RETRY_MARK: &str = " ! ";
const BODY_PAD: usize = 5;
const RIGHT_PAD: usize = 1;
const COL_GAP: &str = " ";
const COL_GAP_W: usize = COL_GAP.len();
const SPIN_W: usize = 3;
const COMPACT_FILE_DIV: usize = 3;
const BAR_MAX: usize = 32;
const BAR_MIN: usize = 8;
const PERMILLE: usize = 1000;
const BAR_ON: char = '━';
const BAR_OFF: char = '─';
const BAR_CHAR_BYTES: usize = BAR_ON.len_utf8();
const BAR_ON_STR: &str = "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
const BAR_OFF_STR: &str = "────────────────────────────────";
const SPACE_STR: &str = concat!(
" ",
" ",
" ",
" ",
);
const WAIT_BAR_W: usize = 6;
const WAIT_BAR_MIN_W: usize = 68;
const MID_MIN_W: usize = 8;
const SIGINT_EXIT: i32 = 130;
static INTR: AtomicBool = AtomicBool::new(false);
const _: () = {
assert!(BAR_ON.len_utf8() == BAR_OFF.len_utf8());
assert!(BAR_ON_STR.len() == BAR_MAX * BAR_CHAR_BYTES);
assert!(BAR_OFF_STR.len() == BAR_MAX * BAR_CHAR_BYTES);
assert!(SPACE_STR.len() == 256);
assert!(WAIT_BAR_W <= BAR_MAX);
};
const DIM: Style = Style::new().fg(Color::DarkGray);
const BOLD: Style = Style::new().add_modifier(Modifier::BOLD);
const OK: Style = Style::new().fg(Color::Green);
const BAD: Style = Style::new().fg(Color::Red);
const WARN: Style = Style::new().fg(Color::Yellow);
const NOTE: Style = Style::new().fg(Color::Yellow);
fn pad(n: usize) -> Cow<'static, str> {
if n <= SPACE_STR.len() {
Cow::Borrowed(&SPACE_STR[..n])
} else {
Cow::Owned(" ".repeat(n))
}
}
#[derive(Clone, Copy)]
struct Layout {
slot: u16,
row: u16,
}
impl Layout {
fn new(concurrency: u16) -> Self {
let term_row = size().map_or(TERM_ROW, |(_, h)| h);
let room = term_row.saturating_sub(FOOT_ROW + HISTORY_ROW).max(1);
let full = 1 + BODY_ROW;
let slot = concurrency.clamp(1, room);
let row = if slot.checked_mul(full).is_some_and(|n| n <= room) {
full
} else {
1
};
Self { slot, row }
}
fn height(self) -> u16 {
self.slot * self.row + FOOT_ROW
}
}
pub(crate) fn run(rx: &Rx<List<Event>>, concurrency: u16) {
let mut layout = Layout::new(concurrency);
let Ok(mut term) = Terminal::with_options(
CrosstermBackend::new(stderr()),
TerminalOptions {
viewport: Viewport::Inline(layout.height()),
},
) else {
plain::run(rx);
return;
};
let _ = ctrlc::set_handler(|| INTR.store(true, Ordering::Relaxed));
let res = catch_unwind(AssertUnwindSafe(|| {
let mut board = Board::new();
let begin = Instant::now();
let mut dim = size().unwrap_or((0, 0));
'main: loop {
match rx.recv_timeout(FRAME) {
Ok(event) => {
if apply(&mut term, &mut board, event) {
break;
}
while let Ok(event) = rx.try_recv() {
if apply(&mut term, &mut board, event) {
break 'main;
}
}
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => break,
}
if INTR.load(Ordering::Relaxed) {
let _ = close(&mut term, &board);
exit(SIGINT_EXIT);
}
let now = size().unwrap_or(dim);
if now != dim {
dim = now;
layout = Layout::new(concurrency);
let _ = term.autoresize();
let _ = term.clear();
}
let frame = (begin.elapsed().as_millis() / FRAME.as_millis()) as usize;
let _ = term.draw(|f| draw(f.area(), f.buffer_mut(), &board, layout, frame));
}
board
}));
match res {
Ok(board) => {
let _ = close(&mut term, &board);
}
Err(payload) => {
let _ = term.clear();
let _ = term.show_cursor();
resume_unwind(payload);
}
}
}
fn apply(term: &mut Term, board: &mut Board, event: Event) -> bool {
match board.apply(event) {
Act::None | Act::Start(_) | Act::Retry(_) => {}
Act::Text { id, text, reply } => {
if let Some(run) = board.run(id) {
run.push_tail(&text, reply);
}
}
Act::End(ended) => history(term, ended_line(&ended)),
Act::Log(text) => history(
term,
Line::from(vec![
Span::styled(format!(" {} ", T.ui.note()), NOTE),
Span::raw(text),
]),
),
Act::Close => return true,
}
false
}
fn history(term: &mut Term, line: Line<'static>) {
let _ = term.insert_before(1, |buf| line.render(buf.area, buf));
}
fn ended_line(ended: &Ended) -> Line<'static> {
let (tag, style) = match ended.err {
None => (format!(" {} ", T.ui.ok()), OK),
Some(_) => (format!(" {} ", T.ui.bad()), BAD),
};
let mut span_li = vec![Span::styled(tag, style)];
if ended.err.is_none() {
span_li.push(Span::styled(dur_col(ended.sec), DIM));
span_li.push(Span::raw(COL_GAP));
}
span_li.push(Span::styled(ended.name.from.clone(), DIM));
span_li.push(Span::styled(ARROW, DIM));
span_li.push(Span::styled(ended.name.out.clone(), DIM));
match &ended.err {
None => {
if ended.retry_cnt > 0 {
span_li.push(Span::styled(
format!(" {}", T.ui.retry_n(ended.retry_cnt)),
DIM,
));
}
}
Some(msg) => {
span_li.push(Span::raw(COL_GAP));
span_li.push(Span::styled(msg.clone(), BAD));
}
}
Line::from(span_li)
}
fn draw(area: Rect, buf: &mut Buffer, board: &Board, layout: Layout, frame: usize) {
let w = usize::from(area.width);
let now = Instant::now();
let fit_slot = area.height.saturating_sub(FOOT_ROW) / layout.row;
for (i, run) in board
.run_li
.iter()
.take(usize::from(layout.slot.min(fit_slot)))
.enumerate()
{
let y = area.y + i as u16 * layout.row;
let spin = SPIN_LI[(frame + i) % SPIN_LI.len()];
if layout.row == 1 {
compact(run, spin, w, now).render(row(area, y), buf);
continue;
}
header(run, spin, w).render(row(area, y), buf);
for (k, line) in body(run, w, now).into_iter().enumerate() {
line.render(row(area, y + 1 + k as u16), buf);
}
}
footer(board, w).render(row(area, area.bottom().saturating_sub(1)), buf);
}
fn row(area: Rect, y: u16) -> Rect {
Rect::new(area.x, y, area.width, 1)
}
fn header(run: &Run, spin: &'static str, w: usize) -> Line<'static> {
let time = dur(sec(run.begin));
let fixed = SPIN_W + width(&run.name.from) + width(ARROW) + width(&time) + COL_GAP_W;
let file = fit_end(&run.name.out, w.saturating_sub(fixed));
let gap = w.saturating_sub(fixed + width(&file)) + RIGHT_PAD;
let mut span_li = vec![
Span::raw(" "),
Span::styled(spin, DIM),
Span::raw(" "),
Span::styled(run.name.from.clone(), DIM),
Span::styled(ARROW, DIM),
Span::styled(file, DIM),
];
span_li.push(Span::raw(pad(gap)));
span_li.push(Span::styled(time, DIM));
Line::from(span_li)
}
fn retry_badge(r: &RetryState) -> String {
let mut out = T.ui.retry_badge(r.nth, r.total).into_owned();
if r.streak > 1 {
out.push_str(" · ×");
out.push_str(ItoaBuffer::new().format(r.streak));
}
out
}
fn countdown(r: &RetryState, now: Instant, show_bar: bool) -> (Vec<Span<'static>>, usize) {
if r.wait.is_zero() {
return (Vec::new(), 0);
}
let rem = r.rem(now);
if rem.is_zero() {
let reconnect = T.ui.reconnect();
return (vec![Span::styled(reconnect, DIM)], width(reconnect));
}
let mut num = String::with_capacity(8);
tenth_sec(rem, &mut num);
let wait_suffix = T.ui.retry_after();
let text_w = num.len() + 1 + width(wait_suffix);
if show_bar {
let total_ms = r.wait.as_millis().max(1);
let rem_ms = rem.as_millis().min(total_ms);
let lit = ((rem_ms * WAIT_BAR_W as u128).div_ceil(total_ms) as usize).clamp(1, WAIT_BAR_W);
(
vec![
Span::styled(&BAR_ON_STR[..lit * BAR_CHAR_BYTES], WARN),
Span::styled(&BAR_OFF_STR[..(WAIT_BAR_W - lit) * BAR_CHAR_BYTES], DIM),
Span::raw(" "),
Span::styled(num, WARN),
Span::raw(" "),
Span::styled(wait_suffix, DIM),
],
WAIT_BAR_W + 1 + text_w,
)
} else {
(
vec![
Span::styled(num, WARN),
Span::raw(" "),
Span::styled(wait_suffix, DIM),
],
text_w,
)
}
}
fn retry_line(
badge: String,
mid_src: &str,
mid_style: Style,
r: &RetryState,
now: Instant,
w: usize,
) -> (Line<'static>, bool) {
let col = w.saturating_sub(BODY_PAD + RIGHT_PAD);
let badge_w = width(&badge);
let (right_li, right_w) = countdown(r, now, w >= WAIT_BAR_MIN_W);
if right_w == 0 {
if let Some(mid_max) = col.checked_sub(badge_w + COL_GAP_W)
&& mid_max >= MID_MIN_W
{
let mid = fit(mid_src, mid_max);
return (
Line::from(vec![
Span::styled(RETRY_MARK, WARN),
Span::styled(badge, WARN),
Span::raw(COL_GAP),
Span::styled(mid, mid_style),
]),
true,
);
}
let clipped = if badge_w <= col {
badge
} else {
fit(&badge, col)
};
return (
Line::from(vec![
Span::styled(RETRY_MARK, WARN),
Span::styled(clipped, WARN),
]),
false,
);
}
if let Some(mid_max) = col.checked_sub(badge_w + COL_GAP_W * 2 + right_w)
&& mid_max >= MID_MIN_W
{
let mid = fit(mid_src, mid_max);
let gap = col - badge_w - COL_GAP_W - width(&mid) - right_w;
let mut span_li = Vec::with_capacity(5 + right_li.len());
span_li.push(Span::styled(RETRY_MARK, WARN));
span_li.push(Span::styled(badge, WARN));
span_li.push(Span::raw(COL_GAP));
span_li.push(Span::styled(mid, mid_style));
span_li.push(Span::raw(pad(gap)));
span_li.extend(right_li);
return (Line::from(span_li), true);
}
if let Some(gap) = col.checked_sub(badge_w + COL_GAP_W + right_w) {
let mut span_li = Vec::with_capacity(3 + right_li.len());
span_li.push(Span::styled(RETRY_MARK, WARN));
span_li.push(Span::styled(badge, WARN));
span_li.push(Span::raw(pad(gap + COL_GAP_W)));
span_li.extend(right_li);
return (Line::from(span_li), false);
}
let mut merged_src = badge;
merged_src.push(' ');
for s in &right_li {
merged_src.push_str(s.content.as_ref());
}
let merged = fit(&merged_src, col);
(
Line::from(vec![
Span::styled(RETRY_MARK, WARN),
Span::styled(merged, WARN),
]),
false,
)
}
fn body(run: &Run, w: usize, now: Instant) -> Vec<Line<'static>> {
let col = w.saturating_sub(BODY_PAD + RIGHT_PAD);
let row = usize::from(BODY_ROW);
if let Some(r) = &run.retry {
let badge = retry_badge(r);
if run.think.is_empty() && run.reply.is_empty() {
let (head, base_shown) = retry_line(badge, &r.base, DIM, r, now, w);
let sub = if base_shown || r.base.is_empty() {
fit(&r.err, col)
} else {
fit(&format!("{} · {}", r.base, r.err), col)
};
return vec![
head,
Line::from(vec![Span::styled(THINK_MARK, DIM), Span::styled(sub, DIM)]),
];
}
let mut line_li = Vec::with_capacity(row);
if let Some(text) = tail(&run.reply, col, 1).pop() {
line_li.push(Line::from(vec![
Span::styled(REPLY_MARK, DIM),
Span::styled(text, DIM),
]));
} else if let Some(text) = tail(&run.think, col, 1).pop() {
line_li.push(Line::from(vec![
Span::styled(THINK_MARK, DIM),
Span::styled(text, DIM),
]));
}
let detail = if r.base.is_empty() {
r.err.clone()
} else {
format!("{} · {}", r.base, r.err)
};
let (retry_row, _) = retry_line(badge, &detail, DIM, r, now, w);
line_li.push(retry_row);
return line_li;
}
let think_row = if run.reply.is_empty() { row } else { row - 1 };
let mut line_li: Vec<Line<'static>> = tail(&run.think, col, think_row)
.into_iter()
.map(|text| Line::from(vec![Span::styled(THINK_MARK, DIM), Span::styled(text, DIM)]))
.collect();
if let Some(text) = tail(&run.reply, col, 1).pop() {
line_li.push(Line::from(vec![
Span::styled(REPLY_MARK, DIM),
Span::styled(text, DIM),
]));
}
line_li
}
fn compact(run: &Run, spin: &'static str, w: usize, now: Instant) -> Line<'static> {
let time = dur_col(sec(run.begin));
let file = fit_end(&run.name.out, w / COMPACT_FILE_DIV);
let used = SPIN_W
+ width(&run.name.from)
+ width(ARROW)
+ width(&file)
+ COL_GAP_W
+ width(&time)
+ COL_GAP_W;
let avail = w.saturating_sub(used);
let (tail_str, style) = if let Some(r) = &run.retry {
let mut text = retry_badge(r);
if !r.wait.is_zero() {
text.push_str(" · ");
let rem = r.rem(now);
if rem.is_zero() {
text.push_str(T.ui.reconnect());
} else {
tenth_sec(rem, &mut text);
text.push(' ');
text.push_str(T.ui.retry_after());
}
if !r.base.is_empty() {
text.push_str(" · ");
text.push_str(&r.base);
}
} else if !r.base.is_empty() {
text.push(' ');
text.push_str(&r.base);
}
(fit(&text, avail), WARN)
} else {
let (text, style) = if run.reply.is_empty() {
(&run.think, DIM)
} else {
(&run.reply, DIM)
};
(tail(text, avail, 1).pop().unwrap_or_default(), style)
};
let mut span_li = vec![
Span::raw(" "),
Span::styled(spin, DIM),
Span::raw(" "),
Span::styled(run.name.from.clone(), DIM),
Span::styled(ARROW, DIM),
Span::styled(file, DIM),
];
span_li.push(Span::raw(COL_GAP));
span_li.push(Span::styled(time, DIM));
span_li.push(Span::raw(COL_GAP));
span_li.push(Span::styled(tail_str, style));
Line::from(span_li)
}
fn footer(board: &Board, w: usize) -> Line<'static> {
if !board.plan_ready {
return Line::from(vec![Span::raw(" "), Span::styled(T.ui.scan(), DIM)]);
}
let view = board.progress.view();
let mut tail_li = vec![
Span::raw(COL_GAP),
Span::styled(percent(&view), BOLD),
Span::raw(COL_GAP),
Span::raw(count(&view)),
Span::raw(COL_GAP),
Span::styled(eta(&view), DIM),
];
if board.hit > 0 {
tail_li.push(Span::styled(
format!(" {}", T.ui.count_cache(board.hit)),
DIM,
));
}
if board.retry > 0 {
tail_li.push(Span::styled(
format!(" {}", T.ui.count_retry(board.retry)),
WARN,
));
}
if board.fail > 0 {
tail_li.push(Span::styled(
format!(" {}", T.ui.count_fail(board.fail)),
BAD,
));
}
let tail_w = tail_li
.iter()
.map(|span| width(&span.content))
.sum::<usize>();
let bar_w = BAR_MAX.min(w.saturating_sub(1 + tail_w)).max(BAR_MIN);
let on = usize::from(view.permille) * bar_w / PERMILLE;
let mut span_li = vec![
Span::raw(" "),
Span::styled(
&BAR_ON_STR[..on * BAR_CHAR_BYTES],
Style::new().fg(Color::Cyan),
),
Span::styled(&BAR_OFF_STR[..(bar_w - on) * BAR_CHAR_BYTES], DIM),
];
span_li.extend(tail_li);
let line = Line::from(span_li);
if line.width() <= w {
line
} else {
Line::raw(fit(&line.to_string(), w))
}
}
fn close(term: &mut Term, board: &Board) -> io::Result<()> {
let line = Line::from(vec![
Span::styled(format!(" {} ", T.ui.summary_label()), BOLD),
Span::raw(summary(board.ok, board.hit, board.fail, board.sec())),
]);
term.insert_before(1, |buf| line.render(buf.area, buf))?;
let top = term.get_frame().area().as_position();
term.clear()?;
term.set_cursor_position(top)?;
term.show_cursor()
}