agentmux_srv_core/backend/file_icons/
child.rs1use std::io::{BufRead, Write};
9
10use serde::Deserialize;
11
12use super::pool::ERR_NO_ICON;
13use super::request::IconRequest;
14
15#[derive(Deserialize)]
16struct ChildRequest {
17 kind: String,
18 ext: String,
19 px: u32,
20}
21
22#[cfg(windows)]
24fn render(req: &IconRequest) -> Result<Vec<u8>, &'static str> {
25 use super::shell_windows::{render, ShellError};
26 render(req).map_err(|e| match e {
27 ShellError::NoIcon => ERR_NO_ICON,
28 ShellError::Failed(why) => why,
29 })
30}
31
32#[cfg(not(windows))]
33fn render(_req: &IconRequest) -> Result<Vec<u8>, &'static str> {
34 Err("unsupported")
35}
36
37fn answer(line: &str) -> Vec<u8> {
40 let parsed = serde_json::from_str::<ChildRequest>(line)
41 .map_err(|_| "bad-request")
42 .and_then(|r| IconRequest::parse(Some(&r.kind), Some(&r.ext), Some(&r.px.to_string())).map_err(|_| "bad-request"))
43 .and_then(|req| render(&req));
44 match parsed {
45 Ok(png) => {
46 let mut out = format!("{{\"ok\":true,\"len\":{}}}\n", png.len()).into_bytes();
47 out.extend_from_slice(&png);
48 out
49 }
50 Err(err) => format!("{{\"ok\":false,\"err\":\"{err}\"}}\n").into_bytes(),
51 }
52}
53
54pub fn run_child() -> i32 {
56 #[cfg(windows)]
57 if let Err(e) = super::shell_windows::init() {
58 eprintln!("file icons helper: {e}");
59 return 1;
60 }
61 let stdin = std::io::stdin();
62 let mut stdout = std::io::stdout().lock();
63 for line in stdin.lock().lines() {
64 let Ok(line) = line else { return 0 };
65 if stdout.write_all(&answer(&line)).and_then(|()| stdout.flush()).is_err() {
66 return 0;
67 }
68 }
69 0
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 #[test]
77 fn a_malformed_or_out_of_range_request_is_refused_without_touching_the_system() {
78 for bad in [
79 "",
80 "not json",
81 r#"{"kind":"file","ext":"rs"}"#,
82 r#"{"kind":"file","ext":"..\x","px":16}"#,
83 r#"{"kind":"file","ext":"rs","px":17}"#,
84 r#"{"kind":"drive","ext":"","px":16}"#,
85 ] {
86 assert_eq!(answer(bad), b"{\"ok\":false,\"err\":\"bad-request\"}\n".to_vec(), "{bad}");
87 }
88 }
89
90 #[cfg(windows)]
91 #[test]
92 fn a_good_request_is_answered_with_a_header_line_and_that_many_png_bytes() {
93 let _turn = super::super::shell_windows::SHELL_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
94 super::super::shell_windows::init().unwrap();
95 let out = answer(r#"{"kind":"file","ext":"txt","px":16}"#);
96 let nl = out.iter().position(|b| *b == b'\n').unwrap();
97 let header: serde_json::Value = serde_json::from_slice(&out[..nl]).unwrap();
98 assert_eq!(header["ok"], true);
99 assert_eq!(header["len"].as_u64().unwrap() as usize, out.len() - nl - 1);
100 assert_eq!(&out[nl + 1..nl + 5], b"\x89PNG");
101 }
102}