i18n_ui 0.2.112

i18n 翻译进度终端界面:交互式并发面板与非交互逐行输出
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! 交互模式:ratatui 内联视口
//!
//! ```text
//!  完成  en    zh/a.md                                  4.2s     ← 滚入终端历史
//!  ⠹ fr    zh/c.md                                      8.3s     ← 每个运行中任务一格
//!    │ 思考尾部,深灰,按宽度折成两行,始终显示最新内容
//!    │ …
//!
//!  ━━━━━━━━━━━━━━━━━━━━──────────  42.1%  18/43  剩余 3m12s  缓存 31
//! ```

use std::{
  borrow::Cow,
  io::{self, Stderr, Write, stderr},
  process::exit,
  time::{Duration, Instant},
};

use crossfire::{RecvTimeoutError, Rx, mpsc::List};
use crossterm::terminal::size;
use itoa::Buffer as ItoaBuffer;
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, sec},
  event::Event,
  plain,
  text::{LANG_W, count, dur, eta, fit, fit_end, percent, summary, tail, tenth_sec, width},
};

type Term = Terminal<CrosstermBackend<Stderr>>;

/// 重绘间隔
const FRAME: Duration = Duration::from_millis(80);
/// 加载动画帧(盲文点阵)
const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
/// 每格正文行数(思考 + 译文输出)
const BODY_ROW: u16 = 2;
/// 面板下方行数:空行 + 进度条
const FOOT_ROW: u16 = 2;
/// 至少给终端历史保留的行数
const HISTORY_ROW: u16 = 2;
/// 取不到终端尺寸时假定的高度
const TERM_ROW: u16 = 24;
/// 思考行、译文行、重试行的前缀,宽度一致
const THINK_MARK: &str = "   │ ";
const REPLY_MARK: &str = "   › ";
const RETRY_MARK: &str = "   ! ";
/// 正文行前缀宽度与右侧安全边距
const BODY_PAD: usize = 5;
const RIGHT_PAD: usize = 1;
/// 栏间标准双空格分隔符与宽度
const COL_GAP: &str = "  ";
const COL_GAP_W: usize = COL_GAP.len();
/// 行首动画列宽:空格 + 动画 + 空格
const SPIN_W: usize = 3;
/// 单行紧凑模式下文件路径占终端宽度的分母(1/3)
const COMPACT_FILE_DIV: usize = 3;
/// 进度条最大 / 最小宽度与千分比基数
const BAR_MAX: usize = 32;
const BAR_MIN: usize = 8;
const PERMILLE: usize = 1000;
/// 进度条右侧百分比、计数、剩余时间等文字预留宽度
const BAR_RESERVE: usize = 40;
/// 进度条已完成 / 未完成字符与预置静态串(免除每帧堆分配)
const BAR_ON: char = '━';
const BAR_OFF: char = '─';
const BAR_CHAR_BYTES: usize = BAR_ON.len_utf8();
const BAR_ON_STR: &str = "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
const BAR_OFF_STR: &str = "────────────────────────────────";
/// 预置 256 个空格,常规终端宽度下零分配切片复用
const SPACE_STR: &str = "                                                                \
                                                                \
                                                                \
                                                                ";
/// 重试冷却微型倒计时条宽度与启用它的最小终端宽度
const WAIT_BAR_W: usize = 6;
const WAIT_BAR_MIN_W: usize = 68;
/// 重试行中间段展示网址所需的最小宽度,不足时下沉到次行
const MID_MIN_W: usize = 8;
/// 冷却倒计时文案
const WAIT_SUFFIX: &str = " 后重试";
const RECONNECT: &str = "重连中…";
/// Ctrl-C 退出时恢复光标与颜色
const RESTORE: &str = "\x1b[0m\x1b[?25h\n";
/// 被 Ctrl-C 中断的退出码
const SIGINT_EXIT: i32 = 130;

const _: () = {
  assert!(BAR_ON.len_utf8() == BAR_OFF.len_utf8());
  assert!(BAR_ON_STR.len() == BAR_MAX * BAR_CHAR_BYTES);
  assert!(BAR_OFF_STR.len() == BAR_MAX * BAR_CHAR_BYTES);
  assert!(WAIT_BAR_W <= BAR_MAX);
};

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);

/// 取 `n` 个空格,常规宽度直接切片静态常量
fn pad(n: usize) -> Cow<'static, str> {
  if n <= SPACE_STR.len() {
    Cow::Borrowed(&SPACE_STR[..n])
  } else {
    Cow::Owned(" ".repeat(n))
  }
}

/// 面板布局
#[derive(Clone, Copy)]
struct Layout {
  slot: u16,
  /// 每格行数:完整模式 1 + 正文行,终端过矮时退化为 1
  row: u16,
}

impl Layout {
  /// 格数与每格行数都受终端高度约束,视口不超出终端、乘法不溢出
  fn new(job: u16) -> Self {
    let term_row = size().map_or(TERM_ROW, |(_, h)| h);
    let room = term_row.saturating_sub(FOOT_ROW + HISTORY_ROW).max(1);
    let full = 1 + BODY_ROW;
    let slot = job.clamp(1, room);
    let row = if slot.checked_mul(full).is_some_and(|n| n <= room) {
      full
    } else {
      1
    };
    Self { slot, row }
  }

  fn height(self) -> u16 {
    self.slot * self.row + FOOT_ROW
  }
}

pub(crate) fn run(rx: &Rx<List<Event>>, job: u16) {
  let layout = Layout::new(job);
  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;
        }
        // 合并积压事件后统一重绘,token 流再密也不闪
        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,
      wait,
      base,
      err,
    } => {
      board.on_retry(id, nth, total, wait, 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.sec), DIM));
      if ended.retry_cnt > 0 {
        let mut buf = ItoaBuffer::new();
        let mut s = String::with_capacity(12);
        s.push_str("  重试 ");
        s.push_str(buf.format(ended.retry_cnt));
        span_li.push(Span::styled(s, 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 now = Instant::now();
  let fit_slot = area.height.saturating_sub(FOOT_ROW) / layout.row;
  for (i, run) in board
    .run_li
    .iter()
    .take(usize::from(layout.slot.min(fit_slot)))
    .enumerate()
  {
    let y = area.y + i as u16 * layout.row;
    let spin = SPIN[(frame + i) % SPIN.len()];
    if layout.row == 1 {
      compact(run, spin, w, now).render(row(area, y), buf);
      continue;
    }
    header(run, spin, w).render(row(area, y), buf);
    for (k, line) in body(run, w, now).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);
}

/// 视口内第 `y` 行
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(sec(run.begin));
  // 前缀 " ⠹ " + 语言列 + 空格,右侧留耗时与边距
  let fixed = SPIN_W + LANG_W + 1 + width(&time) + COL_GAP_W;
  let file = fit_end(&run.name.file, w.saturating_sub(fixed));
  let gap = w.saturating_sub(fixed + width(&file)) + RIGHT_PAD;
  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(pad(gap)),
    Span::styled(time, DIM),
  ])
}

/// 轮次徽章:同一段连续重试多次时附上 `×N`,体现换 token / 端点的实时进展
fn retry_badge(r: &RetryState) -> String {
  let mut buf = ItoaBuffer::new();
  let mut out = String::with_capacity(24);
  out.push_str("第 ");
  out.push_str(buf.format(r.nth));
  out.push('/');
  out.push_str(buf.format(r.total));
  out.push_str(" 轮");
  if r.streak > 1 {
    out.push_str(" · ×");
    out.push_str(buf.format(r.streak));
  }
  out
}

/// 倒计时右栏:冷却中展示微型退去条 + `2.4s 后重试`,归零后切为 `重连中…`
fn countdown(r: &RetryState, now: Instant, show_bar: bool) -> (Vec<Span<'static>>, usize) {
  if r.wait.is_zero() {
    return (Vec::new(), 0);
  }
  let rem = r.rem(now);
  if rem.is_zero() {
    return (vec![Span::styled(RECONNECT, LANG)], width(RECONNECT));
  }
  let mut num = String::with_capacity(8);
  tenth_sec(rem, &mut num);
  let text_w = num.len() + width(WAIT_SUFFIX);
  if show_bar {
    let total_ms = r.wait.as_millis().max(1);
    let rem_ms = rem.as_millis().min(total_ms);
    let lit = ((rem_ms * WAIT_BAR_W as u128).div_ceil(total_ms) as usize).clamp(1, WAIT_BAR_W);
    (
      vec![
        Span::styled(&BAR_ON_STR[..lit * BAR_CHAR_BYTES], WARN),
        Span::styled(&BAR_OFF_STR[..(WAIT_BAR_W - lit) * BAR_CHAR_BYTES], DIM),
        Span::raw(" "),
        Span::styled(num, WARN),
        Span::styled(WAIT_SUFFIX, DIM),
      ],
      WAIT_BAR_W + 1 + text_w,
    )
  } else {
    (
      vec![Span::styled(num, WARN), Span::styled(WAIT_SUFFIX, DIM)],
      text_w,
    )
  }
}

/// 重试主行:左栏轮次 + 中栏网址 + 右栏倒计时(与标题耗时右边界对齐);返回中栏是否已展示
fn retry_line(
  badge: String,
  mid_src: &str,
  mid_style: Style,
  r: &RetryState,
  now: Instant,
  w: usize,
) -> (Line<'static>, bool) {
  let col = w.saturating_sub(BODY_PAD + RIGHT_PAD);
  let badge_w = width(&badge);
  let (right_li, right_w) = countdown(r, now, w >= WAIT_BAR_MIN_W);

  if right_w == 0 {
    if let Some(mid_max) = col.checked_sub(badge_w + COL_GAP_W)
      && mid_max >= MID_MIN_W
    {
      let mid = fit(mid_src, mid_max);
      return (
        Line::from(vec![
          Span::styled(RETRY_MARK, WARN),
          Span::styled(badge, WARN),
          Span::raw(COL_GAP),
          Span::styled(mid, mid_style),
        ]),
        true,
      );
    }
    let clipped = if badge_w <= col {
      badge
    } else {
      fit(&badge, col)
    };
    return (
      Line::from(vec![
        Span::styled(RETRY_MARK, WARN),
        Span::styled(clipped, WARN),
      ]),
      false,
    );
  }

  // 宽度充裕:左轮次 + 中网址 + 右对齐倒计时
  if let Some(mid_max) = col.checked_sub(badge_w + COL_GAP_W * 2 + right_w)
    && mid_max >= MID_MIN_W
  {
    let mid = fit(mid_src, mid_max);
    let gap = col - badge_w - COL_GAP_W - width(&mid) - right_w;
    let mut span_li = Vec::with_capacity(5 + right_li.len());
    span_li.push(Span::styled(RETRY_MARK, WARN));
    span_li.push(Span::styled(badge, WARN));
    span_li.push(Span::raw(COL_GAP));
    span_li.push(Span::styled(mid, mid_style));
    span_li.push(Span::raw(pad(gap)));
    span_li.extend(right_li);
    return (Line::from(span_li), true);
  }

  // 窄窗口:两端对齐轮次与倒计时,网址留给次行展示
  if let Some(gap) = col.checked_sub(badge_w + COL_GAP_W + right_w) {
    let mut span_li = Vec::with_capacity(3 + right_li.len());
    span_li.push(Span::styled(RETRY_MARK, WARN));
    span_li.push(Span::styled(badge, WARN));
    span_li.push(Span::raw(pad(gap + COL_GAP_W)));
    span_li.extend(right_li);
    return (Line::from(span_li), false);
  }

  // 极窄窗口兜底裁剪
  let mut merged_src = badge;
  merged_src.push(' ');
  for s in &right_li {
    merged_src.push_str(s.content.as_ref());
  }
  let merged = fit(&merged_src, col);
  (
    Line::from(vec![
      Span::styled(RETRY_MARK, WARN),
      Span::styled(merged, WARN),
    ]),
    false,
  )
}

/// 任务格正文:重试中优先展示轮次、API 网址、倒计时与错误摘要;正常流式时展示思考与译文
fn body(run: &Run, w: usize, now: Instant) -> Vec<Line<'static>> {
  let col = w.saturating_sub(BODY_PAD + RIGHT_PAD);
  let row = usize::from(BODY_ROW);

  if let Some(r) = &run.retry {
    let badge = retry_badge(r);
    if run.think.is_empty() && run.reply.is_empty() {
      let (head, base_shown) = retry_line(badge, &r.base, REPLY, r, now, w);
      let sub = if base_shown || r.base.is_empty() {
        fit(&r.err, col)
      } else {
        fit(&format!("{} · {}", r.base, r.err), col)
      };
      return vec![
        head,
        Line::from(vec![Span::styled(THINK_MARK, DIM), Span::styled(sub, DIM)]),
      ];
    }
    // 大文件后续批次重试:首行保留上一批最新输出,次行展示重试状态与倒计时
    let mut line_li = Vec::with_capacity(row);
    if let Some(text) = tail(&run.reply, col, 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, col, 1).pop() {
      line_li.push(Line::from(vec![
        Span::styled(THINK_MARK, DIM),
        Span::styled(text, DIM),
      ]));
    }
    let detail = if r.base.is_empty() {
      r.err.clone()
    } else {
      format!("{} · {}", r.base, r.err)
    };
    let (retry_row, _) = retry_line(badge, &detail, DIM, r, now, w);
    line_li.push(retry_row);
    return line_li;
  }

  let think_row = if run.reply.is_empty() { row } else { row - 1 };
  let mut line_li: Vec<Line<'static>> = tail(&run.think, col, think_row)
    .into_iter()
    .map(|text| Line::from(vec![Span::styled(THINK_MARK, DIM), Span::styled(text, DIM)]))
    .collect();
  if let Some(text) = tail(&run.reply, col, 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, now: Instant) -> Line<'static> {
  let time = dur(sec(run.begin));
  let file = fit_end(&run.name.file, w / COMPACT_FILE_DIV);
  let used = SPIN_W + LANG_W + 1 + width(&file) + COL_GAP_W + width(&time) + COL_GAP_W;
  let avail = w.saturating_sub(used);
  let (tail_str, style) = if let Some(r) = &run.retry {
    let mut text = retry_badge(r);
    if !r.wait.is_zero() {
      text.push_str(" · ");
      let rem = r.rem(now);
      if rem.is_zero() {
        text.push_str(RECONNECT);
      } else {
        tenth_sec(rem, &mut text);
        text.push_str(WAIT_SUFFIX);
      }
      if !r.base.is_empty() {
        text.push_str(" · ");
        text.push_str(&r.base);
      }
    } else if !r.base.is_empty() {
      text.push(' ');
      text.push_str(&r.base);
    }
    (fit(&text, 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(COL_GAP),
    Span::styled(time, DIM),
    Span::raw(COL_GAP),
    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 / PERMILLE;
  let mut span_li = vec![
    Span::raw(" "),
    Span::styled(
      &BAR_ON_STR[..on * BAR_CHAR_BYTES],
      Style::new().fg(Color::Cyan),
    ),
    Span::styled(&BAR_OFF_STR[..(bar_w - on) * BAR_CHAR_BYTES], DIM),
    Span::raw(COL_GAP),
    Span::styled(percent(&view), BOLD),
    Span::raw(COL_GAP),
    Span::raw(count(&view)),
    Span::raw(COL_GAP),
    Span::styled(eta(&view), DIM),
  ];
  let mut buf = ItoaBuffer::new();
  if board.hit > 0 {
    span_li.push(Span::styled(
      format!("  缓存 {}", buf.format(board.hit)),
      DIM,
    ));
  }
  if board.retry > 0 {
    span_li.push(Span::styled(
      format!("  重试 {}", buf.format(board.retry)),
      WARN,
    ));
  }
  if board.fail > 0 {
    span_li.push(Span::styled(
      format!("  失败 {}", buf.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.sec())),
  ]);
  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()
}