use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
pub fn start(port: u16) -> std::io::Result<u16> {
let listener = TcpListener::bind(("127.0.0.1", port))?;
let addr = listener.local_addr()?;
thread::spawn(move || {
for stream in listener.incoming().flatten() {
handle_client(stream);
}
});
Ok(addr.port())
}
fn read_line(stream: &mut TcpStream) -> std::io::Result<String> {
let mut buf = Vec::new();
let mut byte = [0u8; 1];
loop {
match stream.read(&mut byte)? {
0 => return Ok(String::from_utf8_lossy(&buf).into_owned()),
_ => {
if byte[0] == b'\n' {
return Ok(String::from_utf8_lossy(&buf).into_owned());
}
buf.push(byte[0]);
}
}
}
}
fn handle_client(mut stream: TcpStream) {
while let Some(command) = read_command(&mut stream) {
if command.is_empty() {
continue;
}
if command == "QUIT" {
break;
}
let response = dispatch_command(&command);
if write_response(&mut stream, &response).is_none() {
break;
}
}
}
fn dispatch_command(command: &str) -> String {
let (name, rest) = command.split_once(' ').unwrap_or((command, ""));
match name {
"SNAPSHOT" => super::read_latest_snapshot().unwrap_or_else(|| "null".to_owned()),
"PING" => "PONG".to_owned(),
"CLICK" => {
let key = rest.trim();
if !key.is_empty() {
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::Click {
key: key.to_owned(),
response_tx: tx,
});
match rx.recv_timeout(std::time::Duration::from_secs(1)) {
Ok(true) => "ok:true".to_owned(),
Ok(false) => "ok:false".to_owned(),
_ => "timeout".to_owned(),
}
} else {
"missing key".to_owned()
}
}
"SET_STATE" => {
let mut sp = rest.splitn(2, ' ');
let field = sp.next().unwrap_or("");
let raw_value = sp.next().unwrap_or("");
if field.is_empty() {
return "missing field".to_owned();
}
let value = match serde_json::from_str::<serde_json::Value>(raw_value) {
Ok(value) => value,
Err(_) => return "invalid json".to_owned(),
};
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::SetState {
field: field.to_owned(),
value,
response_tx: tx,
});
match rx.recv_timeout(std::time::Duration::from_secs(1)) {
Ok(true) => "ok:true".to_owned(),
Ok(false) => "ok:false".to_owned(),
_ => "timeout".to_owned(),
}
}
"SAVE_STATE" => {
super::send_command(super::DevToolsCommand::SaveState);
"ok".to_owned()
}
"RELOAD_TEMPLATE" => {
super::send_command(super::DevToolsCommand::ReloadTemplate);
"ok".to_owned()
}
"SAVE_ALL" => {
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::SaveAll { response_tx: tx });
match rx.recv_timeout(std::time::Duration::from_secs(1)) {
Ok(true) => "ok".to_owned(),
Ok(false) => "error".to_owned(),
_ => "timeout".to_owned(),
}
}
"TREE" => {
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::Tree { response_tx: tx });
match rx.recv_timeout(std::time::Duration::from_secs(2)) {
Ok(Some(s)) => s,
Ok(None) | Err(_) => "timeout".to_owned(),
}
}
"LAYOUT" => {
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::LayoutCmd { response_tx: tx });
match rx.recv_timeout(std::time::Duration::from_secs(2)) {
Ok(Some(s)) => s,
Ok(None) | Err(_) => "timeout".to_owned(),
}
}
"FIND" => {
let query = rest.trim();
if query.is_empty() {
return "missing query".to_owned();
}
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::Find {
query: query.to_owned(),
response_tx: tx,
});
match rx.recv_timeout(std::time::Duration::from_secs(2)) {
Ok(Some(s)) => s,
Ok(None) | Err(_) => "timeout".to_owned(),
}
}
"TYPE" => {
let mut sp = rest.splitn(2, ' ');
let key = sp.next().unwrap_or("").trim();
let text = sp.next().unwrap_or("");
if key.is_empty() {
return "missing key".to_owned();
}
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::Type {
key: key.to_owned(),
text: text.to_owned(),
response_tx: tx,
});
match rx.recv_timeout(std::time::Duration::from_secs(1)) {
Ok(Some(s)) => s,
Ok(None) | Err(_) => "timeout".to_owned(),
}
}
"KEY" => {
let mut sp = rest.splitn(2, ' ');
let key = sp.next().unwrap_or("").trim();
let keyname = sp.next().unwrap_or("").trim();
if key.is_empty() || keyname.is_empty() {
return "missing key or keyname".to_owned();
}
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::Key {
key: key.to_owned(),
keyname: keyname.to_owned(),
response_tx: tx,
});
match rx.recv_timeout(std::time::Duration::from_secs(1)) {
Ok(Some(s)) => s,
Ok(None) | Err(_) => "timeout".to_owned(),
}
}
"SHOT" => {
let (tx, rx) = std::sync::mpsc::channel();
super::send_command(super::DevToolsCommand::Shot { response_tx: tx });
match rx.recv_timeout(std::time::Duration::from_secs(2)) {
Ok(Some(s)) => s,
Ok(None) | Err(_) => "timeout".to_owned(),
}
}
_ => "unknown command".to_owned(),
}
}
fn read_command(stream: &mut TcpStream) -> Option<String> {
let line = read_line(stream).ok()?;
if line.is_empty() {
None
} else {
Some(line.trim().to_owned())
}
}
fn write_response(stream: &mut TcpStream, text: &str) -> Option<()> {
writeln!(stream, "{}", text).ok()?;
stream.flush().ok()?;
Some(())
}