1use std::io::Read;
11use std::path::{Path, PathBuf};
12use std::process::{Command, Stdio};
13use std::time::{Duration, Instant};
14
15const THE_V1: &str = "C:\\Program Files\\AutoHotkey\\v1.1.37.02\\AutoHotkeyU64.exe";
20
21const THE_SECONDS: u64 = 10;
23
24pub fn the_path_of_the_v1() -> String {
26 std::env::var("AHK_V1").unwrap_or_else(|_| THE_V1.to_string())
27}
28
29#[derive(Debug, Default)]
31pub struct TheAnswer {
32 pub output: String,
34 pub code: Option<i32>,
36 pub hung: bool,
38 pub failure: Option<String>,
40}
41
42impl TheAnswer {
43 pub fn the_errors(&self) -> Vec<String> {
54 self.output
55 .lines()
56 .filter(|line| line.contains("==>"))
57 .map(the_line_of_the_script)
58 .collect()
59 }
60}
61
62fn the_line_of_the_script(line: &str) -> String {
67 let Some(mark) = line.find(" : ==> ") else {
68 return line.to_string();
69 };
70 let (head, tail) = line.split_at(mark);
71 let Some(open) = head.rfind('(') else {
72 return line.to_string();
73 };
74 let Some(close) = head[open..].find(')') else {
75 return line.to_string();
76 };
77 let close = open + close;
78 let digits = &head[open + 1..close];
79 let Ok(number) = digits.trim().parse::<u64>() else {
80 return line.to_string();
81 };
82 if number == 0 {
83 return line.to_string();
84 }
85 format!("{}({}){}", &head[..open], number - 1, &head[close + 1..])
86 + tail
87}
88
89fn the_file_of_the_script(source: &str) -> std::io::Result<PathBuf> {
91 let dir = std::env::temp_dir().join(format!("ahk-mcp-{}", std::process::id()));
92 std::fs::create_dir_all(&dir)?;
93 let file = dir.join("probe.ahk");
94 std::fs::write(&file, format!("#ErrorStdOut\n{source}"))?;
98 Ok(file)
99}
100
101pub fn the_run_of_the_v1(source: &str) -> TheAnswer {
104 let path = the_path_of_the_v1();
105 if !Path::new(&path).exists() {
106 return TheAnswer {
107 failure: Some(format!(
108 "the binary of the v1 is not there: {path} (the path comes from AHK_V1)"
109 )),
110 ..TheAnswer::default()
111 };
112 }
113 let file = match the_file_of_the_script(source) {
114 Ok(file) => file,
115 Err(e) => {
116 return TheAnswer {
117 failure: Some(format!("the script was not written: {e}")),
118 ..TheAnswer::default()
119 }
120 }
121 };
122 let mut child = match Command::new(&path)
123 .arg("/ErrorStdOut")
124 .arg(&file)
125 .stdin(Stdio::null())
126 .stdout(Stdio::piped())
127 .stderr(Stdio::piped())
128 .spawn()
129 {
130 Ok(child) => child,
131 Err(e) => {
132 return TheAnswer {
133 failure: Some(format!("the v1 did not start: {e}")),
134 ..TheAnswer::default()
135 }
136 }
137 };
138 let deadline = Instant::now() + Duration::from_secs(THE_SECONDS);
139 let mut code = None;
140 let mut hung = false;
141 loop {
142 match child.try_wait() {
143 Ok(Some(status)) => {
144 code = status.code();
145 break;
146 }
147 Ok(None) => {
148 if Instant::now() >= deadline {
149 let _ = child.kill();
150 let _ = child.wait();
151 hung = true;
152 break;
153 }
154 std::thread::sleep(Duration::from_millis(20));
155 }
156 Err(e) => {
157 return TheAnswer {
158 failure: Some(format!("the v1 was not waited for: {e}")),
159 ..TheAnswer::default()
160 };
161 }
162 }
163 }
164 let mut output = String::new();
165 let mut errors = String::new();
166 if let Some(mut out) = child.stdout.take() {
167 let _ = out.read_to_string(&mut output);
168 }
169 if let Some(mut err) = child.stderr.take() {
170 let _ = err.read_to_string(&mut errors);
171 }
172 if !errors.is_empty() {
173 output.push_str(&errors);
174 }
175 TheAnswer {
176 output,
177 code,
178 hung,
179 failure: None,
180 }
181}