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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use crate::keys::Key;
use crate::terminal::Options;
use crate::terminal::Terminal;
use crate::Result;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
pub use crossterm::terminal::disable_raw_mode;
use crossterm::{
    event::{self, Event, KeyCode},
    terminal,
};
use std::io::{stdout, Stdout, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

///
/// # Crossterm
///
/// Wrapper around Crossterm interface - [https://crates.io/crates/crossterm](https://crates.io/crates/crossterm)
///
pub struct Crossterm {
    terminal: Arc<Mutex<Option<Arc<Terminal>>>>,
    terminate: Arc<AtomicBool>,
    stdout: Arc<Mutex<Option<Stdout>>>,
}

impl Crossterm {
    pub fn try_new() -> Result<Self> {
        Self::try_new_with_options(&Options::default())
    }
    pub fn try_new_with_options(_options: &Options) -> Result<Self> {
        let crossterm = Crossterm {
            terminal: Arc::new(Mutex::new(None)),
            terminate: Arc::new(AtomicBool::new(false)),
            stdout: Arc::new(Mutex::new(Some(stdout()))),
            // stdout: Arc::new(Mutex::new(Some(stdout().into_raw_mode().unwrap()))),
        };
        Ok(crossterm)
    }

    pub async fn init(self: &Arc<Self>, terminal: &Arc<Terminal>) -> Result<()> {
        *self.terminal.lock().unwrap() = Some(terminal.clone());
        Ok(())
    }

    pub fn exit(&self) {
        self.terminate.store(true, Ordering::SeqCst);
    }

    pub fn terminal(&self) -> Arc<Terminal> {
        self.terminal.lock().unwrap().as_ref().unwrap().clone()
    }

    pub async fn run(&self) -> Result<()> {
        terminal::enable_raw_mode()?;
        self.flush();
        self.intake(&self.terminate).await?;
        self.flush();
        terminal::disable_raw_mode()?;

        Ok(())
    }

    pub async fn intake(&self, terminate: &Arc<AtomicBool>) -> Result<()> {
        loop {
            let event = event::read()?;
            // println!("{:?}",event);
            if let Event::Key(key) = event {
                if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
                    let key = match key.code {
                        KeyCode::Char(c) => {
                            if key.modifiers & KeyModifiers::ALT == KeyModifiers::ALT {
                                Key::Alt(c)
                            } else if key.modifiers & KeyModifiers::CONTROL == KeyModifiers::CONTROL
                            {
                                Key::Ctrl(c)
                            } else {
                                Key::Char(c)
                            }
                        }
                        KeyCode::Enter => Key::Enter,
                        KeyCode::Esc => Key::Esc,
                        KeyCode::Left => Key::ArrowLeft,
                        KeyCode::Right => Key::ArrowRight,
                        KeyCode::Up => Key::ArrowUp,
                        KeyCode::Down => Key::ArrowDown,
                        KeyCode::Backspace => Key::Backspace,
                        _ => {
                            continue;
                        }
                    };

                    self.terminal().ingest(key, "".to_string()).await?;
                    self.flush();

                    if terminate.load(Ordering::SeqCst) {
                        break;
                    }
                }
            }
        }

        Ok(())
    }

    pub fn write<S>(&self, s: S)
    where
        S: ToString,
    {
        print!("{}", s.to_string());
        self.flush();
    }

    pub fn flush(&self) {
        // stdout
        if let Some(stdout) = self.stdout.lock().unwrap().as_mut() {
            stdout.flush().unwrap();
        }
    }
}

use std::{panic, process};

/// configure custom panic hook that disables terminal raw mode
/// supply a closure that will be called when a panic occurs
/// giving an opportunity to output a custom message.  The closure
/// should return a desirable process exit code.
pub fn init_panic_hook<F>(f: F)
where
    F: Fn() -> i32 + Send + Sync + 'static,
{
    let default_hook = panic::take_hook();
    panic::set_hook(Box::new(move |panic_info| {
        disable_raw_mode().ok();
        default_hook(panic_info);
        let exit_code = f();
        process::exit(exit_code);
    }));
}

// compatibility functions
impl Crossterm {
    pub fn get_font_size(&self) -> Result<Option<f64>> {
        Ok(None)
    }

    pub fn set_font_size(&self, _font_size: f64) -> Result<()> {
        Ok(())
    }

    pub fn cols(&self) -> Option<usize> {
        None
    }

    pub fn rows(&self) -> Option<usize> {
        None
    }

    pub fn increase_font_size(&self) -> Result<Option<f64>> {
        Ok(None)
    }

    pub fn decrease_font_size(&self) -> Result<Option<f64>> {
        Ok(None)
    }
}