Skip to main content

memseek_test/
tui.rs

1//! 终端 TUI 模式(需开启 feature `tui`)。
2//!
3//! 进入 alternate screen(`\x1b[?1049h`)全屏显示:顶部固定当前场景进度行,
4//! 下方日志滚动区。所有终端字节都经渲染任务统一绘制:框架内部日志与业务
5//! 日志先进 [`LogChannel`] 环形缓冲再入屏,消除多写入者的字节级交错。
6//!
7//! 业务日志接入(可选):把 [`LogChannel`] 作为 writer 挂到 tracing 上,
8//! 日志区即可显示业务侧输出,且不替换用户已有的 subscriber:
9//!
10//! ```ignore
11//! use tracing_subscriber::prelude::*;
12//! use memseek_test::{
13//!     LogChannel, manager::{ManagerConfig, ScenarioManager},
14//! };
15//!
16//! let channel = LogChannel::with_capacity(500);
17//! tracing_subscriber::registry()
18//!     .with(tracing_subscriber::fmt::layer().with_writer(channel.clone()))
19//!     .init();
20//!
21//! let manager = ScenarioManager::new(
22//!     ManagerConfig::new(8).with_tui_options(memseek_test::tui::TuiOptions::default().with_channel(channel)),
23//! );
24//! ```
25//!
26//! 非 TTY(CI/重定向)时自动静默(不进入全屏);每次运行结束后日志缓冲
27//! 回放到 stderr,保证日志档案完整。
28//!
29//! 已知限制:终端高度未知,日志区固定显示 [`TuiOptions::log_lines`] 行
30//! (默认 12),若终端行数 < 进度区 + 日志区,进度行会被顶出可视区,
31//! 请调小 `log_lines`。
32
33use std::fmt::Write as _;
34use std::time::Duration;
35
36use crate::LogChannel;
37
38/// 终端 TUI 显示选项。
39#[derive(Debug, Clone)]
40pub struct TuiOptions {
41    /// 日志区固定显示行数(默认 12)
42    pub log_lines: usize,
43    /// 日志缓冲容量:超过丢最旧;TUI 退出时完整回放到 stderr(默认 500)
44    pub buffer_lines: usize,
45    /// 刷新间隔(默认 100ms)
46    pub refresh: Duration,
47    /// 进度条宽度(字符数,默认 20)
48    pub bar_width: usize,
49    /// 进度行是否启用 ANSI 颜色,默认 `false`
50    pub color: bool,
51    /// 日志通道;`None` 时由 Manager 自动创建(仅收编框架内部日志)
52    channel: Option<LogChannel>,
53}
54
55impl Default for TuiOptions {
56    fn default() -> Self {
57        Self {
58            log_lines: 12,
59            buffer_lines: 500,
60            refresh: Duration::from_millis(100),
61            bar_width: 20,
62            color: false,
63            channel: None,
64        }
65    }
66}
67
68impl TuiOptions {
69    /// 指定日志通道:同时作为用户 tracing 日志的接入点(见模块文档示例)。
70    pub fn with_channel(mut self, channel: LogChannel) -> Self {
71        self.channel = Some(channel);
72        self
73    }
74
75    pub(crate) fn take_channel(&mut self) -> LogChannel {
76        self.channel
77            .take()
78            .unwrap_or_else(|| LogChannel::with_capacity(self.buffer_lines))
79    }
80}
81
82/// 组装一帧 TUI 画面(纯函数,便于测试):进度行 + 分隔线 + 最近日志。
83pub(crate) fn render_frame(
84    progress_line: &str,
85    channel: &LogChannel,
86    options: &TuiOptions,
87) -> String {
88    let mut frame = String::new();
89    let _ = write!(frame, "{progress_line}\r\n");
90    let _ = write!(frame, "{}\r\n", "─".repeat(options.bar_width + 32));
91
92    let lines: Vec<String> = channel
93        .lines()
94        .into_iter()
95        .rev()
96        .take(options.log_lines)
97        .rev()
98        .collect();
99    for line in lines {
100        let line: String = line.chars().take(240).collect();
101        let _ = write!(frame, "{line}\r\n");
102    }
103
104    frame
105}
106
107/// [`LogChannel`] 作为 `tracing_subscriber::fmt` writer 的适配:
108/// 业务日志按行进入环形缓冲(供 TUI 日志区与退出回放使用)。
109impl tracing_subscriber::fmt::MakeWriter<'_> for LogChannel {
110    type Writer = LogChannel;
111
112    fn make_writer(&self) -> Self::Writer {
113        self.clone()
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    fn frame_fixture() -> LogChannel {
122        let channel = LogChannel::with_capacity(20);
123        for i in 0..5 {
124            channel.push_line(format!("log line {i}"));
125        }
126        channel
127    }
128
129    #[test]
130    fn frame_lays_out_progress_and_recent_logs() {
131        let channel = frame_fixture();
132        let frame = render_frame(
133            "[████████░░░░] 50.0% 5/10",
134            &channel,
135            &TuiOptions::default(),
136        );
137
138        assert!(
139            frame.starts_with("[████████░░░░] 50.0% 5/10\r\n"),
140            "{frame:?}"
141        );
142        assert!(frame.contains("─"), "{frame:?}");
143        assert!(frame.contains("log line 0\r\n"), "{frame:?}");
144        assert!(frame.ends_with("log line 4\r\n"), "{frame:?}");
145    }
146
147    #[test]
148    fn frame_keeps_only_recent_lines() {
149        let channel = frame_fixture();
150        let options = TuiOptions {
151            log_lines: 2,
152            ..TuiOptions::default()
153        };
154        let frame = render_frame("progress", &channel, &options);
155
156        assert!(!frame.contains("log line 0"), "{frame:?}");
157        assert!(!frame.contains("log line 2"), "{frame:?}");
158        assert!(frame.ends_with("log line 4\r\n"), "{frame:?}");
159    }
160
161    #[test]
162    fn frame_truncates_overlong_log_lines() {
163        let channel = LogChannel::with_capacity(5);
164        channel.push_line("x".repeat(300));
165        let frame = render_frame("p", &channel, &TuiOptions::default());
166
167        assert!(frame.contains(&"x".repeat(240)), "应截断到 240 字符");
168        assert!(!frame.contains(&"x".repeat(241)), "{frame:?}");
169    }
170
171    #[test]
172    fn make_writer_routes_fmt_lines_into_buffer() {
173        use tracing_subscriber::fmt::MakeWriter as _;
174
175        let channel = LogChannel::with_capacity(10);
176        {
177            let mut writer = channel.clone().make_writer();
178            std::io::Write::write_all(&mut writer, b"hello from fmt\n").unwrap();
179        }
180        assert_eq!(channel.lines(), vec!["hello from fmt"]);
181    }
182}