use std::{
borrow::Cow,
io::{self, Stderr, stderr},
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::{Board, Ended, RetryState, Run, sec},
event::Event,
plain,
text::{LANG_W, count, dur, eta, fit, fit_end, percent, summary, tail, tenth_sec, width},
};
type Term = Terminal<CrosstermBackend<Stderr>>;
const FRAME: Duration = Duration::from_millis(80);
const SPIN: [&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_RESERVE: usize = 40;
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 = " \
\
\
";
const WAIT_BAR_W: usize = 6;
const WAIT_BAR_MIN_W: usize = 68;
const MID_MIN_W: usize = 8;
const WAIT_SUFFIX: &str = " 后重试";
const RECONNECT: &str = "重连中…";
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!(WAIT_BAR_W <= BAR_MAX);
};
const DIM: Style = Style::new().fg(Color::DarkGray);
const LANG: Style = Style::new().fg(Color::Cyan).add_modifier(Modifier::BOLD);
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);
const REPLY: Style = Style::new().fg(Color::Gray);
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(job: 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 = job.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>>, job: u16) {
let layout = Layout::new(job);
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 mut board = Board::new();
let begin = Instant::now();
let mut width = size().map_or(0, |(w, _)| w);
'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_w = size().map_or(width, |(w, _)| w);
if now_w != width {
width = now_w;
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));
}
let _ = close(&mut term, &board);
}
fn apply(term: &mut Term, board: &mut Board, event: Event) -> bool {
match event {
Event::Plan { weight, job } => board.plan(weight, job),
Event::Hit { weight } => board.hit(weight),
Event::Start { id, name, weight } => board.start(id, name, weight),
Event::Text { id, text, reply } => {
if let Some(run) = board.run(id) {
run.push_tail(&text, reply);
}
}
Event::Retry {
id,
nth,
total,
wait,
base,
err,
} => {
board.on_retry(id, nth, total, wait, base, err);
}
Event::End { id, err } => {
if let Some((_, ended)) = board.end(id, err) {
history(term, ended_line(&ended));
}
}
Event::Log(text) => history(
term,
Line::from(vec![Span::styled(" 提示 ", NOTE), Span::raw(text)]),
),
Event::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 => (" 完成 ", OK),
Some(_) => (" 失败 ", BAD),
};
let mut span_li = vec![
Span::styled(tag, style),
Span::styled(format!("{:<LANG_W$} ", ended.name.lang), LANG),
Span::raw(ended.name.file.clone()),
Span::raw(" "),
];
match &ended.err {
None => {
span_li.push(Span::styled(dur(ended.sec), DIM));
if ended.retry_cnt > 0 {
let mut buf = ItoaBuffer::new();
let mut s = String::with_capacity(12);
s.push_str(" 重试 ");
s.push_str(buf.format(ended.retry_cnt));
span_li.push(Span::styled(s, DIM));
}
}
Some(msg) => 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[(frame + i) % SPIN.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 + LANG_W + 1 + width(&time) + COL_GAP_W;
let file = fit_end(&run.name.file, w.saturating_sub(fixed));
let gap = w.saturating_sub(fixed + width(&file)) + RIGHT_PAD;
Line::from(vec![
Span::raw(" "),
Span::styled(spin, LANG),
Span::raw(" "),
Span::styled(format!("{:<LANG_W$} ", run.name.lang), LANG),
Span::raw(file),
Span::raw(pad(gap)),
Span::styled(time, DIM),
])
}
fn retry_badge(r: &RetryState) -> String {
let mut buf = ItoaBuffer::new();
let mut out = String::with_capacity(24);
out.push_str("第 ");
out.push_str(buf.format(r.nth));
out.push('/');
out.push_str(buf.format(r.total));
out.push_str(" 轮");
if r.streak > 1 {
out.push_str(" · ×");
out.push_str(buf.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() {
return (vec![Span::styled(RECONNECT, LANG)], width(RECONNECT));
}
let mut num = String::with_capacity(8);
tenth_sec(rem, &mut num);
let text_w = num.len() + 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::styled(WAIT_SUFFIX, DIM),
],
WAIT_BAR_W + 1 + text_w,
)
} else {
(
vec![Span::styled(num, WARN), 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, REPLY, 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, LANG),
Span::styled(text, REPLY),
]));
} 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, LANG),
Span::styled(text, REPLY),
]));
}
line_li
}
fn compact(run: &Run, spin: &'static str, w: usize, now: Instant) -> Line<'static> {
let time = dur(sec(run.begin));
let file = fit_end(&run.name.file, w / COMPACT_FILE_DIV);
let used = SPIN_W + LANG_W + 1 + 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(RECONNECT);
} else {
tenth_sec(rem, &mut text);
text.push_str(WAIT_SUFFIX);
}
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, REPLY)
};
(tail(text, avail, 1).pop().unwrap_or_default(), style)
};
Line::from(vec![
Span::raw(" "),
Span::styled(spin, LANG),
Span::raw(" "),
Span::styled(format!("{:<LANG_W$} ", run.name.lang), LANG),
Span::raw(file),
Span::raw(COL_GAP),
Span::styled(time, DIM),
Span::raw(COL_GAP),
Span::styled(tail_str, style),
])
}
fn footer(board: &Board, w: usize) -> Line<'static> {
let view = board.view();
let bar_w = BAR_MAX.min(w.saturating_sub(BAR_RESERVE)).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::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),
];
let mut buf = ItoaBuffer::new();
if board.hit > 0 {
span_li.push(Span::styled(
format!(" 缓存 {}", buf.format(board.hit)),
DIM,
));
}
if board.retry > 0 {
span_li.push(Span::styled(
format!(" 重试 {}", buf.format(board.retry)),
WARN,
));
}
if board.fail > 0 {
span_li.push(Span::styled(
format!(" 失败 {}", buf.format(board.fail)),
BAD,
));
}
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(" 汇总 ", 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()
}