i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Non-interactive mode: line-by-line stderr output, no color, suited to CI logs and pipes

use std::{
  fmt::Arguments,
  io::{Write, stderr},
  time::Duration,
};

use clean_text::one_line;
use crossfire::{RecvTimeoutError, Rx, mpsc::List};

use crate::{
  board::{Act, Board, TAIL_CAP},
  event::Event,
  i18n::T,
  interrupt::Interrupt,
  text::{ELLIPSIS_STR, count, dur_col, eta, percent, push_meta, width},
};

/// Interrupt poll interval when line output continues an interactive run
const POLL: Duration = Duration::from_millis(200);

/// Line-by-line output; lock separately for each line
///
/// If the render thread held the stderr lock for the whole session, stderr output from other threads
/// (including the panic hook) would block until the UI ends, possibly deadlocking on panic
fn emit(arg: Arguments<'_>) {
  let mut err = stderr().lock();
  let _ = writeln!(err, "{arg}");
}

/// Emit a cleaned log line in plain line-by-line format, flushed immediately
pub(crate) fn emit_log(text: &str) {
  let mut err = stderr().lock();
  let _ = writeln!(err, "{}", T.ui.log(text));
  let _ = err.flush();
}

/// Emit a note immediately, with the same format as a log event
///
/// Used for messages before the UI starts (e.g. auto-generated config); locking matches line mode.
pub(crate) fn note(text: &str) {
  emit_log(one_line(text).as_ref());
}

pub(crate) fn run(rx: &Rx<List<Event>>) {
  run_from(Board::new(), rx, None);
}

/// Continue line output on an existing board
///
/// Used when the interactive scan stage discovers that every task is a cache hit: the summary and any
/// remaining log lines still reach the normal screen without a full-screen round trip.
///
/// `sig` is set when the caller already intercepts Ctrl+C; line output then polls it so an
/// interrupted run still prints the summary. Returns whether an interrupt was observed.
pub(crate) fn run_from(mut board: Board, rx: &Rx<List<Event>>, sig: Option<&Interrupt>) -> bool {
  // Indent thinking lines to align with the status word: the word varies by language, so its width is computed live
  let pad = " ".repeat(width(&T.ui.start("")));
  let mut interrupted = false;
  loop {
    let event = match sig {
      Some(sig) => match rx.recv_timeout(POLL) {
        Ok(event) => event,
        Err(RecvTimeoutError::Timeout) => {
          if sig.hit() {
            interrupted = true;
            break;
          }
          continue;
        }
        Err(RecvTimeoutError::Disconnected) => break,
      },
      None => match rx.recv() {
        Ok(event) => event,
        Err(_) => break,
      },
    };
    match board.apply(event) {
      Act::None | Act::Plan { .. } => {}
      Act::Start(id) => {
        if let Some(run) = board.run(id) {
          emit(format_args!("{}", T.ui.start(run.name.tag())));
        }
      }
      Act::Text {
        id,
        text,
        reply: false,
      } => {
        if let Some(run) = board.run(id) {
          run.think.push_str(&text);
          // Emit complete lines in one pass, shifting any trailing partial line once
          if let Some(last_nl) = run.think.rfind('\n') {
            let job_tag = run.name.tag();
            for raw in run.think[..last_nl].split('\n') {
              let line = raw.trim_end();
              if !line.is_empty() {
                emit(format_args!("{pad}{job_tag} │ {line}"));
              }
            }
            run.think.drain(..=last_nl);
          }
          // Replace oversized newline-free tail in one shift while staying strictly within TAIL_CAP
          if run.think.len() > TAIL_CAP {
            let keep = TAIL_CAP - ELLIPSIS_STR.len();
            let cut = run.think.ceil_char_boundary(run.think.len() - keep);
            run.think.replace_range(..cut, ELLIPSIS_STR);
          }
        }
      }
      Act::Text { .. } => {}
      Act::Retry(id) => {
        if let Some(run) = board.run(id)
          && let Some(r) = &run.retry
        {
          emit(format_args!(
            "{}",
            T.ui.retry(
              run.name.tag(),
              r.nth,
              r.total,
              r.base.as_str(),
              r.err.as_str(),
            )
          ));
        }
      }
      Act::End(ended) => {
        let rest = ended.think.trim();
        if !rest.is_empty() {
          emit(format_args!("{pad}{} │ {rest}", ended.name.tag()));
        }
        let view = board.progress.view();
        match ended.err {
          None => {
            let mut line = T
              .ui
              .done(
                dur_col(ended.sec),
                ended.name.from(),
                ended.name.out(),
                count(&view),
                percent(&view),
                eta(&view),
              )
              .into_owned();
            line.truncate(line.trim_end().len());
            push_meta(&mut line, ended.slot_label.as_deref(), ended.tok);
            emit(format_args!("{line}"));
          }
          Some(msg) => emit(format_args!("{}", T.ui.fail(ended.name.tag(), msg))),
        }
      }
      Act::Log(text) => emit(format_args!("{}", T.ui.log(text))),
      Act::Close => break,
    }
  }
  if let Some(summary) = board.summary() {
    emit(format_args!("{summary}"));
  }
  interrupted
}