use std::{
io::{self, Stderr, Write, stderr},
time::Duration,
};
use crossfire::{RecvTimeoutError, Rx, mpsc::List};
use ratatui::{
Terminal, TerminalOptions, Viewport,
backend::CrosstermBackend,
buffer::Buffer,
crossterm::terminal::size,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::Widget,
};
use crate::{
board::{Board, Ended, 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 THINK_ROWS: u16 = 2;
const LANG_W: usize = 5;
const BAR_MAX: usize = 32;
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 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(24, |(_, h)| h);
let slot = jobs.max(1);
let full = 1 + THINK_ROWS;
let rows = if slot * full + 2 + 2 <= term_rows {
full
} else {
1
};
Self { slot, rows }
}
fn height(self) -> u16 {
self.slot * self.rows + 2
}
}
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());
std::process::exit(SIGINT_EXIT);
});
let mut board = Board::new();
let mut frame = 0usize;
'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,
}
frame = frame.wrapping_add(1);
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::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)),
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);
for (i, run) in board
.run_li
.iter()
.take(usize::from(layout.slot))
.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);
let cols = w.saturating_sub(6);
let style = if run.reply { REPLY } else { DIM };
for (k, text) in tail(&run.text, cols, usize::from(THINK_ROWS))
.into_iter()
.enumerate()
{
Line::from(vec![Span::styled(" │ ", DIM), Span::styled(text, style)])
.render(row(area, y + 1 + k as u16), buf);
}
}
let y = area.y + layout.slot * layout.rows + 1;
footer(board, w).render(row(area, y), 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 = 3 + 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 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 = 3 + LANG_W + 1 + width(&file) + 2 + width(&time) + 2;
let think = tail(&run.text, w.saturating_sub(used), 1)
.pop()
.unwrap_or_default();
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(think, if run.reply { REPLY } else { DIM }),
])
}
fn footer(board: &Board, w: usize) -> Line<'static> {
let view = board.view();
let bar_w = BAR_MAX.min(w.saturating_sub(40)).max(8);
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.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()
}