i18n_ui 0.2.108

i18n 翻译进度终端界面:交互式并发面板与非交互逐行输出
Documentation
//! 两种渲染共用的界面状态:进度、运行中任务与计数

use coarsetime::Instant;
use i18n_progress::{Progress, View};

use crate::event::Name;

/// 思考尾部保留上限(字节),只用于显示最新内容
const TAIL_CAP: usize = 4096;

/// 运行中的任务
pub(crate) struct Run {
  pub(crate) id: u32,
  pub(crate) name: Name,
  pub(crate) weight: u64,
  pub(crate) begin: Instant,
  /// 交互模式:最新输出尾部;非交互模式:尚未成行的思考
  pub(crate) text: String,
  /// 最近一段输出是否为正文
  pub(crate) reply: bool,
}

impl Run {
  /// 追加输出并裁掉过旧内容(按字符边界)
  pub(crate) fn push_tail(&mut self, s: &str, reply: bool) {
    if self.reply != reply {
      self.reply = reply;
      self.text.clear();
    }
    self.text.push_str(s);
    if self.text.len() > TAIL_CAP {
      let mut cut = self.text.len() - TAIL_CAP;
      while !self.text.is_char_boundary(cut) {
        cut += 1;
      }
      self.text.drain(..cut);
    }
  }
}

/// 已结束任务
pub(crate) struct Ended {
  pub(crate) name: Name,
  pub(crate) secs: f32,
  pub(crate) err: Option<String>,
}

pub(crate) struct Board {
  pub(crate) progress: Progress,
  pub(crate) run_li: Vec<Run>,
  pub(crate) hit: usize,
  pub(crate) ok: usize,
  pub(crate) fail: usize,
  begin: Instant,
}

impl Board {
  pub(crate) fn new() -> Self {
    Self {
      progress: Progress::new(0, 0),
      run_li: Vec::new(),
      hit: 0,
      ok: 0,
      fail: 0,
      begin: Instant::now(),
    }
  }

  pub(crate) fn plan(&mut self, weight: u64, job: usize) {
    self.progress = Progress::new(weight, job);
  }

  pub(crate) fn hit(&mut self, weight: u64) {
    self.hit += 1;
    self.progress.skip(weight);
  }

  pub(crate) fn start(&mut self, id: u32, name: Name, weight: u64) {
    self.progress.start();
    self.run_li.push(Run {
      id,
      name,
      weight,
      begin: Instant::now(),
      text: String::new(),
      reply: false,
    });
  }

  pub(crate) fn run(&mut self, id: u32) -> Option<&mut Run> {
    self.run_li.iter_mut().find(|run| run.id == id)
  }

  /// 结束任务:成功计入进度,失败从总量扣除
  pub(crate) fn end(&mut self, id: u32, err: Option<String>) -> Option<(Run, Ended)> {
    let pos = self.run_li.iter().position(|run| run.id == id)?;
    let mut run = self.run_li.remove(pos);
    if err.is_some() {
      self.fail += 1;
      self.progress.skip(run.weight);
    } else {
      self.ok += 1;
      self.progress.finish(run.weight);
    }
    let ended = Ended {
      name: Name {
        lang: std::mem::take(&mut run.name.lang),
        file: std::mem::take(&mut run.name.file),
      },
      secs: secs(run.begin),
      err,
    };
    Some((run, ended))
  }

  pub(crate) fn view(&self) -> View {
    self.progress.view()
  }

  /// 总耗时(秒)
  pub(crate) fn secs(&self) -> f32 {
    secs(self.begin)
  }
}

/// 自 `begin` 起的秒数
pub(crate) fn secs(begin: Instant) -> f32 {
  begin.elapsed().as_f64() as f32
}