i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! UI handle: choose mode, start the render thread, send events

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

use crossfire::{
  MTx,
  mpsc::{self, List},
};

use crate::{
  event::{Event, Name, PoolStat, SlotMeta, SlotRow},
  i18n::T,
  interrupt::Interrupt,
  job::Job,
  plain,
  text::one_line,
  tty,
};

/// Environment variable forcing the UI mode: `tty` / `plain`
const ENV_UI: &str = "I18N_UI";

/// UI mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
  /// Auto: interactive when stderr is a terminal, not CI, and `TERM` is not `dumb`; `I18N_UI` can force it
  #[default]
  Auto,
  /// Interactive UI: inline scan first, then the concurrency panel on the alternate screen
  Tty,
  /// Line-by-line text
  Plain,
}

impl Mode {
  /// Resolve to whether interactive
  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_os("TERM").is_none_or(|term| term != "dumb")
        }
      },
    }
  }
}

/// UI handle: lightweight, shareable by reference across concurrent tasks; `drop` prints the summary and restores the terminal
pub struct Ui {
  tx: MTx<List<Event>>,
  /// Whether the interactive board is active; plain mode neither streams replies nor reports scan progress
  tty: bool,
  /// Interrupt flag polled by the interactive stages, set by the caller's signal watcher
  sig: Interrupt,
  /// Task id generator; compio runs single-threaded, so `Cell` suffices
  next: Cell<u32>,
  thread: Option<JoinHandle<()>>,
}

impl Ui {
  /// Start the render thread by mode
  pub fn new(mode: Mode) -> Self {
    let (tx, rx) = mpsc::unbounded_blocking();
    let tty = mode.tty();
    let sig = Interrupt::new();
    let render_sig = sig.clone();
    let thread = thread::Builder::new()
      .name("i18n_ui".into())
      .spawn(move || {
        if tty {
          tty::run(&rx, &render_sig);
        } else {
          plain::run(&rx);
        }
      })
      // If the thread fails to start, warn and continue: the UI does not affect translation, only drops progress feedback
      .inspect_err(|e| eprintln!("{}", T.ui.no_ui(e.to_string())))
      .ok();
    Self {
      tx,
      tty,
      sig,
      next: Cell::new(0),
      thread,
    }
  }

  /// Whether the interactive terminal board is active
  pub fn interactive(&self) -> bool {
    self.tty
  }

  /// Interrupt handle: set it from the caller's platform signal (e.g. `compio_ctrl_c::watch_with`)
  /// to make the interactive stage restore the terminal, print the summary, and exit with code 130
  pub fn interrupt(&self) -> &Interrupt {
    &self.sig
  }

  fn send(&self, event: Event) {
    // Dropped when the render thread has exited; the UI does not affect translation results
    let _ = self.tx.send(event);
  }

  /// Source files discovered by the directory walk so far (interactive scan stage only)
  pub fn scan_found(&self, found: usize) {
    if self.tty {
      self.send(Event::ScanFound(found));
    }
  }

  /// Source files whose cache state is checked so far, plus confirmed cache hits (interactive scan stage only)
  pub fn scan_checked(&self, checked: usize, cache: usize) {
    if self.tty {
      self.send(Event::ScanChecked { checked, cache });
    }
  }

  /// Set the model task count and cache hits confirmed in the precheck phase
  pub fn plan(&self, job: usize, cache: usize) {
    self.send(Event::Plan { job, cache });
  }

  /// Register all `(endpoint, token)` slots for live pool status display
  pub fn pool(&self, slot_li: Vec<SlotMeta>) {
    self.send(Event::Pool(slot_li));
  }

  /// Push a live slot update and global pool statistics
  pub fn slot(&self, row: SlotRow, stat: PoolStat) {
    self.send(Event::Slot { row, stat });
  }

  /// Tasks that are all cache hits
  pub fn hit(&self) {
    self.send(Event::Hit);
  }

  /// Model work found during execution that the precheck did not count
  pub fn grow(&self) {
    self.send(Event::Grow);
  }

  /// Languages planned but unprocessed this round: consume one planned unit, keeping progress and counts accurate
  pub fn skip(&self) {
    self.send(Event::Skip);
  }

  /// Record a local non-model failure in the final summary count
  pub fn fail(&self) {
    self.send(Event::Fail);
  }

  /// Mark that non-model disk or cache updates occurred this round so the full summary is displayed
  pub fn change(&self) {
    self.send(Event::Change);
  }

  /// Start a model-calling task: `from` is the source language, `out` is the target file display path
  pub fn job(&self, from: &str, out: &str) -> Job {
    let id = self.next.get();
    self.next.set(id.wrapping_add(1));
    self.send(Event::Start {
      id,
      name: Name::new(from, out),
    });
    Job::new(self.tx.clone(), id, self.tty)
  }

  /// Informational message
  pub fn log(&self, text: &str) {
    self.send(Event::Log(one_line(text)));
  }
}

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