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
use std::{
  ops::{Deref, DerefMut},
  sync::Arc,
};

use anyhow::{anyhow, Context, Result};
use crossterm::{
  cursor,
  event::{DisableMouseCapture, EnableMouseCapture},
  terminal::{EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::backend::CrosstermBackend as Backend;
use signal_hook::{iterator::Signals, low_level};
use tokio::{
  sync::{mpsc, Mutex},
  task::JoinHandle,
};

use crate::components::{home::Home, Component};

// pub type Frame<'a> = ratatui::Frame<'a, Backend<std::io::Stderr>>;

pub struct Tui {
  pub terminal: ratatui::Terminal<Backend<std::io::Stderr>>,
}

impl Tui {
  pub fn new() -> Result<Self> {
    let terminal = ratatui::Terminal::new(Backend::new(std::io::stderr()))?;

    // spin up a signal handler to catch SIGTERM and exit gracefully
    let _ = std::thread::spawn(move || {
      const SIGNALS: &[libc::c_int] = &[signal_hook::consts::signal::SIGTERM];
      let mut sigs = Signals::new(SIGNALS).unwrap();
      let signal = sigs.into_iter().next().unwrap();
      let _ = exit();
      low_level::emulate_default_handler(signal).unwrap();
    });

    Ok(Self { terminal })
  }

  pub fn enter(&self) -> Result<()> {
    crossterm::terminal::enable_raw_mode()?;
    crossterm::execute!(std::io::stderr(), EnterAlternateScreen, EnableMouseCapture, cursor::Hide)?;
    Ok(())
  }

  pub fn suspend(&self) -> Result<()> {
    exit()?;
    #[cfg(not(windows))]
    signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP)?;
    Ok(())
  }

  pub fn resume(&self) -> Result<()> {
    self.enter()?;
    Ok(())
  }
}

pub fn exit() -> Result<()> {
  crossterm::execute!(std::io::stderr(), LeaveAlternateScreen, DisableMouseCapture, cursor::Show)?;
  crossterm::terminal::disable_raw_mode()?;
  Ok(())
}

impl Deref for Tui {
  type Target = ratatui::Terminal<Backend<std::io::Stderr>>;

  fn deref(&self) -> &Self::Target {
    &self.terminal
  }
}

impl DerefMut for Tui {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.terminal
  }
}

impl Drop for Tui {
  fn drop(&mut self) {
    exit().unwrap();
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Message {
  Render,
  Stop,
  Suspend,
}

pub struct TerminalHandler {
  pub task: JoinHandle<()>,
  tx: mpsc::UnboundedSender<Message>,
  home: Arc<Mutex<Home>>,
  tui: Arc<Mutex<Tui>>,
}

impl TerminalHandler {
  pub fn new(home: Arc<Mutex<Home>>) -> Self {
    let (tx, mut rx) = mpsc::unbounded_channel::<Message>();
    let cloned_home = home.clone();
    let tui = Tui::new().context(anyhow!("Unable to create terminal")).unwrap();
    tui.enter().unwrap();
    let tui = Arc::new(Mutex::new(tui));
    let cloned_tui = tui.clone();
    let task = tokio::spawn(async move {
      loop {
        match rx.recv().await {
          Some(Message::Stop) => {
            exit().unwrap_or_default();
            break;
          },
          Some(Message::Suspend) => {
            let t = tui.lock().await;
            t.suspend().unwrap_or_default();
            break;
          },
          Some(Message::Render) => {
            let mut t = tui.lock().await;
            let mut home = home.lock().await;
            render(&mut t, &mut home);
          },
          None => {},
        }
      }
    });
    Self { task, tx, home: cloned_home, tui: cloned_tui }
  }

  pub fn suspend(&self) -> Result<()> {
    self.tx.send(Message::Suspend)?;
    Ok(())
  }

  pub fn stop(&self) -> Result<()> {
    self.tx.send(Message::Stop)?;
    Ok(())
  }

  pub async fn render(&self) {
    let mut home = self.home.lock().await;
    let mut tui = self.tui.lock().await;
    render(&mut tui, &mut home);
  }

  // little more performant in situations where we don't need to wait for the render to complete
  pub fn enqueue_render(&self) -> Result<()> {
    self.tx.send(Message::Render)?;
    Ok(())
  }
}

fn render(tui: &mut Tui, home: &mut Home) {
  tui
    .draw(|f| {
      home.render(f, f.size());
    })
    .expect("Unable to draw");
}