|
| 1 | +use crossterm::{ |
| 2 | + event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, |
| 3 | + execute, |
| 4 | + terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, |
| 5 | +}; |
| 6 | +use sqlx::postgres::PgListener; |
| 7 | +use sqlx::PgPool; |
| 8 | +use std::sync::Arc; |
| 9 | +use std::{error::Error, io}; |
| 10 | +use tokio::{sync::Mutex, time::Duration}; |
| 11 | +use tui::{ |
| 12 | + backend::{Backend, CrosstermBackend}, |
| 13 | + layout::{Constraint, Direction, Layout}, |
| 14 | + style::{Color, Modifier, Style}, |
| 15 | + text::{Span, Spans, Text}, |
| 16 | + widgets::{Block, Borders, List, ListItem, Paragraph}, |
| 17 | + Frame, Terminal, |
| 18 | +}; |
| 19 | +use unicode_width::UnicodeWidthStr; |
| 20 | + |
| 21 | +struct ChatApp { |
| 22 | + input: String, |
| 23 | + messages: Arc<Mutex<Vec<String>>>, |
| 24 | + pool: PgPool, |
| 25 | +} |
| 26 | + |
| 27 | +impl ChatApp { |
| 28 | + fn new(pool: PgPool) -> Self { |
| 29 | + ChatApp { |
| 30 | + input: String::new(), |
| 31 | + messages: Arc::new(Mutex::new(Vec::new())), |
| 32 | + pool, |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + async fn run<B: Backend>( |
| 37 | + mut self, |
| 38 | + terminal: &mut Terminal<B>, |
| 39 | + mut listener: PgListener, |
| 40 | + ) -> Result<(), Box<dyn Error>> { |
| 41 | + // setup listener task |
| 42 | + let messages = self.messages.clone(); |
| 43 | + tokio::spawn(async move { |
| 44 | + while let Ok(msg) = listener.recv().await { |
| 45 | + messages.lock().await.push(msg.payload().to_string()); |
| 46 | + } |
| 47 | + }); |
| 48 | + |
| 49 | + loop { |
| 50 | + let messages: Vec<ListItem> = self |
| 51 | + .messages |
| 52 | + .lock() |
| 53 | + .await |
| 54 | + .iter() |
| 55 | + .map(|m| { |
| 56 | + let content = vec![Spans::from(Span::raw(m.to_owned()))]; |
| 57 | + ListItem::new(content) |
| 58 | + }) |
| 59 | + .collect(); |
| 60 | + |
| 61 | + terminal.draw(|f| self.ui(f, messages))?; |
| 62 | + |
| 63 | + if !event::poll(Duration::from_millis(20))? { |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + if let Event::Key(key) = event::read()? { |
| 68 | + match key.code { |
| 69 | + KeyCode::Enter => { |
| 70 | + notify(&self.pool, &self.input).await?; |
| 71 | + self.input.clear(); |
| 72 | + } |
| 73 | + KeyCode::Char(c) => { |
| 74 | + self.input.push(c); |
| 75 | + } |
| 76 | + KeyCode::Backspace => { |
| 77 | + self.input.pop(); |
| 78 | + } |
| 79 | + KeyCode::Esc => { |
| 80 | + return Ok(()); |
| 81 | + } |
| 82 | + _ => {} |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + fn ui<B: Backend>(&mut self, frame: &mut Frame<B>, messages: Vec<ListItem>) { |
| 89 | + let chunks = Layout::default() |
| 90 | + .direction(Direction::Vertical) |
| 91 | + .margin(2) |
| 92 | + .constraints( |
| 93 | + [ |
| 94 | + Constraint::Length(1), |
| 95 | + Constraint::Length(3), |
| 96 | + Constraint::Min(1), |
| 97 | + ] |
| 98 | + .as_ref(), |
| 99 | + ) |
| 100 | + .split(frame.size()); |
| 101 | + |
| 102 | + let text = Text::from(Spans::from(vec![ |
| 103 | + Span::raw("Press "), |
| 104 | + Span::styled("Enter", Style::default().add_modifier(Modifier::BOLD)), |
| 105 | + Span::raw(" to send the message, "), |
| 106 | + Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)), |
| 107 | + Span::raw(" to quit"), |
| 108 | + ])); |
| 109 | + let help_message = Paragraph::new(text); |
| 110 | + frame.render_widget(help_message, chunks[0]); |
| 111 | + |
| 112 | + let input = Paragraph::new(self.input.as_ref()) |
| 113 | + .style(Style::default().fg(Color::Yellow)) |
| 114 | + .block(Block::default().borders(Borders::ALL).title("Input")); |
| 115 | + frame.render_widget(input, chunks[1]); |
| 116 | + frame.set_cursor( |
| 117 | + // Put cursor past the end of the input text |
| 118 | + chunks[1].x + self.input.width() as u16 + 1, |
| 119 | + // Move one line down, from the border to the input line |
| 120 | + chunks[1].y + 1, |
| 121 | + ); |
| 122 | + |
| 123 | + let messages = |
| 124 | + List::new(messages).block(Block::default().borders(Borders::ALL).title("Messages")); |
| 125 | + frame.render_widget(messages, chunks[2]); |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +#[tokio::main] |
| 130 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 131 | + // setup postgres |
| 132 | + let conn_url = |
| 133 | + std::env::var("DATABASE_URL").expect("Env var DATABASE_URL is required for this example."); |
| 134 | + let pool = sqlx::PgPool::connect(&conn_url).await?; |
| 135 | + |
| 136 | + let mut listener = PgListener::connect(&conn_url).await?; |
| 137 | + listener.listen("chan0").await?; |
| 138 | + |
| 139 | + // setup terminal |
| 140 | + enable_raw_mode()?; |
| 141 | + let mut stdout = io::stdout(); |
| 142 | + execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?; |
| 143 | + let backend = CrosstermBackend::new(stdout); |
| 144 | + let mut terminal = Terminal::new(backend)?; |
| 145 | + |
| 146 | + // create app and run it |
| 147 | + let app = ChatApp::new(pool); |
| 148 | + let res = app.run(&mut terminal, listener).await; |
| 149 | + |
| 150 | + // restore terminal |
| 151 | + disable_raw_mode()?; |
| 152 | + execute!( |
| 153 | + terminal.backend_mut(), |
| 154 | + LeaveAlternateScreen, |
| 155 | + DisableMouseCapture, |
| 156 | + )?; |
| 157 | + terminal.show_cursor()?; |
| 158 | + |
| 159 | + if let Err(err) = res { |
| 160 | + println!("{:?}", err) |
| 161 | + } |
| 162 | + |
| 163 | + Ok(()) |
| 164 | +} |
| 165 | + |
| 166 | +async fn notify(pool: &PgPool, s: &str) -> Result<(), sqlx::Error> { |
| 167 | + sqlx::query( |
| 168 | + r#" |
| 169 | +SELECT pg_notify(chan, payload) |
| 170 | +FROM (VALUES ('chan0', $1)) v(chan, payload) |
| 171 | +"#, |
| 172 | + ) |
| 173 | + .bind(s) |
| 174 | + .execute(pool) |
| 175 | + .await?; |
| 176 | + |
| 177 | + Ok(()) |
| 178 | +} |
0 commit comments