i18n_ui 0.2.110

i18n 翻译进度终端界面:交互式并发面板与非交互逐行输出
Documentation
//! 文本排版:显示宽度裁剪、尾部折行、时长与百分比格式化

use std::{fmt::Write as _, time::Duration};

use i18n_progress::{View, eta_text};
use itoa::Buffer;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

/// 语言列宽(交互与非交互共用)
pub(crate) const LANG_W: usize = 5;
/// 省略号
const ELLIPSIS: char = '…';
/// 0.1 秒对应的毫秒数与四舍五入偏置
const TENTH_MS: u128 = 100;
const HALF_TENTH_MS: u128 = 50;

/// 字符显示宽度(控制字符按 0)
fn char_w(c: char) -> usize {
  c.width().unwrap_or(0)
}

/// 字符串显示宽度
pub(crate) fn width(s: &str) -> usize {
  s.width()
}

/// 保留开头,超出 `max` 宽度时以省略号结尾
pub(crate) fn fit(s: &str, max: usize) -> String {
  if width(s) <= max {
    return s.to_owned();
  }
  let mut out = String::new();
  let mut w = 0;
  for c in s.chars() {
    let cw = char_w(c);
    if w + cw + 1 > max {
      break;
    }
    w += cw;
    out.push(c);
  }
  if max > 0 {
    out.push(ELLIPSIS);
  }
  out
}

/// 保留结尾,超出 `max` 宽度时以省略号开头(长路径保留文件名)
pub(crate) fn fit_end(s: &str, max: usize) -> String {
  if width(s) <= max {
    return s.to_owned();
  }
  let mut rev_li = Vec::new();
  let mut w = 0;
  for c in s.chars().rev() {
    let cw = char_w(c);
    if w + cw + 1 > max {
      break;
    }
    w += cw;
    rev_li.push(c);
  }
  let mut out = String::with_capacity(rev_li.len() * 3 + 3);
  if max > 0 {
    out.push(ELLIPSIS);
  }
  out.extend(rev_li.into_iter().rev());
  out
}

/// 取最新输出的尾部,空白折叠为单个空格后按 `col` 宽度折成至多 `row` 行
pub(crate) fn tail(s: &str, col: usize, row: usize) -> Vec<String> {
  if col == 0 || row == 0 {
    return Vec::new();
  }
  // 逆序收集足够填满 row 行的字符,空白折叠
  let budget = col * row;
  let mut rev_li = Vec::new();
  let mut w = 0;
  let mut space = false;
  for c in s.trim_end().chars().rev() {
    if c.is_whitespace() {
      if space || rev_li.is_empty() {
        continue;
      }
      space = true;
      rev_li.push(' ');
      w += 1;
    } else {
      space = false;
      rev_li.push(c);
      w += char_w(c);
    }
    if w >= budget {
      break;
    }
  }
  if rev_li.is_empty() {
    return Vec::new();
  }
  // 正向折行,多出的开头行丢弃
  let mut line_li = vec![String::new()];
  let mut lw = 0;
  for c in rev_li.into_iter().rev() {
    let cw = char_w(c);
    // 行首不换行:极窄宽度下宽字符独占一行,不产生空行
    if lw > 0 && lw + cw > col {
      line_li.push(String::new());
      lw = 0;
    }
    if let Some(line) = line_li.last_mut() {
      line.push(c);
    }
    lw += cw;
  }
  let skip = line_li.len().saturating_sub(row);
  line_li.drain(..skip);
  if let Some(first) = line_li.first_mut() {
    let trimmed = first.trim_start().len();
    first.drain(..first.len() - trimmed);
  }
  line_li
}

/// 时长:`8.3s` / `1m05s` / `1h02m`
pub(crate) fn dur(sec: f32) -> String {
  let mut out = String::new();
  if sec < 60.0 {
    let _ = write!(out, "{sec:.1}s");
  } else {
    let s = sec as u64;
    if s >= 3600 {
      let _ = write!(out, "{}h{:02}m", s / 3600, s % 3600 / 60);
    } else {
      let _ = write!(out, "{}m{:02}s", s / 60, s % 60);
    }
  }
  out
}

/// 倒计时十分位秒数(至少 `0.1s`,纯整数格式化)
pub(crate) fn tenth_sec(rem: Duration, out: &mut String) {
  let tenth = (rem.as_millis().saturating_add(HALF_TENTH_MS) / TENTH_MS).max(1);
  let mut buf = Buffer::new();
  out.push_str(buf.format(tenth / 10));
  out.push('.');
  out.push((b'0' + (tenth % 10) as u8) as char);
  out.push('s');
}

/// 百分比:`42.1%`
pub(crate) fn percent(view: &View) -> String {
  let mut out = String::with_capacity(6);
  let mut buf = Buffer::new();
  out.push_str(buf.format(view.permille / 10));
  out.push('.');
  out.push((b'0' + (view.permille % 10) as u8) as char);
  out.push('%');
  out
}

/// 完成数:`18/43`
pub(crate) fn count(view: &View) -> String {
  let mut out = String::with_capacity(12);
  let mut buf = Buffer::new();
  out.push_str(buf.format(view.done_job));
  out.push('/');
  out.push_str(buf.format(view.total_job));
  out
}

/// 剩余时间:`剩余 3m12s`;已全部完成时为空
pub(crate) fn eta(view: &View) -> String {
  if view.eta.is_some_and(|eta| eta.is_zero()) {
    return String::new();
  }
  format!("剩余 {}", eta_text(view.eta))
}

/// 汇总:`翻译 12  缓存 31  失败 0  用时 3m12s`
pub(crate) fn summary(ok: usize, hit: usize, fail: usize, sec: f32) -> String {
  format!("翻译 {ok}  缓存 {hit}  失败 {fail}  用时 {}", dur(sec))
}