i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Inline scan stage: a two-line progress block on the normal screen, repainted every 200 ms
//!
//! The block never switches to the alternate screen, so the directory walk and cache preflight stay
//! visible without taking the terminal over; a finished scan clears both lines before the board starts.
//!
//! Rendering prefers a ratatui inline viewport: the framework diffs cells, keeps the cursor hidden,
//! and inserts log lines above the block, so the visible cursor never jumps. The viewport needs the
//! terminal cursor position, which crossterm queries on stdout; when stdout is redirected the query
//! cannot be answered, so a raw two-line painter (hidden cursor, newline-based line reservation)
//! keeps progress visible on stderr.

use std::{
  io::{IsTerminal, Write, stderr, stdout},
  mem::replace,
  time::{Duration, Instant},
};

use crossterm::{
  cursor::{Hide, MoveDown, MoveToColumn, MoveUp, Show},
  queue,
  style::Print,
  terminal::{Clear, ClearType, size},
};
use itoa::Buffer as ItoaBuffer;
use ratatui::{
  Terminal, TerminalOptions, Viewport,
  backend::CrosstermBackend,
  text::{Line, Span},
  widgets::Widget,
};

use super::{ACCENT, BOLD, DIM, OK, Term, row_rect, spin_at};
use crate::{
  board::Board,
  i18n::T,
  plain::emit_log,
  text::{fit_owned, width},
};

/// Repaint interval: scan counters stay readable without flooding the terminal
pub(super) const FRAME: Duration = Duration::from_millis(200);

/// Fallback terminal width when the size query fails
const TERM_COL: u16 = 80;
/// Block height: status line plus quit hint
const ROW: u16 = 2;
/// Column kept free so the last cell never triggers a pending wrap on the bottom row
const FREE_COL: usize = 1;
/// Hint indent: the spinner plus its trailing space, so the hint aligns with the label above
const INDENT: &str = "  ";

/// How the scan block reaches the terminal
enum Render {
  /// stderr is not a terminal: only permanent note lines are emitted
  Off,
  /// Framed inline viewport on stderr
  Inline(Term),
  /// Raw two-line painter used when the inline viewport cannot query the cursor position
  Raw { live: bool },
}

pub(super) struct Scan {
  begin: Instant,
  render: Render,
}

impl Scan {
  pub(super) fn new() -> Self {
    // The inline viewport asks the terminal for the cursor row; crossterm sends that query to
    // stdout. Requiring both streams keeps a redirected stdout from stalling the query for its
    // full timeout, and the raw painter covers that case.
    let render = if !stderr().is_terminal() {
      Render::Off
    } else if stdout().is_terminal() {
      Terminal::with_options(
        CrosstermBackend::new(stderr()),
        TerminalOptions {
          viewport: Viewport::Inline(ROW),
        },
      )
      .map_or(Render::Raw { live: false }, Render::Inline)
    } else {
      Render::Raw { live: false }
    };
    Self {
      begin: Instant::now(),
      render,
    }
  }

  /// Repaint the block with the newest counters
  pub(super) fn paint(&mut self, board: &Board) {
    let elapsed = self.begin.elapsed();
    match &mut self.render {
      Render::Off => {}
      Render::Inline(term) => draw(term, board, elapsed),
      Render::Raw { live } => paint_raw(board, elapsed, live),
    }
  }

  /// Print a permanent line above the block
  pub(super) fn note(&mut self, text: &str, board: &Board) {
    match &mut self.render {
      Render::Off => {
        emit_log(text);
        return;
      }
      Render::Inline(term) => {
        let line = T.ui.log(text);
        // Scrolling regions keep the viewport intact; the immediate redraw also covers the
        // portable fallback that clears it
        let _ = term.insert_before(1, |buf| {
          Line::raw(line).render(buf.area, buf);
        });
        draw(term, board, self.begin.elapsed());
        return;
      }
      Render::Raw { live } => {
        if *live {
          erase_raw();
          *live = false;
        }
        emit_log(text);
      }
    }
    self.paint(board);
  }

  /// Erase the block, leaving the cursor at the start of its first line
  pub(super) fn finish(&mut self) {
    match replace(&mut self.render, Render::Off) {
      Render::Off => {}
      Render::Inline(mut term) => {
        let area = term.get_frame().area();
        let _ = term.clear();
        let _ = term.set_cursor_position((area.x, area.y));
        // Dropping the terminal restores cursor visibility
      }
      Render::Raw { mut live } => end_raw(&mut live),
    }
  }
}

impl Drop for Scan {
  fn drop(&mut self) {
    // Also runs while unwinding: never leave the cursor hidden or the viewport anchored
    self.finish();
  }
}

/// Draw both block lines into the inline viewport
fn draw(term: &mut Term, board: &Board, elapsed: Duration) {
  let _ = term.draw(|f| {
    let area = f.area();
    if area.width == 0 || area.height == 0 {
      return;
    }
    let w = usize::from(area.width).saturating_sub(FREE_COL);
    status_line(board, elapsed, w).render(row_rect(area, area.y), f.buffer_mut());
    if area.height > 1 {
      hint_line(w).render(row_rect(area, area.y + 1), f.buffer_mut());
    }
  });
}

/// Status line: cyan spinner and label, bold checked/total, green cache hits
///
/// Styled segments cannot be clipped by display width, so a terminal narrower than the full line
/// falls back to one plain, clipped run.
fn status_line(board: &Board, elapsed: Duration, w: usize) -> Line<'static> {
  let frame = (elapsed.as_millis() / FRAME.as_millis()) as usize;
  let mut num = ItoaBuffer::new();
  // Spinner, label, checked/total, cache hits: at most nine spans
  let mut span_li = Vec::with_capacity(9);
  span_li.push(Span::styled(spin_at(frame), ACCENT));
  span_li.push(Span::raw(" "));
  span_li.push(Span::raw(T.ui.scan()));
  if board.scan_found > 0 {
    span_li.push(Span::raw(" "));
    if board.scan_checked > 0 {
      span_li.push(Span::styled(
        num.format(board.scan_checked).to_owned(),
        BOLD,
      ));
      span_li.push(Span::styled("/", DIM));
      span_li.push(Span::styled(num.format(board.scan_found).to_owned(), BOLD));
    } else {
      span_li.push(Span::styled(num.format(board.scan_found).to_owned(), BOLD));
    }
  }
  if board.scan_cache > 0 {
    span_li.push(Span::raw("  "));
    span_li.push(Span::styled(T.ui.count_cache(board.scan_cache), OK));
  }
  let line = Line::from(span_li);
  if line.width() <= w {
    line
  } else {
    Line::raw(fit_owned(line.to_string(), w))
  }
}

/// Quit hint, dimmed unless it has to be clipped
fn hint_line(w: usize) -> Line<'static> {
  let hint = T.ui.quit_hint();
  if INDENT.len() + width(hint) > w {
    let mut text = String::with_capacity(INDENT.len() + hint.len());
    text.push_str(INDENT);
    text.push_str(hint);
    Line::raw(fit_owned(text, w))
  } else {
    Line::from(vec![Span::raw(INDENT), Span::styled(hint, DIM)])
  }
}

/// Usable columns for the raw painter: terminal width minus the reserved trailing column
fn usable_col() -> usize {
  match size() {
    Ok((w, _)) if usize::from(w) > FREE_COL => usize::from(w) - FREE_COL,
    // Unknown width: the conventional fallback still keeps the trailing column free
    _ => usize::from(TERM_COL) - FREE_COL,
  }
}

/// Raw painter used when the terminal state cannot be queried
///
/// Line two is opened with a newline instead of a relative move: on the last row that scrolls the
/// terminal, so the second line always exists regardless of where the block sits.
fn paint_raw(board: &Board, elapsed: Duration, live: &mut bool) {
  let w = usable_col();
  let status = status_line(board, elapsed, w).to_string();
  let hint = hint_line(w).to_string();
  let mut err = stderr().lock();
  if !*live {
    let _ = queue!(err, Hide);
    *live = true;
  }
  let _ = queue!(err, MoveToColumn(0), Clear(ClearType::UntilNewLine));
  let _ = queue!(err, Print(status));
  let _ = queue!(
    err,
    Print("\r\n"),
    MoveToColumn(0),
    Clear(ClearType::UntilNewLine)
  );
  let _ = queue!(err, Print(hint));
  let _ = queue!(err, MoveUp(1), MoveToColumn(0));
  let _ = err.flush();
}

/// Clear both block lines, leaving the cursor at the start of the first
fn erase_raw() {
  let mut err = stderr().lock();
  let _ = queue!(
    err,
    MoveToColumn(0),
    Clear(ClearType::UntilNewLine),
    MoveDown(1),
    MoveToColumn(0),
    Clear(ClearType::UntilNewLine),
    MoveUp(1),
    MoveToColumn(0),
  );
  let _ = err.flush();
}

/// Erase the raw block and restore cursor visibility
fn end_raw(live: &mut bool) {
  if !*live {
    return;
  }
  erase_raw();
  let mut err = stderr().lock();
  let _ = queue!(err, Show);
  let _ = err.flush();
  *live = false;
}