i18n_ui 0.2.113

i18n 翻译进度终端界面:交互式并发面板与非交互逐行输出
Documentation
//! 界面句柄:选择模式、启动渲染线程、发送事件

use std::{
  cell::Cell,
  env,
  io::{IsTerminal, stderr},
  thread::{self, JoinHandle},
};

use ai_api::clean_text as clean;
use crossfire::{
  MTx,
  mpsc::{self, List},
};

use crate::{
  event::{Event, Name},
  job::Job,
  plain, tty,
};

/// 强制界面模式的环境变量:`tty` / `plain`
const ENV_UI: &str = "I18N_UI";

/// 界面模式
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
  /// 自动:stderr 是终端、非 CI、`TERM` 不是 `dumb` 时为交互模式;`I18N_UI` 可强制
  #[default]
  Auto,
  /// 交互式并发面板
  Tty,
  /// 逐行文本
  Plain,
}

impl Mode {
  /// 解析为是否交互
  fn tty(self) -> bool {
    match self {
      Self::Tty => true,
      Self::Plain => false,
      Self::Auto => match env::var(ENV_UI).as_deref() {
        Ok("tty") => true,
        Ok("plain") => false,
        _ => {
          stderr().is_terminal()
            && env::var_os("CI").is_none()
            && env::var("TERM").map_or(true, |term| term != "dumb")
        }
      },
    }
  }
}

/// 界面句柄:轻量、可在多个并发任务间共享引用;`drop` 时输出汇总并恢复终端
pub struct Ui {
  tx: MTx<List<Event>>,
  next: Cell<u32>,
  thread: Option<JoinHandle<()>>,
}

impl Ui {
  /// 按模式启动渲染线程;`job` 为并发数,决定交互面板的格数
  pub fn new(mode: Mode, job: u16) -> Self {
    let (tx, rx) = mpsc::unbounded_blocking();
    let tty = mode.tty();
    let thread = thread::Builder::new()
      .name("i18n_ui".into())
      .spawn(move || {
        if tty {
          tty::run(&rx, job);
        } else {
          plain::run(&rx);
        }
      })
      .ok();
    Self {
      tx,
      next: Cell::new(0),
      thread,
    }
  }

  fn send(&self, event: Event) {
    // 渲染线程已退出时丢弃,界面不影响翻译结果
    let _ = self.tx.send(event);
  }

  /// 设定进度总量
  pub fn plan(&self, weight: u64, job: usize) {
    self.send(Event::Plan { weight, job });
  }

  /// 缓存全命中的任务
  pub fn hit(&self, weight: u64) {
    self.send(Event::Hit { weight });
  }

  /// 开始一个调用模型的任务
  pub fn job(&self, lang: &str, file: &str, weight: u64) -> Job {
    let id = self.next.get();
    self.next.set(id.wrapping_add(1));
    self.send(Event::Start {
      id,
      name: Name {
        lang: clean(lang).into_owned(),
        file: clean(file).into_owned(),
      },
      weight,
    });
    Job::new(self.tx.clone(), id)
  }

  /// 提示信息
  pub fn log(&self, text: &str) {
    self.send(Event::Log(clean(text).into_owned()));
  }
}

impl Drop for Ui {
  fn drop(&mut self) {
    self.send(Event::Close);
    if let Some(thread) = self.thread.take() {
      let _ = thread.join();
    }
  }
}