crtimg 0.1.0

A CLI tool that processes a pixel art image to make it CRT-ish.
Documentation
//! # Command-Line Interface Module
//!
//! This module defines the command-line interface for the `crtimg` application.
//! It uses the `clap` crate to parse arguments and orchestrate the main application flow.

use crate::crt::crt;
use indicatif::{ProgressBar, ProgressStyle};
use std::path::PathBuf;
use std::time::Duration;

/// A CLI tool that processes a pixel art image to give it a CRT-like effect.
#[derive(clap::Parser, Debug, Clone)]
#[command(
    version,
    about = "A CLI tool that processes a pixel art image to make it CRT-ish.",
    author = "Dexter Chen<dexterccc@126.com>"
)]
pub struct Cli {
    /// The path to the input image file.
    pub image_path: PathBuf,
    /// The factor by which to upscale the image. Must be 2 or greater.
    #[arg(short, long, help = "Set upscale factor.", default_value_t = 2)]
    pub upscale_factor: u32,
    /// If set, the scanline effect will not be applied.
    #[arg(short, long, help = "Skip scanline effect.", default_value_t = false)]
    pub scanline_disable: bool,
    /// The height of the scanlines in pixels on the upscaled image.
    /// If not provided, it defaults to `upscale_factor / 2`.
    /// Must be greater than 0 and less than `upscale_factor`.
    #[arg(long, help = "Set scanline height in pixel of scaled image.")]
    pub scanline_height: Option<u32>,
    /// If set, a barrel distortion effect is applied to simulate a curved screen.
    #[arg(short, long, help = "Add distortion effect.", default_value_t = false)]
    pub distortion: bool,
    /// Sets the strength of the barrel distortion effect.
    /// A larger value results in a more pronounced curve.
    #[arg(
        long,
        help = "Set barrel distortion strength.",
        default_value_t = 2.0e-7
    )]
    pub distortion_strength: f64,
    /// If set, a final Gaussian blur is applied to the image.
    #[arg(short, long, help = "Add post-blur effect", default_value_t = false)]
    pub blur: bool,
    /// If set, intermediate processing steps are saved as images in a `./cache/` directory.
    #[arg(
        short,
        long,
        help = "Save intermediate processing steps",
        default_value_t = false
    )]
    pub cache: bool,
}

impl Cli {
    /// Executes the main logic of the CLI application.
    ///
    /// This function performs the following steps:
    /// 1.  Validates the provided `upscale_factor` and `scanline_height` arguments.
    /// 2.  Determines the output file path.
    /// 3.  Opens the input image.
    /// 4.  Initializes and displays a progress spinner.
    /// 5.  Spawns an asynchronous task to process the image using the `crt` function.
    /// 6.  Waits for the processing to complete.
    /// 7.  Saves the resulting image to the output path.
    pub async fn run(&self) -> anyhow::Result<()> {
        if self.upscale_factor < 2 {
            return Err(anyhow::anyhow!("Upscale factor must be at least 2."));
        }

        let actual_scanline_height = self.scanline_height.unwrap_or(self.upscale_factor / 2);

        if actual_scanline_height == 0 || actual_scanline_height >= self.upscale_factor {
            return Err(anyhow::anyhow!(
                "Scanline height must be > 0 and < upscale_factor."
            ));
        }

        let filename = self.image_path.file_name().unwrap().to_str().unwrap();
        let mut filename_splits = filename.split(".");
        let base_name = filename_splits
            .next()
            .ok_or_else(|| anyhow::format_err!("Failed to get the base file name."))?;
        let extension = filename_splits
            .next()
            .ok_or_else(|| anyhow::format_err!("Failed to get the extension."))?;

        let image = image::open(&self.image_path)?;
        let spinner = ProgressBar::new_spinner();
        spinner.set_style(
            ProgressStyle::default_spinner()
                .tick_strings(&["-", "\\", "|", "/"])
                .template("{spinner:.blue} {msg}")?,
        );

        spinner.enable_steady_tick(Duration::from_millis(100));
        spinner.set_message("Processing image...");

        // Spawn the image processing task to keep the spinner responsive.
        let param = self.clone();
        let task = tokio::task::spawn(async move {
            crt(
                &image,
                param.upscale_factor,
                actual_scanline_height, // Use the calculated actual_scanline_height
                param.scanline_disable,
                param.distortion,
                param.distortion_strength,
                param.blur,
                param.cache,
            )
            .await
        });

        // Wait for the task to complete and retrieve the result.
        let processed = task.await??;
        spinner.finish_and_clear();
        log::info!("Image process finished");

        let output_path = self
            .image_path
            .with_file_name(format!("{}-crt.{}", base_name, extension));
        processed.save(&output_path)?;
        log::info!("Proccessed image saved to: {}", output_path.display());

        Ok(())
    }
}