use std::fmt::Write as _;
use std::time::Duration;
use crate::LogChannel;
#[derive(Debug, Clone)]
pub struct TuiOptions {
pub log_lines: usize,
pub buffer_lines: usize,
pub refresh: Duration,
pub bar_width: usize,
pub color: bool,
channel: Option<LogChannel>,
}
impl Default for TuiOptions {
fn default() -> Self {
Self {
log_lines: 12,
buffer_lines: 500,
refresh: Duration::from_millis(100),
bar_width: 20,
color: false,
channel: None,
}
}
}
impl TuiOptions {
pub fn with_channel(mut self, channel: LogChannel) -> Self {
self.channel = Some(channel);
self
}
pub(crate) fn take_channel(&mut self) -> LogChannel {
self.channel
.take()
.unwrap_or_else(|| LogChannel::with_capacity(self.buffer_lines))
}
}
pub(crate) fn render_frame(
progress_line: &str,
channel: &LogChannel,
options: &TuiOptions,
) -> String {
let mut frame = String::new();
let _ = write!(frame, "{progress_line}\r\n");
let _ = write!(frame, "{}\r\n", "─".repeat(options.bar_width + 32));
let lines: Vec<String> = channel
.lines()
.into_iter()
.rev()
.take(options.log_lines)
.rev()
.collect();
for line in lines {
let line: String = line.chars().take(240).collect();
let _ = write!(frame, "{line}\r\n");
}
frame
}
impl tracing_subscriber::fmt::MakeWriter<'_> for LogChannel {
type Writer = LogChannel;
fn make_writer(&self) -> Self::Writer {
self.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn frame_fixture() -> LogChannel {
let channel = LogChannel::with_capacity(20);
for i in 0..5 {
channel.push_line(format!("log line {i}"));
}
channel
}
#[test]
fn frame_lays_out_progress_and_recent_logs() {
let channel = frame_fixture();
let frame = render_frame(
"[████████░░░░] 50.0% 5/10",
&channel,
&TuiOptions::default(),
);
assert!(
frame.starts_with("[████████░░░░] 50.0% 5/10\r\n"),
"{frame:?}"
);
assert!(frame.contains("─"), "{frame:?}");
assert!(frame.contains("log line 0\r\n"), "{frame:?}");
assert!(frame.ends_with("log line 4\r\n"), "{frame:?}");
}
#[test]
fn frame_keeps_only_recent_lines() {
let channel = frame_fixture();
let options = TuiOptions {
log_lines: 2,
..TuiOptions::default()
};
let frame = render_frame("progress", &channel, &options);
assert!(!frame.contains("log line 0"), "{frame:?}");
assert!(!frame.contains("log line 2"), "{frame:?}");
assert!(frame.ends_with("log line 4\r\n"), "{frame:?}");
}
#[test]
fn frame_truncates_overlong_log_lines() {
let channel = LogChannel::with_capacity(5);
channel.push_line("x".repeat(300));
let frame = render_frame("p", &channel, &TuiOptions::default());
assert!(frame.contains(&"x".repeat(240)), "应截断到 240 字符");
assert!(!frame.contains(&"x".repeat(241)), "{frame:?}");
}
#[test]
fn make_writer_routes_fmt_lines_into_buffer() {
use tracing_subscriber::fmt::MakeWriter as _;
let channel = LogChannel::with_capacity(10);
{
let mut writer = channel.clone().make_writer();
std::io::Write::write_all(&mut writer, b"hello from fmt\n").unwrap();
}
assert_eq!(channel.lines(), vec!["hello from fmt"]);
}
}