//! The integrated terminal over a real TCP control connection: //! `terminal.create` answers at once, `terminalOutput` and `terminalExited` //! arrive as event lines from the pump, `terminal.input` reaches the shell. //! //! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits //! for the answer; the client answers like xterm.js does. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, clippy::panic )] use std::io::{BufRead, BufReader, Write}; use std::net::TcpStream; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use lutra_testkit::EngineBackend; use serde_json::{Value, json}; /// A client that answers requests and collects terminal events. struct Client { reader: BufReader, writer: TcpStream, output: String, exit: Option, answered: usize, next: u64, } impl Client { fn connect(addr: std::net::SocketAddr) -> Self { let stream = TcpStream::connect(addr).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(10))) .unwrap(); Self { writer: stream.try_clone().unwrap(), reader: BufReader::new(stream), output: String::new(), exit: None, answered: 0, next: 0, } } fn line(&mut self) -> Value { let mut line = String::new(); self.reader.read_line(&mut line).expect("line within 10 s"); serde_json::from_str(&line).unwrap() } fn event(&mut self, event: &Value) { match event["kind"].as_str() { Some("terminalOutput") => self.output.push_str(event["data"].as_str().unwrap()), Some("terminalExited") => self.exit = Some(event.clone()), _ => {} } } fn call(&mut self, method: &str, params: Value) -> Value { self.next += 1; let request = json!({"id": self.next, "method": method, "params": params}); self.writer .write_all(format!("{request}\n").as_bytes()) .unwrap(); loop { let line = self.line(); if let Some(event) = line.get("event") { let event = event.clone(); self.event(&event); } else { return line; } } } fn execute(&mut self, command: &str, params: Value) -> Value { self.call( "engine.execute", json!({"command": command, "params": params}), ) } /// Reads events until `done` holds or the terminal exited, answering /// cursor-position queries. fn until(&mut self, id: u64, done: impl Fn(&str) -> bool) { let deadline = Instant::now() + Duration::from_secs(30); while Instant::now() < deadline { while self.answered < self.output.matches("\x1b[6n").count() { let r = self.execute( "terminal.input", json!({"terminalId": id, "data": "\x1b[1;1R"}), ); assert!(r.get("error").is_none(), "{r}"); self.answered += 1; } if self.exit.is_some() || done(&self.output) { return; } let line = self.line(); if let Some(event) = line.get("event") { let event = event.clone(); self.event(&event); } } panic!("timed out; output so far: {:?}", self.output); } } /// Pumps the backend every 20 ms, like the desktop's pump thread, until /// dropped. struct Pump(Arc); impl Pump { fn start(backend: Arc) -> Self { let stop = Arc::new(AtomicBool::new(false)); let flag = stop.clone(); std::thread::spawn(move || { while !flag.load(Ordering::Relaxed) { backend.pump(); std::thread::sleep(Duration::from_millis(20)); } }); Self(stop) } } impl Drop for Pump { fn drop(&mut self) { self.0.store(true, Ordering::Relaxed); } } #[test] fn create_output_input_exit() { let dir = tempfile::tempdir().unwrap(); let backend = Arc::new(EngineBackend::new()); let server = lutra_control::start(0, backend.clone()).unwrap(); let mut client = Client::connect(server.local_addr()); client.call("events.subscribe", json!({})); let r = client.execute("project.open", json!({"path": dir.path()})); assert!(r["result"]["root"].is_string(), "{r}"); let _pump = Pump::start(backend.clone()); let shell = if cfg!(windows) { "cmd.exe" } else { "sh" }; let r = client.execute( "terminal.create", json!({"shell": shell, "cols": 100, "rows": 30}), ); let id = r["result"]["terminalId"].as_u64().expect("terminalId"); let r = client.execute( "terminal.input", json!({"terminalId": id, "data": "echo lutra-tcp\r"}), ); assert!(r.get("error").is_none(), "{r}"); client.until(id, |out| out.matches("lutra-tcp").count() >= 2); let r = client.execute( "terminal.resize", json!({"terminalId": id, "cols": 70, "rows": 20}), ); assert!(r.get("error").is_none(), "{r}"); client.execute( "terminal.input", json!({"terminalId": id, "data": "exit 4\r"}), ); client.until(id, |_| false); let exit = client.exit.clone().unwrap(); assert_eq!( exit, json!({"kind": "terminalExited", "terminalId": id, "code": 4}) ); }