use std::{
borrow::Cow,
fmt::Write as _,
time::{Duration, Instant},
};
use itoa::Buffer as ItoaBuffer;
use ratatui::{
buffer::Buffer,
layout::Rect,
text::{Line, Span},
widgets::Widget,
};
use super::{
ACCENT, BAD, BAR_DOT, BAR_ON, BOLD, COL_GAP, COL_GAP_W, DIM, FAINT, RIGHT_PAD, WARN, bar_str,
pad, row_rect,
};
use crate::{
board::{Board, SlotEntry},
event::SlotState,
i18n::T,
text::{fit, fit_owned, fmt_tok, fmt_tok_word, tenth_sec, width},
};
const POOL_BAR_W: usize = 8;
const POOL_BAR_MIN_W: usize = 80;
pub(super) struct PoolCache {
last_pick: Instant,
keep_li: Vec<usize>,
rank_li: Vec<(u8, u16, u64, usize)>,
}
impl Default for PoolCache {
fn default() -> Self {
Self {
last_pick: Instant::now()
.checked_sub(Duration::from_secs(2))
.unwrap_or_else(Instant::now),
keep_li: Vec::new(),
rank_li: Vec::new(),
}
}
}
impl PoolCache {
fn select(&mut self, slot_li: &[SlotEntry], keep_n: usize, now: Instant) -> &[usize] {
let valid = self.keep_li.len() == keep_n && self.keep_li.iter().all(|&i| i < slot_li.len());
if valid && now.saturating_duration_since(self.last_pick) < Duration::from_secs(1) {
return &self.keep_li;
}
self.last_pick = now;
self.rank_li.clear();
self
.rank_li
.extend(slot_li.iter().enumerate().map(|(i, s)| {
let tier = if s.in_flight > 0 {
3
} else if s.cool_rem(now).is_some() {
2
} else if matches!(s.state, SlotState::Dead { .. }) {
1
} else {
0
};
(tier, s.in_flight, s.tok, i)
}));
self.rank_li.sort_unstable_by(|a, b| {
b.0
.cmp(&a.0)
.then(b.1.cmp(&a.1))
.then(b.2.cmp(&a.2))
.then(a.3.cmp(&b.3))
});
self.keep_li.clear();
self
.keep_li
.extend(self.rank_li.iter().take(keep_n).map(|x| x.3));
self.keep_li.sort_unstable();
&self.keep_li
}
}
pub(super) fn draw_pool(area: Rect, buf: &mut Buffer, board: &Board, cache: &mut PoolCache) {
let max_row = usize::from(area.height);
if max_row == 0 || board.slot_li.is_empty() {
return;
}
let w = usize::from(area.width);
let now = Instant::now();
if board.slot_li.len() <= max_row {
for (row_idx, slot) in board.slot_li.iter().enumerate() {
slot_line(slot, w, now).render(row_rect(area, area.y + row_idx as u16), buf);
}
return;
}
let show = max_row.saturating_sub(1);
let keep_li = cache.select(&board.slot_li, show, now);
for (row_idx, &slot_idx) in keep_li.iter().enumerate() {
slot_line(&board.slot_li[slot_idx], w, now)
.render(row_rect(area, area.y + row_idx as u16), buf);
}
if show < max_row {
folded_line(&board.slot_li, keep_li, w, now).render(row_rect(area, area.y + show as u16), buf);
}
}
fn slot_line<'a>(s: &'a SlotEntry, w: usize, now: Instant) -> Line<'a> {
let cool_rem = s.cool_rem(now);
let is_dead = matches!(s.state, SlotState::Dead { .. });
let is_cool = cool_rem.is_some();
let (glyph, glyph_style) = if is_dead {
(" ✕ ", BAD)
} else if is_cool {
(" ◐ ", WARN)
} else if s.in_flight > 0 {
(" ● ", ACCENT)
} else {
(" ○ ", FAINT)
};
let tok_full = if w >= 56 {
fmt_tok_word(s.tok)
} else {
fmt_tok(s.tok)
};
let tok_w = width(&tok_full);
let tok_col_w = 12usize.min(w / 4).max(tok_w);
let tok_pad = tok_col_w.saturating_sub(tok_w);
let state_text = state_label(s, cool_rem);
let state_style = if is_dead {
BAD
} else if is_cool {
WARN
} else if matches!(
s.state,
SlotState::Fast | SlotState::Probe | SlotState::Recover
) && s.in_flight > 0
{
ACCENT
} else {
DIM
};
let state_w = width(&state_text);
let state_col_w = 10usize.max(state_w);
let state_pad = state_col_w.saturating_sub(state_w);
let ratio: Cow<'static, str> = if is_dead {
Cow::Borrowed("0/—")
} else {
let mut num = ItoaBuffer::new();
let mut out = String::with_capacity(9);
out.push_str(num.format(s.in_flight));
out.push('/');
out.push_str(num.format(s.cwnd));
Cow::Owned(out)
};
let ratio_w = width(&ratio);
let ratio_col_w = 7usize.max(ratio_w);
let ratio_pad = ratio_col_w.saturating_sub(ratio_w);
let conc_word = if w >= 62 { T.ui.conc_word() } else { "" };
let conc_w = if conc_word.is_empty() {
0
} else {
1 + width(conc_word)
};
let show_bar = w >= POOL_BAR_MIN_W;
let bar_total_w = if show_bar { POOL_BAR_W + COL_GAP_W } else { 0 };
let right_w = bar_total_w
+ ratio_col_w
+ conc_w
+ COL_GAP_W
+ state_col_w
+ COL_GAP_W
+ tok_col_w
+ RIGHT_PAD;
let left_budget = w.saturating_sub(3 + COL_GAP_W + right_w).max(6);
let label = fit(&s.label, left_budget);
let label_pad = left_budget.saturating_sub(width(&label));
let mut span_li = Vec::with_capacity(14);
span_li.push(Span::styled(glyph, glyph_style));
span_li.push(Span::styled(label, if is_dead { DIM } else { BOLD }));
span_li.push(Span::raw(pad(label_pad + COL_GAP_W)));
if show_bar {
let lit = if is_dead || s.cwnd == 0 {
0
} else {
((usize::from(s.in_flight) * POOL_BAR_W).div_ceil(usize::from(s.cwnd))).min(POOL_BAR_W)
};
let bar_style = if is_cool {
WARN
} else if s.in_flight > 0 {
ACCENT
} else {
DIM
};
span_li.push(Span::styled(bar_str(BAR_ON, lit), bar_style));
span_li.push(Span::styled(bar_str(BAR_DOT, POOL_BAR_W - lit), FAINT));
span_li.push(Span::raw(COL_GAP));
}
if ratio_pad > 0 {
span_li.push(Span::raw(pad(ratio_pad)));
}
span_li.push(Span::styled(
ratio,
if s.in_flight > 0 { ACCENT } else { DIM },
));
if !conc_word.is_empty() {
span_li.push(Span::raw(" "));
span_li.push(Span::styled(conc_word, DIM));
}
span_li.push(Span::raw(COL_GAP));
span_li.push(Span::styled(state_text, state_style));
span_li.push(Span::raw(pad(state_pad + COL_GAP_W + tok_pad)));
span_li.push(Span::styled(tok_full, if s.tok > 0 { BOLD } else { DIM }));
Line::from(span_li)
}
fn state_label(s: &SlotEntry, cool_rem: Option<Duration>) -> Cow<'static, str> {
if let Some(rem) = cool_rem {
let mut sec_buf = String::with_capacity(8);
tenth_sec(rem, &mut sec_buf);
return T.ui.phase_cool(sec_buf);
}
match s.state {
SlotState::Idle => Cow::Borrowed(T.ui.phase_idle()),
SlotState::Fast => Cow::Borrowed(T.ui.phase_fast()),
SlotState::Probe => Cow::Borrowed(T.ui.phase_probe()),
SlotState::Cruise => Cow::Borrowed(T.ui.phase_cruise()),
SlotState::Cool { .. } | SlotState::Recover => Cow::Borrowed(T.ui.phase_recover()),
SlotState::Dead { code } => {
if code > 0 {
T.ui.phase_dead(code)
} else {
Cow::Borrowed(T.ui.phase_dead_plain())
}
}
}
}
fn folded_line(slot_li: &[SlotEntry], keep_li: &[usize], w: usize, now: Instant) -> Line<'static> {
let mut hidden = 0usize;
let mut conc = 0u64;
let mut cool = 0usize;
let mut idle = 0usize;
let mut dead = 0usize;
let mut tok = 0u64;
let mut keep_cur = 0usize;
for (i, s) in slot_li.iter().enumerate() {
if keep_li.get(keep_cur) == Some(&i) {
keep_cur += 1;
continue;
}
hidden += 1;
conc += u64::from(s.in_flight);
tok = tok.saturating_add(s.tok);
if matches!(s.state, SlotState::Dead { .. }) {
dead += 1;
} else if s.cool_rem(now).is_some() {
cool += 1;
} else if s.in_flight == 0 {
idle += 1;
}
}
let mut info = String::with_capacity(64);
let _ = write!(info, "{}", T.ui.pool_conc(conc));
if cool > 0 {
let _ = write!(info, " · {}", T.ui.pool_cool(cool));
}
if idle > 0 {
let _ = write!(info, " · {}", T.ui.pool_idle(idle));
}
if dead > 0 {
let _ = write!(info, " · {}", T.ui.pool_dead(dead));
}
let _ = write!(info, " · {}", T.ui.pool_tok(fmt_tok(tok)));
let msg = format!(" … {}", T.ui.pool_more(hidden, info));
Line::from(Span::styled(
fit_owned(msg, w.saturating_sub(RIGHT_PAD)),
DIM,
))
}