pub mod app;
pub mod command;
pub mod event;
mod runner;
mod ui;
use crate::tui::{app::App, event::AppEvent};
use anyhow::Result;
use crossterm::{self, cursor, event as crossterm_event, terminal};
use ratatui::{self, backend};
use std::{io, path::PathBuf, sync::mpsc, time::Duration};
const RECV_TIMEOUT: Duration = Duration::from_millis(250);
struct TerminalGuard;
impl Drop for TerminalGuard {
fn drop(&mut self) {
let _ = terminal::disable_raw_mode();
let _ = crossterm::execute!(
io::stdout(),
cursor::Show,
terminal::LeaveAlternateScreen,
crossterm_event::DisableMouseCapture
);
}
}
pub fn run(ffmpeg_path: Option<PathBuf>) -> Result<()> {
terminal::enable_raw_mode()?;
let mut stdout = io::stdout();
crossterm::execute!(
stdout,
terminal::EnterAlternateScreen,
crossterm_event::EnableMouseCapture,
cursor::Hide,
)?;
let backend = backend::CrosstermBackend::new(stdout);
let mut terminal = ratatui::Terminal::new(backend)?;
let _guard = TerminalGuard;
let (tx, rx) = mpsc::channel::<AppEvent>();
let _input_handle = event::spawn_input_thread(tx.clone());
let mut app = App::new(ffmpeg_path);
let result = event_loop(&mut terminal, &mut app, tx, rx);
terminal.show_cursor()?;
result
}
fn event_loop(
terminal: &mut ratatui::Terminal<backend::CrosstermBackend<io::Stdout>>,
app: &mut App,
tx: mpsc::Sender<AppEvent>,
rx: mpsc::Receiver<AppEvent>,
) -> Result<()> {
loop {
terminal.draw(|f| ui::draw(f, app))?;
match rx.recv_timeout(RECV_TIMEOUT) {
Ok(AppEvent::Key(key)) => {
app.handle_key(key, &tx);
if app.should_quit {
break;
}
}
Ok(AppEvent::Log(line)) => app.push_log(line),
Ok(AppEvent::FileStarted(i)) => app.file_started(i),
Ok(AppEvent::FileDone(i, ok)) => app.file_done(i, ok),
Ok(AppEvent::AllDone { succeeded, failed }) => app.all_done(succeeded, failed),
Ok(AppEvent::Tick) | Err(mpsc::RecvTimeoutError::Timeout) => app.tick(),
Ok(AppEvent::CancelAll) => {
if let Some(token) = &app.cancel_token {
token.cancel();
}
}
Ok(AppEvent::CancelledWithResidual(files)) => app.cancelled_with_residual(files),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
Ok(())
}