//! The outline over a real TCP control connection: `syntax.outline` after //! `file.open`, `outlineChanged` from the pump after the first parse and //! after a `buffer.edit` that changes the declarations. #![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; use lutra_testkit::EngineBackend; use serde_json::{Value, json}; /// A client that keeps responses and event lines apart. struct Client { reader: BufReader, writer: TcpStream, events: Vec, } 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), events: Vec::new(), } } 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 call(&mut self, request: Value) -> Value { self.writer .write_all(format!("{request}\n").as_bytes()) .unwrap(); loop { let line = self.line(); if line.get("event").is_some() { self.events.push(line["event"].clone()); } else { return line; } } } /// Waits for `outlineChanged` of buffer `id`. fn outline_changed(&mut self, id: u64) { let pending = std::mem::take(&mut self.events); if pending .iter() .any(|e| e["kind"] == "outlineChanged" && e["id"] == id) { return; } loop { let line = self.line(); if line["event"]["kind"] == "outlineChanged" && line["event"]["id"] == id { return; } } } } fn execute(command: &str, params: Value) -> Value { json!({"id": command, "method": "engine.execute", "params": {"command": command, "params": params}}) } /// 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); } } /// Names of the items, depth first. fn names(items: &Value) -> Vec { let mut out = Vec::new(); for item in items.as_array().unwrap() { out.push(item["name"].as_str().unwrap().to_string()); out.extend(names(&item["children"])); } out } #[test] fn outline_follows_the_buffer() { let dir = tempfile::tempdir().unwrap(); let source = "