use crate::crt::crt;
use indicatif::{ProgressBar, ProgressStyle};
use std::path::PathBuf;
use std::time::Duration;
#[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 {
pub image_path: PathBuf,
#[arg(short, long, help = "Set upscale factor.", default_value_t = 2)]
pub upscale_factor: u32,
#[arg(short, long, help = "Skip scanline effect.", default_value_t = false)]
pub scanline_disable: bool,
#[arg(long, help = "Set scanline height in pixel of scaled image.")]
pub scanline_height: Option<u32>,
#[arg(short, long, help = "Add distortion effect.", default_value_t = false)]
pub distortion: bool,
#[arg(
long,
help = "Set barrel distortion strength.",
default_value_t = 2.0e-7
)]
pub distortion_strength: f64,
#[arg(short, long, help = "Add post-blur effect", default_value_t = false)]
pub blur: bool,
#[arg(
short,
long,
help = "Save intermediate processing steps",
default_value_t = false
)]
pub cache: bool,
}
impl Cli {
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...");
let param = self.clone();
let task = tokio::task::spawn(async move {
crt(
&image,
param.upscale_factor,
actual_scanline_height, param.scanline_disable,
param.distortion,
param.distortion_strength,
param.blur,
param.cache,
)
.await
});
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(())
}
}