use std::fs::OpenOptions;
use std::io::Write as _;
use std::os::fd::OwnedFd;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{mpsc, Arc};
use anyhow::{Context, Result};
use tam_daemon::pty::{self, Pty};
use tokio::sync::{broadcast, mpsc::UnboundedSender, watch};
use super::peek::Peek;
const TERM: &str = "xterm-256color";
const DEVICE_ATTRIBUTES: &[u8] = b"\x1b[?62;22c";
const WHEEL_LINES: usize = 3;
#[derive(Debug, PartialEq, Eq)]
pub enum Event {
Changed,
Clipboard(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Start {
End,
Line(u64),
}
pub struct Program {
pub argv: Vec<String>,
pub copies: PathBuf,
}
impl Program {
pub fn nvim() -> Self {
let socket = tam_proto::default_socket_path();
Self {
argv: vec!["nvim".into()],
copies: socket
.parent()
.map_or_else(std::env::temp_dir, Path::to_path_buf),
}
}
pub fn name(&self) -> &str {
self.argv.first().map_or("nvim", String::as_str)
}
}
pub struct Editor {
pub view: Peek,
size: (u16, u16),
running: Option<Running>,
}
struct Running {
pty: Pty,
keys: mpsc::Sender<Vec<u8>>,
_copy: Copy,
}
impl Editor {
pub fn open(
program: &Program,
agent: &str,
text: &str,
start: Start,
size: (u16, u16),
dir: &Path,
events: UnboundedSender<Event>,
) -> Result<Self> {
let copy = Copy::write(&program.copies, agent, text)?;
let (name, args) = program.argv.split_first().context("no editor")?;
let mut cmd = Command::new(name);
cmd.args(args)
.args(nvim_args(start, ©.path))
.env("TERM", TERM);
let pty = Pty::spawn(cmd, dir, &pty::Launch::default(), program.name())?;
let size = (size.0.max(1), size.1.max(1));
pty.resize(size.0, size.1);
let keys = key_writer(pty.master())?;
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
let (_, output) = pty.attach_output();
runtime.spawn(watch_output(
pty.screen_changes(),
output,
keys.clone(),
events,
));
}
let mut editor = Self {
view: Peek {
agent: Some(agent.to_string()),
..Peek::default()
},
size,
running: Some(Running {
pty,
keys,
_copy: copy,
}),
};
editor.refresh();
Ok(editor)
}
#[cfg(test)]
pub fn drawn(agent: &str, screen: &tam_proto::ScreenInfo) -> Self {
let mut view = Peek {
agent: Some(agent.to_string()),
..Peek::default()
};
view.set_screen(screen);
Self {
view,
size: (screen.cols, screen.rows),
running: None,
}
}
pub fn keys(&self, bytes: Vec<u8>) {
if let Some(running) = &self.running {
let _ = running.keys.send(bytes);
}
}
pub fn refresh(&mut self) {
if let Some(running) = &self.running {
self.view.set_screen(&running.pty.screen(None));
}
}
pub fn exited(&mut self) -> Option<i32> {
self.running.as_mut()?.pty.check_exited()
}
pub fn fit(&mut self) {
let (cols, rows) = self.view.room;
if cols == 0 || rows == 0 || (cols, rows) == self.size {
return;
}
self.size = (cols, rows);
if let Some(running) = &self.running {
running.pty.resize(cols, rows);
}
}
pub fn wheel(&self, up: bool, x: u16, y: u16) -> Option<Vec<u8>> {
let screen = self.view.screen.as_ref()?.screen();
Some(wheel(
screen,
up,
x.saturating_sub(self.view.area.x),
y.saturating_sub(self.view.area.y),
))
}
}
impl Drop for Running {
fn drop(&mut self) {
if self.pty.check_exited().is_none() {
self.pty.hang_up();
}
}
}
fn nvim_args(start: Start, file: &Path) -> Vec<std::ffi::OsString> {
let mut args: Vec<std::ffi::OsString> = [
"-M",
"-n",
"-i",
"NONE",
"-c",
"setlocal nonumber norelativenumber signcolumn=no foldcolumn=0",
]
.iter()
.map(Into::into)
.collect();
match start {
Start::End => args.extend(["+".into(), "-c".into(), "normal! zb".into()]),
Start::Line(line) => args.extend([
"-c".into(),
format!(
"call winrestview({{'topline': min([{line}, line('$')]), \
'lnum': min([{line} + min([&scrolloff, (winheight(0) - 1) / 2]), line('$')])}})"
)
.into(),
]),
}
args.extend(["--".into(), file.into()]);
args
}
fn wheel(screen: &vt100::Screen, up: bool, col: u16, row: u16) -> Vec<u8> {
if screen.mouse_protocol_mode() == vt100::MouseProtocolMode::None {
let key = if up { 0x19 } else { 0x05 };
return vec![key; WHEEL_LINES];
}
let button = if up { 64u16 } else { 65 };
let (col, row) = (col + 1, row + 1);
match screen.mouse_protocol_encoding() {
vt100::MouseProtocolEncoding::Sgr => format!("\x1b[<{button};{col};{row}M").into_bytes(),
_ => {
let byte = |n: u16| (32 + n).min(255) as u8;
vec![0x1b, b'[', b'M', byte(button), byte(col), byte(row)]
}
}
}
fn key_writer(master: Arc<OwnedFd>) -> Result<mpsc::Sender<Vec<u8>>> {
let (tx, rx) = mpsc::channel::<Vec<u8>>();
std::thread::Builder::new()
.name("editor-keys".into())
.spawn(move || {
for bytes in rx {
if !pty::write_pty(&master, &bytes) {
break;
}
}
})
.context("failed to start the editor's input")?;
Ok(tx)
}
async fn watch_output(
mut changes: watch::Receiver<()>,
mut output: broadcast::Receiver<Vec<u8>>,
keys: mpsc::Sender<Vec<u8>>,
events: UnboundedSender<Event>,
) {
let mut parser = watch_parser();
loop {
tokio::select! {
changed = changes.changed() => {
if changed.is_err() || events.send(Event::Changed).is_err() {
return;
}
}
bytes = output.recv() => match bytes {
Ok(bytes) => {
let fed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
parser.process(&bytes)
}));
if fed.is_err() {
parser = watch_parser();
}
let watch = parser.callbacks_mut();
if !watch.answers.is_empty() {
let _ = keys.send(std::mem::take(&mut watch.answers));
}
for set in watch.sets.drain(..) {
if events.send(Event::Clipboard(set)).is_err() {
return;
}
}
}
Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => return,
},
}
}
}
fn watch_parser() -> vt100::Parser<Watch> {
let (rows, cols) = (
std::num::NonZeroU16::new(24).expect("not zero"),
std::num::NonZeroU16::new(80).expect("not zero"),
);
vt100::Parser::new_with_callbacks(rows, cols, 0, Watch::default())
}
#[derive(Default)]
struct Watch {
answers: Vec<u8>,
sets: Vec<String>,
}
impl vt100::Callbacks for Watch {
fn copy_to_clipboard(&mut self, _: &mut vt100::Screen, ty: &[u8], data: &[u8]) {
self.sets.extend(clipboard_set(ty, data));
}
fn unhandled_csi(
&mut self,
_: &mut vt100::Screen,
i1: Option<u8>,
_i2: Option<u8>,
params: &[&[u16]],
c: char,
) {
match (i1, c, params) {
(None, 'n', [[5]]) => self.answers.extend_from_slice(b"\x1b[0n"),
(None, 'c', [] | [[0]]) => self.answers.extend_from_slice(DEVICE_ATTRIBUTES),
_ => {}
}
}
}
fn clipboard_set(ty: &[u8], data: &[u8]) -> Option<String> {
let ty_ok = ty.iter().all(|b| b"cpqs01234567".contains(b));
let base64 = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=');
if !ty_ok || data.is_empty() || !data.iter().all(base64) {
return None;
}
let ty = std::str::from_utf8(ty).ok()?;
let data = std::str::from_utf8(data).ok()?;
Some(format!("\x1b]52;{ty};{data}\x1b\\"))
}
struct Copy {
path: PathBuf,
}
impl Copy {
fn write(dir: &Path, agent: &str, text: &str) -> Result<Self> {
std::fs::create_dir_all(dir)
.with_context(|| format!("failed to create {}", dir.display()))?;
sweep(dir);
let pid = std::process::id();
let agent: String = agent
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
let path = dir.join(format!("{COPY_PREFIX}{pid}-{agent}"));
let _ = std::fs::remove_file(&path);
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&path)
.with_context(|| format!("failed to write {}", path.display()))?;
let copy = Self { path };
file.write_all(text.as_bytes())
.and_then(|()| file.write_all(b"\n"))
.with_context(|| format!("failed to write {}", copy.path.display()))?;
Ok(copy)
}
}
impl Drop for Copy {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
const COPY_PREFIX: &str = "copy-";
fn sweep(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix(COPY_PREFIX))
.and_then(|rest| rest.split('-').next())
.and_then(|pid| pid.parse::<i32>().ok())
else {
continue;
};
let gone = nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None)
== Err(nix::errno::Errno::ESRCH);
if gone {
let _ = std::fs::remove_file(entry.path());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::time::{Duration, Instant};
fn stand_in(dir: &Path, script: &str) -> Program {
Program {
argv: vec!["sh".into(), "-c".into(), script.into(), "nvim".into()],
copies: dir.to_path_buf(),
}
}
fn open(
program: &Program,
start: Start,
) -> (Editor, tokio::sync::mpsc::UnboundedReceiver<Event>) {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let editor = Editor::open(
program,
"m-0000abcd",
"line 1\nline 2",
start,
(100, 30),
&program.copies,
tx,
)
.unwrap();
(editor, rx)
}
fn text(editor: &Editor) -> String {
let screen = editor.view.screen.as_ref().unwrap().screen();
screen.contents()
}
fn wait_for(editor: &mut Editor, what: &str) -> String {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
editor.refresh();
let text = text(editor);
if text.contains(what) {
return text;
}
assert!(Instant::now() < deadline, "no {what:?} in {text:?}");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn nvim_reads_a_private_copy_at_the_line_the_pane_showed() {
let dir = tempfile::tempdir().unwrap();
let program = stand_in(dir.path(), "printf '<%s>\\n' \"$@\"; exec cat");
let (mut editor, _events) = open(&program, Start::Line(42));
let copies: Vec<PathBuf> = std::fs::read_dir(dir.path())
.unwrap()
.map(|e| e.unwrap().path())
.collect();
assert_eq!(copies.len(), 1, "{copies:?}");
let copy = &copies[0];
assert_eq!(std::fs::read_to_string(copy).unwrap(), "line 1\nline 2\n");
let mode = std::fs::metadata(copy).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
let text = wait_for(&mut editor, &format!("<-->\n<{}>", copy.display()));
for arg in [
"<-M>",
"<-n>",
"<-i>",
"<NONE>",
"<setlocal nonumber norelativenumber signcolumn=no foldcolumn=0>",
"'topline': min([42, line('$')])",
] {
assert!(text.contains(arg), "{arg}: {text}");
}
editor.keys(b"typed\r".to_vec());
wait_for(&mut editor, "typed\ntyped");
let cols = |editor: &Editor| editor.view.screen.as_ref().unwrap().screen().size().1.get();
assert_eq!(cols(&editor), 100);
editor.view.room = (90, 20);
editor.fit();
editor.refresh();
assert_eq!(cols(&editor), 90);
assert_eq!(editor.exited(), None);
drop(editor);
assert!(!copy.exists());
}
#[test]
fn a_live_pane_opens_at_the_end() {
let args = nvim_args(Start::End, Path::new("/run/tam/copy"));
let args: Vec<&str> = args.iter().map(|a| a.to_str().unwrap()).collect();
assert_eq!(args[6..], ["+", "-c", "normal! zb", "--", "/run/tam/copy"]);
}
#[test]
fn its_exit_is_seen_and_a_missing_program_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let (mut editor, _events) = open(&stand_in(dir.path(), "exit 3"), Start::End);
let deadline = Instant::now() + Duration::from_secs(10);
let status = loop {
if let Some(status) = editor.exited() {
break status;
}
assert!(Instant::now() < deadline, "not exited");
std::thread::sleep(Duration::from_millis(10));
};
assert_eq!(status, 3);
drop(editor);
let missing = Program {
argv: vec!["/nonexistent/tam-test-nvim".into()],
copies: dir.path().to_path_buf(),
};
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let err = Editor::open(&missing, "m-1", "x", Start::End, (80, 24), dir.path(), tx)
.err()
.expect("no such program");
assert!(format!("{err:#}").contains("tam-test-nvim"), "{err:#}");
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}
#[test]
fn copies_of_dashboards_gone_are_swept() {
let dir = tempfile::tempdir().unwrap();
let gone = dir.path().join(format!("{COPY_PREFIX}2147483646-m-1"));
let mine = dir
.path()
.join(format!("{COPY_PREFIX}{}-m-2", std::process::id()));
let other = dir.path().join("sock");
for path in [&gone, &mine, &other] {
std::fs::write(path, "x").unwrap();
}
let copy = Copy::write(dir.path(), "m-3", "text").unwrap();
assert!(!gone.exists());
assert!(mine.exists() && other.exists() && copy.path.exists());
}
#[tokio::test(flavor = "multi_thread")]
async fn clipboard_sets_are_passed_on_and_queries_answered() {
let dir = tempfile::tempdir().unwrap();
let script = "sleep 0.5; \
printf '\\033]52;c;aGVsbG8=\\007\\033]52;c;?\\007\\033]52;c;no base64!\\007'; \
stty -icanon -echo min 1; \
printf '\\033[5n'; a=$(head -c 4 | cat -v); \
printf '\\033[c'; b=$(head -c 9 | cat -v); \
echo \"status:$a\"; echo \"attributes:$b\"; exec cat";
let (mut editor, mut events) = open(&stand_in(dir.path(), script), Start::End);
let mut sets = Vec::new();
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
loop {
editor.refresh();
if text(&editor).contains("attributes:") {
break;
}
match tokio::time::timeout_at(deadline, events.recv()).await {
Ok(Some(Event::Clipboard(set))) => sets.push(set),
Ok(Some(Event::Changed)) => {}
_ => panic!("no answers: {:?}", text(&editor)),
}
}
while let Ok(event) = events.try_recv() {
if let Event::Clipboard(set) = event {
sets.push(set);
}
}
assert_eq!(sets, ["\x1b]52;c;aGVsbG8=\x1b\\"]);
let text = text(&editor);
assert!(text.contains("status:^[[0n"), "{text}");
assert!(text.contains("attributes:^[[?62;22c"), "{text}");
}
#[test]
fn wide_characters_do_not_trouble_the_watch() {
let mut parser = watch_parser();
let line = "漢字 🦀 é ".repeat(20);
parser.process(format!("{line}\x1b[5n\x1b]52;c;aGk=\x07{line}").as_bytes());
let watch = parser.callbacks_mut();
assert_eq!(watch.answers, b"\x1b[0n");
assert_eq!(watch.sets, ["\x1b]52;c;aGk=\x1b\\"]);
}
#[test]
fn the_wheel_is_the_mouse_s_where_it_asked_for_it_else_keys() {
let screen = |modes: &str| {
let mut parser = vt100::Parser::new(
std::num::NonZeroU16::new(24).unwrap(),
std::num::NonZeroU16::new(80).unwrap(),
0,
);
parser.process(modes.as_bytes());
parser
};
let sgr = screen("\x1b[?1002h\x1b[?1006h");
assert_eq!(wheel(sgr.screen(), true, 4, 9), b"\x1b[<64;5;10M");
assert_eq!(wheel(sgr.screen(), false, 0, 0), b"\x1b[<65;1;1M");
let x10 = screen("\x1b[?1000h");
assert_eq!(wheel(x10.screen(), true, 4, 9), b"\x1b[M\x60\x25\x2a");
let none = screen("");
assert_eq!(wheel(none.screen(), true, 4, 9), [0x19; 3]);
assert_eq!(wheel(none.screen(), false, 4, 9), [0x05; 3]);
}
#[test]
fn only_well_formed_clipboard_sets_are_passed_on() {
assert_eq!(
clipboard_set(b"c", b"aGk="),
Some("\x1b]52;c;aGk=\x1b\\".into())
);
assert_eq!(
clipboard_set(b"", b"aGk="),
Some("\x1b]52;;aGk=\x1b\\".into())
);
for (ty, data) in [
(&b"c"[..], &b""[..]),
(b"c", b"aGk\x1b[2J"),
(b"c\x1b", b"aGk="),
(b"x", b"aGk="),
] {
assert_eq!(clipboard_set(ty, data), None, "{ty:?} {data:?}");
}
}
}