#![forbid(unsafe_code)]
use std::time::Duration;
use anyhow::Result;
use chrono::Local;
use clap::Parser;
use crossterm::event;
use tasu::app::{Action, Model, Problem, Runtime};
use tasu::cli::{Cli, Command};
use tasu::command;
use tasu::config::Config;
use tasu::domain::Bucket;
use tasu::session;
use tasu::ui::{Chrome, theme::Theme};
const TICK: Duration = Duration::from_millis(200);
fn main() -> std::process::ExitCode {
match run() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(err) => {
eprintln!("{err:#}");
std::process::ExitCode::FAILURE
}
}
}
fn run() -> Result<()> {
let cli = Cli::parse();
let config = Config::load();
match cli.command {
Some(Command::Add { title }) => command::add(&config, &title),
Some(Command::List { bucket, json }) => {
command::list(&config, bucket.map(Bucket::from), json)
}
Some(Command::History { view, json }) => command::history(
&config,
view.map(command::HistoryList::from)
.unwrap_or(command::HistoryList::Both),
json,
),
Some(Command::Done { title }) => command::done(&config, &title),
Some(Command::Drop { title }) => command::drop_task(&config, &title),
Some(Command::Move { bucket, title }) => command::move_task(&config, bucket.into(), &title),
Some(Command::Config { json }) => command::config(&config, json),
Some(Command::Remote { url, clear }) => command::remote(&config, url.as_deref(), clear),
Some(Command::Sync) => command::sync(&config),
Some(Command::Update) => command::update(),
Some(Command::Completions { shell }) => command::completions(shell),
Some(Command::Flush) => command::flush(&config),
None => run_tui(config),
}
}
fn run_tui(config: Config) -> Result<()> {
let board_path = config.board_path();
let remote = config.remote.clone();
let mut runtime = Runtime::new(&config);
let now = Local::now();
let loaded = runtime.load_board(now);
let mut model = Model::new(loaded.board, now);
model.ui.board_damage = loaded.damaged.as_ref().map(Problem::from_damage);
let theme = Theme::detect();
let chrome = Chrome {
data_path: &board_path,
remote: remote.as_deref(),
};
runtime.start_sync();
let result: Result<()> = ratatui::run(|terminal| {
session::run(
terminal,
&mut runtime,
&mut model,
&theme,
&chrome,
next_action,
)
});
if remote.is_some() && runtime.needs_flush() {
spawn_background_flush();
}
result?;
if let Some(error) = runtime.quit_error() {
anyhow::bail!("{error}");
}
Ok(())
}
fn spawn_background_flush() {
let Ok(exe) = std::env::current_exe() else {
return;
};
let _ = std::process::Command::new(exe)
.arg("flush")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
}
fn next_action() -> Result<Action> {
if event::poll(TICK)? {
let event = event::read()?;
Ok(match event.as_key_press_event() {
Some(key) => Action::Key(key),
None => Action::Tick,
})
} else {
Ok(Action::Tick)
}
}