use std::{
io::{self, Stderr, Write, stderr},
process::exit,
time::{Duration, Instant},
};
use crossfire::{RecvTimeoutError, Rx, mpsc::List};
use crossterm::terminal::size;
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, secs},
event::Event,
plain,
text::{count, dur, eta, fit, fit_end, percent, summary, tail, width},
};
type Term = Terminal<CrosstermBackend<Stderr>>;
const FRAME: Duration = Duration::from_millis(80);
const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const BODY_ROWS: u16 = 2;
const FOOT_ROWS: u16 = 2;
const HISTORY_ROWS: u16 = 2;
const TERM_ROWS: u16 = 24;
const THINK_MARK: &str = " │ ";
const REPLY_MARK: &str = " › ";
const RETRY_MARK: &str = " ! ";
const BODY_PAD: usize = 5;
const SPIN_W: usize = 3;
const LANG_W: usize = 5;
const BAR_MAX: usize = 32;
const BAR_MIN: usize = 8;
const BAR_RESERVE: usize = 40;
const BAR_ON: char = '━';
const BAR_OFF: char = '─';
const RESTORE: &str = "\x1b[0m\x1b[?25h\n";
const SIGINT_EXIT: i32 = 130;
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);
#[derive(Clone, Copy)]
struct Layout {
slot: u16,
rows: u16,
}
impl Layout {
fn new(jobs: u16) -> Self {
let term_rows = size().map_or(TERM_ROWS, |(_, h)| h);
let room = term_rows.saturating_sub(FOOT_ROWS + HISTORY_ROWS).max(1);
let full = 1 + BODY_ROWS;
let slot = jobs.clamp(1, room);
let rows = if slot.checked_mul(full).is_some_and(|n| n <= room) {
full
} else {
1
};
Self { slot, rows }
}
fn height(self) -> u16 {
self.slot * self.rows + FOOT_ROWS
}
}
pub(crate) fn run(rx: &Rx<List<Event>>, jobs: u16) {
let layout = Layout::new(jobs);
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(|| {
let _ = stderr().write_all(RESTORE.as_bytes());
exit(SIGINT_EXIT);
});
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,
}
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,
base,
err,
} => {
board.on_retry(id, nth, total, 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.secs), DIM));
if ended.retry_cnt > 0 {
span_li.push(Span::styled(format!(" 重试 {}", ended.retry_cnt), 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 fit = area.height.saturating_sub(FOOT_ROWS) / layout.rows;
for (i, run) in board
.run_li
.iter()
.take(usize::from(layout.slot.min(fit)))
.enumerate()
{
let y = area.y + i as u16 * layout.rows;
let spin = SPIN[(frame + i) % SPIN.len()];
if layout.rows == 1 {
compact(run, spin, w).render(row(area, y), buf);
continue;
}
header(run, spin, w).render(row(area, y), buf);
for (k, line) in body(run, w).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(secs(run.begin));
let fixed = SPIN_W + LANG_W + 1 + width(&time) + 2;
let file = fit_end(&run.name.file, w.saturating_sub(fixed));
let gap = w.saturating_sub(fixed + width(&file)) + 1;
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(" ".repeat(gap)),
Span::styled(time, DIM),
])
}
fn retry_badge(r: &RetryState) -> String {
if r.streak > 1 {
format!("第 {}/{} 轮 · ×{}", r.nth, r.total, r.streak)
} else {
format!("第 {}/{} 轮", r.nth, r.total)
}
}
fn body(run: &Run, w: usize) -> Vec<Line<'static>> {
let cols = w.saturating_sub(BODY_PAD + 1);
let rows = usize::from(BODY_ROWS);
if let Some(r) = &run.retry {
let badge = retry_badge(r);
let badge_w = width(&badge);
if run.think.is_empty() && run.reply.is_empty() {
let rest = cols.saturating_sub(badge_w + 2);
return vec![
Line::from(vec![
Span::styled(RETRY_MARK, WARN),
Span::styled(badge, WARN),
Span::raw(" "),
Span::styled(fit(&r.base, rest), REPLY),
]),
Line::from(vec![
Span::styled(THINK_MARK, DIM),
Span::styled(fit(&r.err, cols), DIM),
]),
];
}
let mut line_li = Vec::with_capacity(rows);
if let Some(text) = tail(&run.reply, cols, 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, cols, 1).pop() {
line_li.push(Line::from(vec![
Span::styled(THINK_MARK, DIM),
Span::styled(text, DIM),
]));
}
let rest = cols.saturating_sub(badge_w + 2);
let detail = fit(&format!("{} · {}", r.base, r.err), rest);
line_li.push(Line::from(vec![
Span::styled(RETRY_MARK, WARN),
Span::styled(badge, WARN),
Span::raw(" "),
Span::styled(detail, DIM),
]));
return line_li;
}
let think_rows = if run.reply.is_empty() { rows } else { rows - 1 };
let mut line_li: Vec<Line<'static>> = tail(&run.think, cols, think_rows)
.into_iter()
.map(|text| Line::from(vec![Span::styled(THINK_MARK, DIM), Span::styled(text, DIM)]))
.collect();
if let Some(text) = tail(&run.reply, cols, 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) -> Line<'static> {
let time = dur(secs(run.begin));
let file = fit_end(&run.name.file, w / 3);
let used = SPIN_W + LANG_W + 1 + width(&file) + 2 + width(&time) + 2;
let avail = w.saturating_sub(used);
let (tail_str, style) = if let Some(r) = &run.retry {
(fit(&format!("{} {}", retry_badge(r), r.base), 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(" "),
Span::styled(time, DIM),
Span::raw(" "),
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 / 1000;
let mut span_li = vec![
Span::raw(" "),
Span::styled(BAR_ON.to_string().repeat(on), Style::new().fg(Color::Cyan)),
Span::styled(BAR_OFF.to_string().repeat(bar_w - on), DIM),
Span::raw(" "),
Span::styled(percent(&view), BOLD),
Span::raw(" "),
Span::raw(count(&view)),
Span::raw(" "),
Span::styled(eta(&view), DIM),
];
if board.hit > 0 {
span_li.push(Span::styled(format!(" 缓存 {}", board.hit), DIM));
}
if board.retry > 0 {
span_li.push(Span::styled(format!(" 重试 {}", board.retry), WARN));
}
if board.fail > 0 {
span_li.push(Span::styled(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.secs())),
]);
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()
}