#![cfg_attr(windows, windows_subsystem = "windows")]
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
use ahk_cli::{json, report};
mod mcp;
use ahk::dialect::{self, Dialect};
use ahk::parse_with;
use ahk::runtime::Runtime;
use ahk::surface;
#[cfg(not(windows))]
use ahk_box::LabDesktop;
fn pid_file() -> PathBuf {
let base = match std::env::var_os("XDG_CACHE_HOME") {
Some(base) => PathBuf::from(base),
None => match std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
Some(home) => PathBuf::from(home).join(".cache"),
None => std::env::temp_dir(),
},
};
base.join("ahk").join("run.pid")
}
fn write_pid_file() {
let path = pid_file();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(&path, format!("{}\n", std::process::id()));
}
fn clear_pid_file() {
let _ = std::fs::remove_file(pid_file());
}
const STACK_BYTES: usize = 128 * 1024 * 1024;
const STACK_BUDGET: usize = 64 * 1024 * 1024;
fn main() -> std::process::ExitCode {
#[cfg(windows)]
let has_console = the_parent_console();
#[cfg(not(windows))]
let has_console = true;
if std::env::args()
.skip(1)
.any(|argument| argument == "--help" || argument == "-h")
{
print!("{}", the_help());
return std::process::ExitCode::from(0);
}
let dialect = the_dialect();
if std::env::args()
.skip(1)
.any(|argument| argument == "--surface")
{
let behaviour = std::env::args()
.skip(1)
.any(|argument| argument == "--behavior" || argument == "--behaviour");
if std::env::args()
.skip(1)
.any(|argument| argument == "--json")
{
print_surface_json(dialect, behaviour);
} else {
print_surface(dialect, behaviour);
}
return std::process::ExitCode::from(0);
}
if std::env::args().skip(1).any(|argument| argument == "--mcp") {
mcp::serve();
return std::process::ExitCode::from(0);
}
if std::env::args()
.skip(1)
.any(|argument| argument == "--associate" || argument == "--unassociate")
{
let register = std::env::args().skip(1).any(|a| a == "--associate");
return the_association(register);
}
let script = the_script_path().map(|path| the_full_path(&path));
let is_file = script.is_some();
let source = match script.as_deref() {
Some(path) => match std::fs::read_to_string(path) {
Ok(source) => source,
Err(error) => {
let error = format!("the script \"{path:?}\" cannot be read: {error}");
let report = report::the_failure_of_the_load(&error, 0, 0);
println!("{report}");
return std::process::ExitCode::from(2);
}
},
None => {
let mut source = String::new();
if let Err(error) = std::io::stdin().read_to_string(&mut source) {
eprintln!("cannot read the script: {error}");
return std::process::ExitCode::from(2);
}
source
}
};
let timeout = std::env::args()
.skip(1)
.find_map(|argument| {
argument
.strip_prefix("--timeout=")
.and_then(|value| value.parse::<f64>().ok())
})
.unwrap_or(60.0);
let wait = std::env::args()
.skip(1)
.any(|argument| argument == "--wait");
let base = script
.as_deref()
.and_then(Path::parent)
.unwrap_or(Path::new("."));
let source = match resolve_includes(&source, base, &mut Vec::new()) {
Ok(source) => source,
Err(error) => {
let report = report::the_failure_of_the_load(&error, 0, 0);
println!("{report}");
if is_file && !has_console { the_gui_error(&error.to_string()); }
return std::process::ExitCode::from(2);
}
};
let statements = match parse_with(&source, dialect) {
Ok(statements) => statements,
Err(error) => {
let report = report::the_failure_of_the_load(&error.message, error.line, error.column);
println!("{report}");
if is_file && !has_console { the_gui_error(&error.message); }
return std::process::ExitCode::from(2);
}
};
write_pid_file();
let _guard = PidGuard;
let script_path = script.map(|path| path.to_string_lossy().into_owned());
let the_file = script_path.clone();
let handle = std::thread::Builder::new()
.stack_size(STACK_BYTES)
.spawn(move || {
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
let x11 =
ahk_box::desktop_kind().eq_ignore_ascii_case("x11") && ahk_box::x11_available();
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
let mut x11_desktop = ahk_box::x11::X11Desktop::new();
#[cfg(windows)]
let mut windows_desktop = ahk_box::windows::WindowsDesktop::new();
#[cfg(not(windows))]
let mut lab_desktop = LabDesktop::new();
#[cfg(not(windows))]
lab_desktop.ensure_session_env();
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
let desktop: &mut dyn ahk::desktop::Desktop = if x11 {
&mut x11_desktop
} else {
&mut lab_desktop
};
#[cfg(windows)]
let desktop: &mut dyn ahk::desktop::Desktop = &mut windows_desktop;
#[cfg(not(any(target_os = "linux", target_os = "freebsd", windows)))]
let desktop: &mut dyn ahk::desktop::Desktop = &mut lab_desktop;
let mut runtime = Runtime::new(desktop, Duration::from_secs_f64(timeout))
.with_stack_budget(STACK_BUDGET)
.with_source(&source)
.with_dialect(dialect);
if wait {
runtime = runtime.with_resident(true);
}
if timeout <= 0.0 {
runtime = runtime.with_no_budget(true);
}
if let Some(path) = script_path.as_deref() {
runtime = runtime.with_script_path(path);
}
let report = runtime.run_and_stay(&statements);
#[cfg_attr(windows, allow(unused_mut))]
let mut notes = report.notes.clone();
#[cfg(not(windows))]
notes.extend(lab_desktop.notes().iter().cloned());
let payload = report::the_report(&report, ¬es);
(payload, report.ok, report.reload)
})
.expect("the thread of the run starts");
let (payload, ok, reload) = match handle.join() {
Ok(triple) => triple,
Err(_) => {
eprintln!("the run of the script died");
return std::process::ExitCode::from(1);
}
};
if reload {
if let Some(path) = the_file.as_deref() {
if let Err(reason) = the_script_runs_again(path) {
eprintln!("the script did not run again: {reason}");
return std::process::ExitCode::from(2);
}
}
}
println!("{payload}");
if !ok && is_file && !has_console {
let msg = the_error_of_payload(&payload).unwrap_or_else(|| "the script failed".to_string());
the_gui_error(&msg);
}
std::process::ExitCode::from(if ok { 0 } else { 1 })
}
fn the_script_runs_again(script: &str) -> Result<(), String> {
let program = std::env::current_exe()
.map_err(|error| format!("the machine did not say what this program is: {error}"))?;
let mut command = std::process::Command::new(program);
command.arg(script);
for argument in std::env::args().skip(1) {
if argument.starts_with('-') {
command.arg(argument);
}
}
command
.stdin(std::process::Stdio::null())
.spawn()
.map(|_| ())
.map_err(|error| format!("the machine did not start the script again: {error}"))
}
#[cfg(windows)]
mod ffi {
use std::ffi::c_void;
#[link(name = "kernel32")]
unsafe extern "system" {
pub fn AttachConsole(id: u32) -> i32;
pub fn GetStdHandle(h: u32) -> *mut c_void;
pub fn SetStdHandle(h: u32, v: *mut c_void) -> i32;
pub fn CreateFileW(
name: *const u16,
access: u32,
share: u32,
sec: *const c_void,
disp: u32,
flags: u32,
tmpl: *mut c_void,
) -> *mut c_void;
}
#[link(name = "shell32")]
unsafe extern "system" {
pub fn SHChangeNotify(event: i32, flags: u32, a: *const c_void, b: *const c_void);
}
#[link(name = "user32")]
unsafe extern "system" {
pub fn MessageBoxW(hwnd: *mut c_void, text: *const u16, caption: *const u16, kind: u32) -> i32;
}
}
#[cfg(windows)]
fn the_parent_console() -> bool {
const ATTACH_PARENT: u32 = u32::MAX;
const STD_IN: u32 = -10i32 as u32;
const STD_OUT: u32 = -12i32 as u32;
const STD_ERR: u32 = -11i32 as u32;
unsafe {
if ffi::AttachConsole(ATTACH_PARENT) == 0 {
return false; }
let conout = wide("CONOUT$");
let conin = wide("CONIN$");
let out = ffi::CreateFileW(conout.as_ptr(), 0x4000_0000, 3, std::ptr::null(), 3, 0, std::ptr::null_mut());
let inp = ffi::CreateFileW(conin.as_ptr(), 0x8000_0000, 3, std::ptr::null(), 3, 0, std::ptr::null_mut());
let invalid = -1isize as *mut std::ffi::c_void;
let h = ffi::GetStdHandle(STD_OUT);
if (h.is_null() || h == invalid) && !out.is_null() { ffi::SetStdHandle(STD_OUT, out); }
let h = ffi::GetStdHandle(STD_ERR);
if (h.is_null() || h == invalid) && !out.is_null() { ffi::SetStdHandle(STD_ERR, out); }
let h = ffi::GetStdHandle(STD_IN);
if (h.is_null() || h == invalid) && !inp.is_null() { ffi::SetStdHandle(STD_IN, inp); }
}
true
}
#[cfg(windows)]
fn the_gui_error(message: &str) {
unsafe {
ffi::MessageBoxW(std::ptr::null_mut(), wide(message).as_ptr(), wide("ahk").as_ptr(), 0x10);
}
}
#[cfg(not(windows))]
fn the_gui_error(_message: &str) {}
#[cfg(windows)]
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
fn the_error_of_payload(payload: &str) -> Option<String> {
let at = payload.find("\"error\":\"")? + "\"error\":\"".len();
let rest = &payload[at..];
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => break,
'\\' => match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('"') => out.push('"'),
Some('\\') => out.push('\\'),
Some(other) => out.push(other),
None => break,
},
other => out.push(other),
}
}
if out.is_empty() { None } else { Some(out) }
}
fn the_association(register: bool) -> std::process::ExitCode {
#[cfg(windows)]
{
let exe = std::env::current_exe()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| "ahk.exe".to_string());
let reg = |args: &[&str]| -> bool {
std::process::Command::new("reg")
.args(args)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
};
if register {
let open = format!("\"{}\" \"%1\"", exe);
let mut ok = reg(&["add", "HKCU\\Software\\Classes\\.ahk", "/ve", "/d", "ahk.Script", "/f"])
&& reg(&["add", "HKCU\\Software\\Classes\\ahk.Script", "/ve", "/d", "AutoHotkey Script (ahk rust)", "/f"])
&& reg(&["add", "HKCU\\Software\\Classes\\ahk.Script\\DefaultIcon", "/ve", "/d", &format!("{},0", exe), "/f"])
&& reg(&["add", "HKCU\\Software\\Classes\\ahk.Script\\shell\\open\\command", "/ve", "/d", &open, "/f"]);
for progid in ["ahk_auto_file", "AutoHotkeyScript"] {
ok &= reg(&["add", &format!("HKCU\\Software\\Classes\\{}\\shell\\open\\command", progid), "/ve", "/d", &open, "/f"]);
}
if ok {
let ux = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.ahk";
reg(&["delete", &format!("{}\\UserChoice", ux), "/f"]);
reg(&["delete", &format!("{}\\UserChoiceLatest", ux), "/f"]);
unsafe { ffi::SHChangeNotify(0x0800_0000, 0x1000, std::ptr::null(), std::ptr::null()); }
println!("associated .ahk with {} (open runs resident)", exe);
return std::process::ExitCode::from(0);
}
eprintln!("the association could not be written");
return std::process::ExitCode::from(1);
}
let ok = reg(&["delete", "HKCU\\Software\\Classes\\.ahk", "/f"])
& reg(&["delete", "HKCU\\Software\\Classes\\ahk.Script", "/f"]);
println!(".ahk association removed (the machine's handler returns)");
std::process::ExitCode::from(if ok { 0 } else { 1 })
}
#[cfg(not(windows))]
{
let _ = register;
eprintln!("the .ahk file association is a thing of Windows");
std::process::ExitCode::from(1)
}
}
fn the_script_path() -> Option<PathBuf> {
std::env::args()
.skip(1)
.find(|argument| !argument.starts_with('-'))
.map(PathBuf::from)
}
fn the_full_path(path: &Path) -> PathBuf {
if path.is_absolute() {
path.to_path_buf()
} else {
match std::env::current_dir() {
Ok(directory) => directory.join(path),
Err(_) => path.to_path_buf(),
}
}
}
fn the_help() -> String {
let mut text = String::new();
text.push_str("usage: ahk [flags] [script]\n");
text.push('\n');
text.push_str(
"The script comes from the standard input, and the report goes to the\n\
standard output. A path as the one argument that is not a flag names\n\
the file of the script: the file is read instead of the standard\n\
input, the includes are resolved against its directory, and the\n\
runtime knows the file.\n",
);
text.push('\n');
text.push_str("flags:\n");
text.push_str(" --dialect=v1 speak the v1 dialect instead of the v2\n");
text.push_str(" --timeout=N stop the script after N seconds (60 by default,\n");
text.push_str(" and 0 means that the run has no budget of time)\n");
text.push_str(" --wait keep the run alive after the statements of the script end\n");
text.push_str(" --associate register .ahk to open with this runner (Windows)\n");
text.push_str(" --unassociate remove the .ahk association (Windows)\n");
text.push_str(" --mcp serve a Model Context Protocol server on stdio (check/run/surface)\n");
text.push_str(" --surface print the names of the dialect and the state of each\n");
text.push_str(" --surface --json the same table, as JSON\n");
text.push_str(" --behavior with --surface, say whether each name works\n");
text.push_str(" --help print this usage\n");
text
}
fn the_dialect() -> &'static dyn Dialect {
let asked = std::env::args().skip(1).find_map(|argument| {
argument
.strip_prefix("--dialect=")
.map(|value| value.to_lowercase())
});
match asked.as_deref() {
Some("v1") => dialect::v1(),
Some("v2.1") | Some("v2_1") => dialect::v2_1(),
Some("ks") => dialect::ks(),
Some("ks20") | Some("ks2.0") => dialect::ks_20(),
Some("v2") | None => dialect::v2(),
Some(other) => {
eprintln!(
"the dialect {other} is not one this tree speaks: the tree speaks v1, v2, v2.1, ks and ks20."
);
std::process::exit(2);
}
}
}
fn print_surface(dialect: &'static dyn Dialect, behaviour: bool) {
let entries = surface::entries_of(dialect);
let mut out = String::new();
for entry in &entries {
out.push_str(&entry.line());
if behaviour {
if let Some(answer) = ahk::behavior::behaviour_of(dialect, &entry.full_name()) {
out.push_str("\tbehaviour=");
out.push_str(&answer);
}
}
out.push('\n');
}
out.push_str(&surface::summary_of(&entries, dialect).text());
out.push('\n');
print!("{out}");
}
fn print_surface_json(dialect: &'static dyn Dialect, behaviour: bool) {
let entries = surface::entries_of(dialect);
let summary = surface::summary_of(&entries, dialect);
let mut report = json::Object::new(64 * 1024);
report.text("dialect", summary.dialect);
report.number("total", summary.total as i64);
report.number("values", summary.values as i64);
report.number("refusals", summary.refusals as i64);
report.number("pending", summary.pending as i64);
report.field("entries", |out| {
out.push('[');
for (index, entry) in entries.iter().enumerate() {
if index > 0 {
out.push(',');
}
let mut row = json::Object::new(96);
row.text("name", entry.name);
row.text("kind", entry.kind.as_str());
row.text(
"state",
match entry.state {
surface::State::Value => "value",
surface::State::Refusal(_) => "refusal",
surface::State::Pending(_) => "pending",
},
);
if !entry.class.is_empty() {
row.text("class", entry.class);
}
if let surface::State::Refusal(reason) | surface::State::Pending(reason) = entry.state {
row.text("reason", reason);
}
if behaviour {
if let Some(answer) = ahk::behavior::behaviour_of(dialect, &entry.full_name()) {
row.text("behavior", &answer);
}
}
out.push_str(&row.finish());
}
out.push(']');
});
println!("{}", report.finish());
}
fn resolve_includes(source: &str, base: &Path, seen: &mut Vec<PathBuf>) -> Result<String, String> {
resolve_includes_at(source, base, seen, 0)
}
const MAX_INCLUDE_DEPTH: usize = 64;
fn resolve_includes_at(
source: &str,
base: &Path,
seen: &mut Vec<PathBuf>,
depth: usize,
) -> Result<String, String> {
if depth > MAX_INCLUDE_DEPTH {
return Err(format!(
"the includes nest more than {MAX_INCLUDE_DEPTH} deep: a file includes itself, or a group of them includes one another."
));
}
let mut out = String::with_capacity(source.len());
for line in source.lines() {
let Some((again, argument)) = the_include_of(line) else {
out.push_str(line);
out.push('\n');
continue;
};
let path = argument
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(argument)
.trim();
if path.is_empty() {
return Err("an include needs a path.".to_string());
}
let path = base.join(path);
let path = match path.canonicalize() {
Ok(path) => path,
Err(_) => return Err(format!("the include \"{path:?}\" cannot be found.")),
};
if !again && seen.contains(&path) {
out.push('\n');
continue;
}
let text = std::fs::read_to_string(&path)
.map_err(|error| format!("the include \"{path:?}\" cannot be read: {error}"))?;
let directory = path.parent().unwrap_or(Path::new(".")).to_path_buf();
if !seen.contains(&path) {
seen.push(path);
}
out.push_str(&resolve_includes_at(&text, &directory, seen, depth + 1)?);
out.push('\n');
}
Ok(out)
}
fn the_include_of(line: &str) -> Option<(bool, &str)> {
let trimmed = line.trim();
let rest = trimmed.strip_prefix('#')?;
let end = rest
.find(|character: char| character.is_whitespace())
.unwrap_or(rest.len());
let (name, argument) = rest.split_at(end);
let again = if name.eq_ignore_ascii_case("include") {
false
} else if name.eq_ignore_ascii_case("includeagain") {
true
} else {
return None;
};
Some((again, argument.trim()))
}
struct PidGuard;
impl Drop for PidGuard {
fn drop(&mut self) {
clear_pid_file();
}
}