summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: aa5fc35649f905ee26aee0e49abe218a63ebcf15 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![allow(clippy::missing_const_for_fn)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::unused_self)]

mod action;
mod history;
mod readline;
mod state;
mod util;

use async_std::stream::StreamExt as _;

async fn async_main() -> anyhow::Result<()> {
    let mut input = textmode::Input::new().await?;
    let mut output = textmode::Output::new().await?;

    // avoid the guards getting stuck in a task that doesn't run to
    // completion
    let _input_guard = input.take_raw_guard();
    let _output_guard = output.take_screen_guard();

    let (action_w, action_r) = async_std::channel::unbounded();

    let mut state = state::State::new(action_w, output);
    state.render().await.unwrap();

    let state = util::mutex(state);

    {
        let state = async_std::sync::Arc::clone(&state);
        let mut signals = signal_hook_async_std::Signals::new(&[
            signal_hook::consts::signal::SIGWINCH,
        ])?;
        async_std::task::spawn(async move {
            while signals.next().await.is_some() {
                state.lock_arc().await.resize().await;
            }
        });
    }

    state.lock_arc().await.resize().await;

    {
        let state = async_std::sync::Arc::clone(&state);
        async_std::task::spawn(async move {
            let debouncer = crate::action::debounce(action_r);
            while let Some(action) = debouncer.recv().await {
                state.lock_arc().await.handle_action(action).await;
            }
        });
    }

    while let Some(key) = input.read_key().await.unwrap() {
        if state.lock_arc().await.handle_input(key).await {
            break;
        }
    }

    Ok(())
}

fn main() {
    match async_std::task::block_on(async_main()) {
        Ok(_) => (),
        Err(e) => {
            eprintln!("nbsh: {}", e);
            std::process::exit(1);
        }
    };
}