cgd 0.1.0-alpha.2

Official command-line interface for Coragrid source-linked private-market data infrastructure
Documentation
mod app;
mod effect;
mod terminal;
mod ui;

use std::env;
use std::io::{self, IsTerminal};
use std::time::Duration;

use crossterm::event::{Event, EventStream, KeyEventKind};
#[cfg(unix)]
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use futures_util::StreamExt;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time::{self, MissedTickBehavior};

use self::app::{App, AppAction};
use self::effect::EffectResult;
use self::terminal::{PanicRestoreGuard, TerminalSession};
use self::ui::Theme;
use crate::cli::{Cli, ThemeArg};
use crate::client::CoragridClient;
use crate::config::EffectiveConfig;
use crate::error::CgdError;
use crate::signals::{TuiSignal, TuiSignals};

#[derive(Debug, Clone, Copy)]
pub struct TuiOptions {
    pub mouse: bool,
    pub theme: ThemeArg,
}

pub fn is_suitable(cli: &Cli) -> bool {
    if cli.output.is_some() || cli.json || cli.quiet {
        return false;
    }
    if env::var_os("CI").is_some()
        || env::var("TERM").is_ok_and(|terminal| terminal.eq_ignore_ascii_case("dumb"))
    {
        return false;
    }
    io::stdin().is_terminal() && io::stdout().is_terminal() && io::stderr().is_terminal()
}

pub async fn run(config: EffectiveConfig, options: TuiOptions) -> Result<(), CgdError> {
    let client = CoragridClient::new(&config)?;
    let mut signals = TuiSignals::new().map_err(|error| {
        CgdError::Internal(format!("cannot initialize signal handling: {error}"))
    })?;
    let _panic_restore = PanicRestoreGuard::install(options.mouse);
    let mut terminal = TerminalSession::enter(options.mouse)?;
    let theme = Theme::from_argument(options.theme);
    run_loop(&mut terminal, client, config, theme, &mut signals).await
}

async fn run_loop(
    terminal: &mut TerminalSession,
    client: CoragridClient,
    config: EffectiveConfig,
    theme: Theme,
    signals: &mut TuiSignals,
) -> Result<(), CgdError> {
    let mut app = App::new(&config.warnings);
    let mut events = EventStream::new();
    let (effect_sender, mut effect_receiver) = mpsc::channel::<EffectResult>(8);
    let mut active_effect: Option<JoinHandle<()>> = None;
    let mut ticks = time::interval(Duration::from_millis(250));
    ticks.set_missed_tick_behavior(MissedTickBehavior::Skip);

    loop {
        terminal
            .terminal_mut()
            .draw(|frame| ui::render(frame, &mut app, theme, &config))
            .map_err(CgdError::from)?;
        if app.should_quit {
            break;
        }

        tokio::select! {
            event = events.next() => {
                match event {
                    Some(Ok(Event::Key(key)))
                        if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) =>
                    {
                        #[cfg(unix)]
                        if is_suspend_key(key) {
                            terminal.suspend()?;
                            continue;
                        }
                        handle_action(
                            app.handle_key(key),
                            &client,
                            &effect_sender,
                            &mut active_effect,
                        );
                    }
                    Some(Ok(Event::Key(_))) => {}
                    Some(Ok(Event::Mouse(mouse))) => app.handle_mouse(mouse),
                    Some(Ok(Event::Paste(value))) => app.handle_paste(&value),
                    Some(Ok(Event::FocusGained)) => app.set_terminal_focus(true),
                    Some(Ok(Event::FocusLost)) => app.set_terminal_focus(false),
                    Some(Ok(Event::Resize(_, _))) => {}
                    Some(Err(error)) => return Err(CgdError::Io(error)),
                    None => {
                        return Err(CgdError::Unavailable(
                            "terminal event stream ended unexpectedly".to_owned(),
                        ));
                    }
                }
            }
            Some(result) = effect_receiver.recv() => {
                active_effect = None;
                app.apply(result);
            }
            _ = ticks.tick() => app.tick(),
            signal = signals.recv() => {
                let signal = signal.map_err(|error| CgdError::Internal(
                    format!("cannot listen for terminal interruption: {error}")
                ))?;
                #[cfg(unix)]
                if signal == TuiSignal::Suspend {
                    terminal.suspend()?;
                    continue;
                }
                match (signal, active_effect.take()) {
                    (TuiSignal::Interrupt, Some(task)) => {
                        task.abort();
                        app.loading = false;
                        app.notice = Some("request cancelled".to_owned());
                    }
                    (_, task) => {
                        if let Some(task) = task {
                            task.abort();
                        }
                        app.should_quit = true;
                    }
                }
            }
        }
    }
    if let Some(task) = active_effect {
        task.abort();
    }
    Ok(())
}

#[cfg(unix)]
fn is_suspend_key(key: KeyEvent) -> bool {
    key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('z'))
}

fn handle_action(
    action: AppAction,
    client: &CoragridClient,
    sender: &mpsc::Sender<EffectResult>,
    active: &mut Option<JoinHandle<()>>,
) {
    match action {
        AppAction::None => {}
        AppAction::Cancel => {
            if let Some(task) = active.take() {
                task.abort();
            }
        }
        AppAction::Start(effect) => {
            if let Some(task) = active.take() {
                task.abort();
            }
            let client = client.clone();
            let sender = sender.clone();
            *active = Some(tokio::spawn(async move {
                let result = effect::execute(client, *effect).await;
                let _ = sender.send(result).await;
            }));
        }
    }
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;

    #[test]
    fn machine_output_prevents_automatic_tui_entry() {
        let cli = Cli::try_parse_from(["cgd", "--output", "json"]).unwrap();
        assert!(!is_suitable(&cli));
    }
}