i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Text layout: display-width clipping, tail wrapping, duration, percentage and localized token formatting

use std::{borrow::Cow, fmt::Write as _, iter::repeat_n, ops::Range, time::Duration};

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

use crate::i18n::{I18N, Lang, T};

/// Direction arrow between source language and target file
pub(crate) const ARROW: &str = " → ";
/// Ellipsis
pub(crate) const ELLIPSIS: char = '…';
pub(crate) const ELLIPSIS_STR: &str = "…";
/// Milliseconds per 0.1 second and the rounding bias
const TENTH_MS: u128 = 100;
const HALF_TENTH_MS: u128 = 50;
/// Duration column width: `dur` output is at most 6 columns (`59m59s` / `10h02m`)
const DUR_W: usize = 6;

/// Character display width (control characters count as 0)
fn char_w(c: char) -> usize {
  c.width().unwrap_or(0)
}

/// Single-line display field: after cleaning control chars, fold newlines and tabs into spaces,
/// so malformed file names/logs/error summaries cannot break line output or the concurrency panel layout
pub(crate) fn one_line(s: &str) -> String {
  clean_text::one_line(s).into_owned()
}

/// String display width
pub(crate) fn width(s: &str) -> usize {
  s.width()
}

/// Return the byte index where `s` must truncate before `ELLIPSIS` when its width exceeds `max > 0`
fn fit_cut(s: &str, max: usize) -> Option<usize> {
  let mut w = 0usize;
  let mut cut = 0usize;
  let mut cut_set = false;
  for (i, c) in s.char_indices() {
    let cw = char_w(c);
    if !cut_set && w + cw + 1 > max {
      cut = i;
      cut_set = true;
    }
    w += cw;
    if w > max {
      return Some(cut);
    }
  }
  None
}

/// Keep the start; end with an ellipsis when wider than `max` (zero allocation when `s` fits)
pub(crate) fn fit(s: &str, max: usize) -> Cow<'_, str> {
  if max == 0 {
    return Cow::Borrowed("");
  }
  match fit_cut(s, max) {
    Some(cut) => {
      let mut out = String::with_capacity(cut + ELLIPSIS.len_utf8());
      out.push_str(&s[..cut]);
      out.push(ELLIPSIS);
      Cow::Owned(out)
    }
    None => Cow::Borrowed(s),
  }
}

/// In-place version of [`fit`] for owned strings: zero allocation whether `s` fits or truncates
pub(crate) fn fit_owned(mut s: String, max: usize) -> String {
  if max == 0 {
    s.clear();
  } else if let Some(cut) = fit_cut(&s, max) {
    s.truncate(cut);
    s.push(ELLIPSIS);
  }
  s
}

/// Keep the end; start with an ellipsis when wider than `max` (long paths keep the file name; zero allocation when `s` fits)
pub(crate) fn fit_end(s: &str, max: usize) -> Cow<'_, str> {
  if max == 0 {
    return Cow::Borrowed("");
  }
  let mut w = 0usize;
  let mut start = s.len();
  let mut start_set = false;
  for (i, c) in s.char_indices().rev() {
    let cw = char_w(c);
    if !start_set && w + cw + 1 > max {
      start_set = true;
    }
    w += cw;
    if w > max {
      let tail = &s[start..];
      let mut out = String::with_capacity(ELLIPSIS.len_utf8() + tail.len());
      out.push(ELLIPSIS);
      out.push_str(tail);
      return Cow::Owned(out);
    }
    if !start_set {
      start = i;
    }
  }
  Cow::Borrowed(s)
}

/// Split at the widest prefix not exceeding `max` columns: `(head, rest)`
pub(crate) fn split_w(s: &str, max: usize) -> (&str, &str) {
  let mut w = 0;
  let cut = s
    .char_indices()
    .find(|&(_, c)| {
      w += char_w(c);
      w > max
    })
    .map_or(s.len(), |(i, _)| i);
  s.split_at(cut)
}

/// Take the tail of the latest output, fold whitespace to single spaces, then wrap from the end into at most `row` lines of `col` width
pub(crate) fn tail(s: &str, col: usize, row: usize) -> Vec<String> {
  if col == 0 || row == 0 {
    return Vec::new();
  }
  // Collect enough chars in reverse to fill row lines, folding whitespace
  let budget = col * row;
  let mut rev_li = Vec::with_capacity(budget.min(s.len()));
  let mut w = 0;
  let mut space = false;
  for c in s.trim().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();
  }
  // Split from newest to oldest into at most row line ranges: fill each right to left so the newest line never holds only a few trailing chars
  let mut range_li: Vec<Range<usize>> = Vec::with_capacity(row.min(rev_li.len()));
  let mut start = 0;
  let mut lw = 0;
  for (i, &c) in rev_li.iter().enumerate() {
    let cw = char_w(c);
    // No break at line start: at extreme narrow widths a wide char takes its own line without producing a blank line
    if lw > 0 && lw + cw > col {
      range_li.push(start..i);
      start = i;
      if range_li.len() == row {
        break;
      }
      lw = 0;
    }
    lw += cw;
  }
  if range_li.len() < row {
    range_li.push(start..rev_li.len());
  }
  range_li
    .into_iter()
    .rev()
    .filter_map(|r| {
      let mut end = r.end;
      while end > r.start && rev_li[end - 1] == ' ' {
        end -= 1;
      }
      (end > r.start).then(|| rev_li[r.start..end].iter().rev().collect())
    })
    .collect()
}

/// Duration: `8.3s` / `1m05s` / `1h02m`, rounded to tenths first so `59.96s` yields `1m00s` instead of `60.0s`
fn write_dur(sec: f32, out: &mut String) {
  let tenth = (sec.max(0.0) * 10.0 + 0.5) as u64;
  let mut buf = Buffer::new();
  if tenth < 600 {
    push_tenth(tenth, 's', out, &mut buf);
    return;
  }
  let s = tenth / 10;
  let (hi, u1, lo, u2) = if s >= 3600 {
    (s / 3600, 'h', (s % 3600 / 60) as u8, 'm')
  } else {
    (s / 60, 'm', (s % 60) as u8, 's')
  };
  out.push_str(buf.format(hi));
  out.push(u1);
  out.push((b'0' + lo / 10) as char);
  out.push((b'0' + lo % 10) as char);
  out.push(u2);
}

pub(crate) fn dur(sec: f32) -> String {
  let mut out = String::with_capacity(DUR_W);
  write_dur(sec, &mut out);
  out
}

/// Duration column: pad right with spaces to [`DUR_W`], keeping fields aligned after short and long durations
pub(crate) fn dur_col(sec: f32) -> String {
  let mut out = String::with_capacity(DUR_W);
  write_dur(sec, &mut out);
  if out.len() < DUR_W {
    out.extend(repeat_n(' ', DUR_W - out.len()));
  }
  out
}

#[inline]
fn push_tenth(val: u64, unit: char, out: &mut String, buf: &mut Buffer) {
  out.push_str(buf.format(val / 10));
  out.push('.');
  out.push((b'0' + (val % 10) as u8) as char);
  out.push(unit);
}

#[inline]
fn push_hundredth(val: u64, unit: char, out: &mut String, buf: &mut Buffer) {
  out.push_str(buf.format(val / 100));
  out.push('.');
  let rem = (val % 100) as u8;
  out.push((b'0' + rem / 10) as char);
  out.push((b'0' + rem % 10) as char);
  out.push(unit);
}

/// Countdown in tenths of a second (at least `0.1s`, pure integer formatting)
pub(crate) fn tenth_sec(rem: Duration, out: &mut String) {
  let tenth = (rem.as_millis().saturating_add(HALF_TENTH_MS) / TENTH_MS).max(1) as u64;
  push_tenth(tenth, 's', out, &mut Buffer::new());
}

fn push_tok(n: u64, out: &mut String) {
  let cjk = match Lang::of_code(I18N.code()) {
    Some(Lang::Zh) => Some(('万', '亿')),
    Some(Lang::ZhTW) => Some(('萬', '億')),
    Some(Lang::Ja) => Some(('万', '億')),
    _ => None,
  };
  let mut buf = Buffer::new();
  if let Some((wan, yi)) = cjk {
    if n < 10_000 {
      out.push_str(buf.format(n));
    } else if n < 100_000_000 {
      push_tenth(n.saturating_add(500) / 1_000, wan, out, &mut buf);
    } else {
      push_hundredth(n.saturating_add(500_000) / 1_000_000, yi, out, &mut buf);
    }
    return;
  }

  if n < 1_000 {
    out.push_str(buf.format(n));
  } else if n < 1_000_000 {
    push_tenth(n.saturating_add(50) / 100, 'k', out, &mut buf);
  } else if n < 1_000_000_000 {
    push_hundredth(n.saturating_add(5_000) / 10_000, 'M', out, &mut buf);
  } else {
    push_hundredth(n.saturating_add(5_000_000) / 10_000_000, 'B', out, &mut buf);
  }
}

/// Format token count using CJK myriad/hundred-million units (`万`/`亿`) or Western `k`/`M`/`B`
pub(crate) fn fmt_tok(n: u64) -> String {
  let mut out = String::with_capacity(12);
  push_tok(n, &mut out);
  out
}

/// Single-allocation formatted token count with trailing localized unit word
pub(crate) fn fmt_tok_word(n: u64) -> String {
  let word = T.ui.tok_word();
  let mut out = String::with_capacity(12 + 1 + word.len());
  push_tok(n, &mut out);
  out.push(' ');
  out.push_str(word);
  out
}

/// Compact display label for an endpoint token slot
pub(crate) fn slot_tag(host: &str, nth: u16) -> String {
  let mut buf = Buffer::new();
  let n = buf.format(nth);
  let mut out = String::with_capacity(host.len() + 2 + n.len());
  out.push_str(host);
  out.push_str(" #");
  out.push_str(n);
  out
}

/// Percentage: `42.1%`
pub(crate) fn percent(view: &View) -> String {
  let mut out = String::with_capacity(6);
  push_tenth(u64::from(view.permille), '%', &mut out, &mut Buffer::new());
  out
}

/// Completed count: `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
}

/// Append slot label and token count suffix when present, shared by plain output and post-exit summary
pub(crate) fn push_meta(out: &mut String, slot_label: Option<&str>, tok: u64) {
  if let Some(s) = slot_label {
    let _ = write!(out, "  {s}");
  }
  if tok > 0 {
    let _ = write!(out, "  {}", fmt_tok_word(tok));
  }
}

/// Remaining time: `left 3m12s`; empty when everything is done
pub(crate) fn eta(view: &View) -> String {
  if view.eta.is_some_and(|eta| eta.is_zero()) {
    return String::new();
  }
  let eta = match view.eta {
    Some(eta) => eta_text(eta),
    None => T.ui.estimating().to_owned(),
  };
  T.ui.eta(eta).into_owned()
}