fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
//! The terminal and the event loop.
//!
//! This is the only part of the crate that owns a terminal. Everything it does is to draw an
//! [`App`] and to feed key presses back into it.

use crate::app::App;
use crate::app::AppError;
use crate::app::Theme;
use crate::app::input;
use crate::app::ui;
use ratatui::DefaultTerminal;
use ratatui::crossterm::event;
use ratatui::crossterm::event::Event;

/// Play a game in the terminal until the player leaves.
///
/// The terminal is restored before this function returns, including when the game ends with an
/// error.
///
/// # Errors
///
/// Returns an [`AppError`] if the terminal cannot be prepared, drawn to, read from or restored.
pub fn run(app: App) -> Result<(), AppError> {
    run_with_theme(app, &Theme::default())
}

/// Play a game in the terminal with colours of your own.
///
/// # Errors
///
/// See [`run`].
pub fn run_with_theme(mut app: App, theme: &Theme) -> Result<(), AppError> {
    let mut terminal = ratatui::try_init().map_err(AppError::TerminalSetup)?;
    let outcome = play(&mut app, &mut terminal, theme);
    let restored = ratatui::try_restore().map_err(AppError::TerminalRestore);

    // The terminal is restored either way, and a failure during play is the more interesting one.
    outcome.and(restored)
}

fn play(app: &mut App, terminal: &mut DefaultTerminal, theme: &Theme) -> Result<(), AppError> {
    while app.is_running() {
        draw(app, terminal, theme)?;

        if let Event::Key(key) = event::read().map_err(AppError::Input)?
            && let Some(action) = input::action_for(key)
        {
            app.handle(action);
        }
    }

    Ok(())
}

fn draw(app: &App, terminal: &mut DefaultTerminal, theme: &Theme) -> Result<(), AppError> {
    terminal
        .draw(|frame| ui::render(app, theme, frame.area(), frame.buffer_mut()))
        .map(|_| ())
        .map_err(AppError::Draw)
}