i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Interactive terminal: an inline scan stage, then the alternate-screen translation board
//!
//! 1. Scan stage: a two-line inline viewport on the normal screen (checked/found files, cache hits,
//!    Ctrl+C hint), repainted every 200 ms; it never takes the terminal over, keeps the cursor
//!    hidden, and keeps log lines scrolling above it, so preflight stays readable.
//! 2. Board stage: alternate screen with a fixed pool matrix, active stream, completed feed, and footer.
//!
//! All-cache runs skip the board entirely and continue as line output.

mod done;
mod foot;
mod fx;
mod pool;
mod scan;
mod style;
mod task;
mod view;

#[cfg(test)]
mod test;

use std::{
  io::{self, Stderr, stderr},
  panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
  process::exit,
  time::{Duration, Instant},
};

use crossfire::{RecvTimeoutError, Rx, mpsc::List};
use crossterm::{
  cursor::{Hide, Show},
  execute,
  terminal::{EnterAlternateScreen, LeaveAlternateScreen, size},
};
use ratatui::{Terminal, TerminalOptions, Viewport, backend::CrosstermBackend};

use self::{
  done::{DoneFeed, draw_done, print_exit},
  foot::draw_foot,
  fx::{
    ACCENT, BAD, BOLD, DIM, FAINT, GLOW, HOST, NOTE, OK, REPLY, THINK, WARN, draw_waiting,
    paint_rain, style_done_line,
  },
  pool::{PoolCache, draw_pool},
  scan::Scan,
  style::{
    BAR_CHAR_LEN, BAR_DOT, BAR_ON, COL_GAP, COL_GAP_W, RIGHT_PAD, bar_str, dash_str, draw_sec_head,
    pad, row_rect, spin_at,
  },
  task::draw_task,
  view::{Stage, draw},
};
use crate::{
  board::{Act, Board},
  event::Event,
  interrupt::Interrupt,
  plain,
};

type Term = Terminal<CrosstermBackend<Stderr>>;

/// Board redraw interval (80ms)
const FRAME: Duration = Duration::from_millis(80);
/// Global footer row count at bottom of screen
const FOOT_ROW: u16 = 1;
/// Fallback terminal height when crossterm size query fails
const TERM_ROW: u16 = 24;
/// Exit code on SIGINT
const SIGINT_EXIT: i32 = 130;

/// RAII alternate-screen + hidden-cursor guard so normal exits, interrupts, and panics restore the terminal cleanly
struct TermGuard;

impl TermGuard {
  fn enter() -> io::Result<Self> {
    let mut err = stderr();
    execute!(err, EnterAlternateScreen, Hide)?;
    Ok(Self)
  }
}

impl Drop for TermGuard {
  fn drop(&mut self) {
    let _ = execute!(stderr(), Show, LeaveAlternateScreen);
  }
}

fn enter_term() -> io::Result<(TermGuard, Term)> {
  let guard = TermGuard::enter()?;
  let term = Terminal::with_options(
    CrosstermBackend::new(stderr()),
    TerminalOptions {
      viewport: Viewport::Fullscreen,
    },
  )?;
  Ok((guard, term))
}

fn run_plain_rest(board: Board, rx: &Rx<List<Event>>, sig: &Interrupt) {
  if plain::run_from(board, rx, Some(sig)) {
    exit(SIGINT_EXIT);
  }
}

pub(crate) fn run(rx: &Rx<List<Event>>, sig: &Interrupt) {
  let mut board = Board::new();
  let mut scan = Scan::new();
  // Paint the first frame immediately: the walk may already be running before the first event arrives
  scan.paint(&board);
  let mut tick = Instant::now();
  let empty_done = DoneFeed::default();

  // Stage 1: inline scan, no alternate screen
  let interrupted = loop {
    match rx.recv_timeout(scan::FRAME) {
      Ok(event) => match board.apply(event) {
        Act::Plan { job } => {
          scan.finish();
          if job == 0 {
            // Every task is cached: keep line output for the remaining logs and the summary
            run_plain_rest(board, rx, sig);
          } else {
            board_stage(board, rx, sig);
          }
          return;
        }
        Act::Log(text) => scan.note(&text, &board),
        Act::Close => break false,
        _ => {}
      },
      Err(RecvTimeoutError::Timeout) => {}
      Err(RecvTimeoutError::Disconnected) => break false,
    }

    if sig.hit() {
      break true;
    }

    // Steady cadence even while a burst of scan events keeps arriving
    if tick.elapsed() >= scan::FRAME {
      tick = Instant::now();
      scan.paint(&board);
    }
  };
  scan.finish();
  print_exit(&board, &empty_done);
  if interrupted {
    exit(SIGINT_EXIT);
  }
}

/// Stage 2: alternate-screen board; falls back to line output when the terminal refuses the switch
fn board_stage(mut board: Board, rx: &Rx<List<Event>>, sig: &Interrupt) {
  let Ok((guard, mut term)) = enter_term() else {
    run_plain_rest(board, rx, sig);
    return;
  };

  let mut stage = Stage::default();
  let res = catch_unwind(AssertUnwindSafe(|| {
    let begin = Instant::now();
    let mut dim = size().unwrap_or((80, TERM_ROW));
    let mut interrupted = false;
    'main: loop {
      match rx.recv_timeout(FRAME) {
        Ok(event) => {
          if stage.apply(&mut board, event) {
            break;
          }
          while let Ok(event) = rx.try_recv() {
            if stage.apply(&mut board, event) {
              break 'main;
            }
          }
        }
        Err(RecvTimeoutError::Timeout) => {}
        Err(RecvTimeoutError::Disconnected) => break,
      }

      if sig.hit() {
        interrupted = true;
        break;
      }

      let now = size().unwrap_or(dim);
      if now != dim {
        dim = now;
        let _ = term.autoresize();
      }

      stage.reap(Instant::now());
      let frame = (begin.elapsed().as_millis() / FRAME.as_millis()) as usize;
      let _ = term.draw(|f| {
        draw(f.area(), f.buffer_mut(), &board, &mut stage, frame);
      });
    }
    // Failed cards still fading must reach the feed and the exit report
    stage.flush();
    interrupted
  }));

  drop(term);
  drop(guard);

  match res {
    Ok(interrupted) => {
      print_exit(&board, &stage.done);
      if interrupted {
        exit(SIGINT_EXIT);
      }
    }
    Err(payload) => resume_unwind(payload),
  }
}