use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use crossterm::event::{Event, KeyEventKind};
use super::{Model, Msg, Options};
use crate::Result;
use crate::tui::view;
const INPUT_POLL: Duration = Duration::from_millis(150);
const DRAIN_LIMIT: usize = 128;
pub fn run(opts: Options) -> Result<()> {
colored::control::set_override(false);
let (tx, rx) = std::sync::mpsc::channel::<Msg>();
let suspended = Arc::new(AtomicBool::new(false));
let mut model = Model::new(opts, tx.clone(), suspended.clone());
model.init();
let mut terminal = ratatui::init();
if let Ok(size) = terminal.size() {
model.width = size.width;
model.height = size.height;
}
spawn_input_thread(tx, suspended);
let res = loop {
model.ensure_cursor_visible();
if let Err(e) = terminal.draw(|f| view::draw(&model, f)) {
break Err(e.into());
}
let Ok(msg) = rx.recv() else { break Ok(()) };
model.handle(msg);
for queued in rx.try_iter().take(DRAIN_LIMIT) {
model.handle(queued);
}
if model.should_quit() {
break Ok(());
}
if let Some(path) = model.take_editor_request() {
open_editor(&mut terminal, &mut model, path);
}
};
ratatui::restore();
res
}
fn open_editor(terminal: &mut ratatui::DefaultTerminal, model: &mut Model, path: String) {
let Some((editor, suspended)) = model.editor_command(path) else {
model.status = "Could not work out which editor to use; check `code.editor`.".to_string();
return;
};
suspended.store(true, Ordering::SeqCst);
ratatui::restore();
let status = std::process::Command::new(&editor.program)
.envs(editor.envs)
.args(editor.args)
.status();
*terminal = ratatui::init();
suspended.store(false, Ordering::SeqCst);
model.status = match status {
Ok(exit) if exit.success() => String::new(),
Ok(exit) => format!("{} exited with {exit}", editor.program),
Err(e) => format!("Could not run {}: {e}", editor.program),
};
}
fn spawn_input_thread(tx: std::sync::mpsc::Sender<Msg>, suspended: Arc<AtomicBool>) {
std::thread::spawn(move || {
loop {
if suspended.load(Ordering::SeqCst) {
std::thread::sleep(INPUT_POLL);
continue;
}
match crossterm::event::poll(INPUT_POLL) {
Ok(false) => continue,
Err(_) => return,
Ok(true) => {}
}
let msg = match crossterm::event::read() {
Ok(Event::Key(k)) if k.kind != KeyEventKind::Release => Msg::Key(k),
Ok(Event::Resize(w, h)) => Msg::Resize(w, h),
Ok(_) => continue,
Err(_) => return,
};
if tx.send(msg).is_err() {
return;
}
}
});
}