use std::io::{self, Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::term;
const AWAY_LONG_ENOUGH: Duration = Duration::from_secs(3);
const WELCOME_BACK: Duration = Duration::from_millis(600);
#[derive(Default)]
struct Times {
away_since: Option<Instant>,
last_absence: Option<(Instant, Instant)>,
}
pub(crate) struct Focus {
focused: AtomicBool,
heard: AtomicBool,
times: Mutex<Times>,
typed: Mutex<Vec<u8>>,
}
impl Focus {
pub(crate) fn away(&self) -> bool {
self.heard.load(Ordering::Relaxed) && !self.focused.load(Ordering::Relaxed)
}
pub(crate) fn just_returned(&self, now: Instant) -> Option<(Instant, Instant)> {
let times = self.times.lock().unwrap_or_else(|e| e.into_inner());
times
.last_absence
.filter(|(_, back)| now.saturating_duration_since(*back) < WELCOME_BACK)
}
fn focus_changed(&self, focused: bool) {
self.heard.store(true, Ordering::Relaxed);
self.focused.store(focused, Ordering::Relaxed);
let mut times = self.times.lock().unwrap_or_else(|e| e.into_inner());
let now = Instant::now();
if !focused {
times.away_since.get_or_insert(now);
} else if let Some(left) = times.away_since.take() {
if now - left >= AWAY_LONG_ENOUGH {
times.last_absence = Some((left, now));
}
}
}
}
pub(crate) struct Watch {
pub(crate) focus: Arc<Focus>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
saved: String,
}
impl Watch {
pub(crate) fn start() -> Option<Watch> {
if !term::interactive() || std::env::var_os("TINSEL_NO_FOCUS").is_some() {
return None;
}
term::remember_terminal();
let saved = term::enter_cbreak().ok()?;
print!("\x1b[?1004h");
let _ = io::stdout().flush();
let focus = Arc::new(Focus {
focused: AtomicBool::new(true),
heard: AtomicBool::new(false),
times: Mutex::new(Times::default()),
typed: Mutex::new(Vec::new()),
});
let stop = Arc::new(AtomicBool::new(false));
let (f, s) = (focus.clone(), stop.clone());
let thread = thread::spawn(move || listen(&f, &s));
Some(Watch {
focus,
stop,
thread: Some(thread),
saved,
})
}
pub(crate) fn stop(&mut self) {
let Some(thread) = self.thread.take() else { return };
self.stop.store(true, Ordering::Relaxed);
let _ = thread.join();
print!("\x1b[?1004l");
let _ = io::stdout().flush();
let _ = term::stty(&[&self.saved]);
term::forget_terminal();
let typed = std::mem::take(&mut *self.focus.typed.lock().unwrap_or_else(|e| e.into_inner()));
term::push_back_input(&typed);
}
}
impl Drop for Watch {
fn drop(&mut self) {
self.stop();
}
}
fn listen(focus: &Focus, stop: &AtomicBool) {
let mut stdin = io::stdin().lock();
let mut pending: Vec<u8> = Vec::new();
while !stop.load(Ordering::Relaxed) {
let mut buf = [0u8; 64];
let n = stdin.read(&mut buf).unwrap_or(0);
for &b in &buf[..n] {
pending.push(b);
match pending.as_slice() {
b"\x1b[I" => {
focus.focus_changed(true);
pending.clear();
}
b"\x1b[O" => {
focus.focus_changed(false);
pending.clear();
}
b"\x1b" | b"\x1b[" => {}
other => {
focus
.typed
.lock()
.unwrap_or_else(|e| e.into_inner())
.extend_from_slice(other);
pending.clear();
}
}
}
}
if !pending.is_empty() {
focus
.typed
.lock()
.unwrap_or_else(|e| e.into_inner())
.extend_from_slice(&pending);
}
}