//! Native input transport. Only opaque frame/mount identities cross to the VM worker. use serde::{Deserialize, Serialize}; use std::{ io::{Read, Write}, net::TcpStream, sync::mpsc::{SyncSender, sync_channel}, thread, time::Duration, }; use winit::event_loop::EventLoopProxy; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Input { pub session: u64, pub layout_version: u64, pub mount: u64, pub kind: String, } pub struct Client(SyncSender); impl Client { pub fn new(proxy: EventLoopProxy) -> anyhow::Result { let (sender, receiver) = sync_channel::(8); thread::Builder::new() .name("tessera-native-events".into()) .spawn(move || { for input in receiver { if let Err(error) = send(&input) { let _ = proxy.send_event(crate::app::AppEvent::RuntimeFailed { message: error.to_string(), }); } } })?; Ok(Self(sender)) } pub fn send(&self, input: Input) -> bool { self.0.try_send(input).is_ok() } } fn send(input: &Input) -> anyhow::Result<()> { let body = serde_json::to_string(input)?; let mut stream = TcpStream::connect_timeout(&crate::api::API_ADDRESS.parse()?, Duration::from_secs(2))?; stream.set_read_timeout(Some(Duration::from_secs(10)))?; stream.set_write_timeout(Some(Duration::from_secs(2)))?; write!( stream, "POST /v1/namespaces/app.main/events HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", body.len(), body )?; let mut response = String::new(); stream.take(32768).read_to_string(&mut response)?; let status = response.split_whitespace().nth(1).unwrap_or(""); // An old frame's event is deliberately discarded, with no automatic retry. if status == "409" { return Ok(()); } if status != "200" { let body = response .split_once("\r\n\r\n") .map(|(_, body)| body) .unwrap_or(&response); anyhow::bail!( "Native event failed: {}", body.chars().take(1024).collect::() ); } Ok(()) }