#![cfg_attr(windows, windows_subsystem = "windows")]
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
use ahk_cli::{json, report};
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") {
ahk_cli::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_raw, script_args) = the_script_path_and_args();
let script = script_raw.map(|path| the_full_path(&path));
let is_file = script.is_some();
let source = match script.as_deref() {
Some(path) => match read_script_file(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(if is_file { 0.0 } else { 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, script.as_deref(), &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 (source, tokens) = include_the_function_libraries(source, base, dialect);
let parsed = match tokens {
Some(tokens) => ahk::Parser::with_dialect(&source, tokens, dialect).parse_script(),
None => parse_with(&source, dialect),
};
let statements = match parsed {
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);
}
if !script_args.is_empty() {
runtime = runtime.with_args(script_args);
}
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_and_args() -> (Option<PathBuf>, Vec<String>) {
let mut args = std::env::args().skip(1);
let mut script = None;
let mut script_args = Vec::new();
for argument in args.by_ref() {
if !argument.starts_with('-') {
script = Some(PathBuf::from(argument));
break;
}
}
if script.is_some() {
script_args.extend(args);
}
(script, script_args)
}
fn the_full_path(path: &Path) -> PathBuf {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
match std::env::current_dir() {
Ok(directory) => directory.join(path),
Err(_) => path.to_path_buf(),
}
};
#[cfg(windows)]
let path = PathBuf::from(path.to_string_lossy().replace('/', "\\"));
path
}
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/v1/diff)\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,
file: Option<&Path>,
seen: &mut Vec<PathBuf>,
) -> Result<String, String> {
resolve_includes_at(source, base, file, seen, 0)
}
const MAX_INCLUDE_DEPTH: usize = 64;
fn resolve_includes_at(
source: &str,
base: &Path,
file: Option<&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 (ignore_missing, argument) = match argument.strip_prefix('*') {
Some(rest) => {
let end = rest
.find(|character: char| character.is_whitespace())
.unwrap_or(rest.len());
let (option, rest) = rest.split_at(end);
if !option.eq_ignore_ascii_case("i") {
return Err(format!("the include option \"*{option}\" is not one this tree speaks."));
}
(true, rest.trim())
}
None => (false, argument),
};
let argument = strip_include_comment(argument);
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 script_dir = absolute_dir(base);
let line_file = file
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_else(|| "*".to_string());
let path = if path.starts_with('<') && path.ends_with('>') {
match find_library(&path[1..path.len() - 1], &script_dir) {
Some(path) => path,
None if ignore_missing => {
out.push('\n');
continue;
}
None => return Err(format!("the include \"{path}\" cannot be found.")),
}
} else {
let expanded = expand_include_vars(path, &script_dir, &line_file);
base.join(expanded)
};
let path = match path.canonicalize() {
Ok(path) => path,
Err(_) if ignore_missing => {
out.push('\n');
continue;
}
Err(_) => return Err(format!("the include \"{path:?}\" cannot be found.")),
};
if !again && seen.contains(&path) {
out.push('\n');
continue;
}
let text = read_script_file(&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.clone());
}
out.push_str(&resolve_includes_at(&text, &directory, Some(&path), seen, depth + 1)?);
out.push('\n');
}
Ok(out)
}
fn read_script_file(path: &Path) -> Result<String, String> {
let bytes = std::fs::read(path).map_err(|error| error.to_string())?;
Ok(decode_script_bytes(&bytes))
}
fn decode_script_bytes(bytes: &[u8]) -> String {
if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
return String::from_utf8_lossy(rest).into_owned();
}
if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
return decode_utf16(rest, true);
}
if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
return decode_utf16(rest, false);
}
match std::str::from_utf8(bytes) {
Ok(text) => text.to_string(),
Err(_) => decode_ansi(bytes),
}
}
fn decode_utf16(bytes: &[u8], little: bool) -> String {
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|pair| {
if little {
u16::from_le_bytes([pair[0], pair[1]])
} else {
u16::from_be_bytes([pair[0], pair[1]])
}
})
.collect();
char::decode_utf16(units)
.map(|result| result.unwrap_or('\u{FFFD}'))
.collect()
}
fn decode_ansi(bytes: &[u8]) -> String {
#[cfg(windows)]
{
unsafe extern "system" {
fn GetACP() -> u32;
fn MultiByteToWideChar(
code_page: u32,
flags: u32,
text: *const u8,
text_len: i32,
wide: *mut u16,
wide_len: i32,
) -> i32;
}
unsafe {
let page = GetACP();
let len = bytes.len() as i32;
let needed = MultiByteToWideChar(page, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0);
if needed > 0 {
let mut wide = vec![0u16; needed as usize];
let written = MultiByteToWideChar(
page,
0,
bytes.as_ptr(),
len,
wide.as_mut_ptr(),
needed,
);
if written > 0 {
wide.truncate(written as usize);
return char::decode_utf16(wide)
.map(|result| result.unwrap_or('\u{FFFD}'))
.collect();
}
}
}
String::from_utf8_lossy(bytes).into_owned()
}
#[cfg(not(windows))]
{
const HIGH: [char; 32] = [
'\u{20AC}', '\u{0081}', '\u{201A}', '\u{0192}', '\u{201E}', '\u{2026}',
'\u{2020}', '\u{2021}', '\u{02C6}', '\u{2030}', '\u{0160}', '\u{2039}',
'\u{0152}', '\u{008D}', '\u{017D}', '\u{008F}', '\u{0090}', '\u{2018}',
'\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}',
'\u{02DC}', '\u{2122}', '\u{0161}', '\u{203A}', '\u{0153}', '\u{009D}',
'\u{017E}', '\u{0178}',
];
bytes
.iter()
.map(|&byte| {
if byte < 0x80 {
byte as char
} else if byte < 0xA0 {
HIGH[(byte - 0x80) as usize]
} else {
byte as char
}
})
.collect()
}
}
fn include_the_function_libraries(
mut source: String,
base: &Path,
dialect: &'static dyn Dialect,
) -> (String, Option<Vec<ahk::lexer::Token>>) {
let script_dir = absolute_dir(base);
let mut seen: Vec<PathBuf> = Vec::new();
for _ in 0..64 {
let (missing, lexed) = match ahk::lexer::tokenize_with(&source, dialect) {
Ok(lexed) => {
let (missing, lexed) =
ahk::parser::the_undefined_functions_of_the_tokens(&source, lexed, dialect);
(missing, Some(lexed))
}
Err(_) => (Vec::new(), None),
};
let mut added = false;
for name in missing {
let Some(path) = find_library(&name, &script_dir) else {
continue;
};
let canon = path.canonicalize().unwrap_or_else(|_| path.clone());
if seen.contains(&canon) {
continue;
}
seen.push(canon);
let Ok(text) = read_script_file(&path) else {
continue;
};
let directory = path.parent().unwrap_or(Path::new(".")).to_path_buf();
let resolved =
resolve_includes(&text, &directory, Some(&path), &mut Vec::new()).unwrap_or(text);
source.push('\n');
source.push_str(&resolved);
added = true;
}
if !added {
return (source, lexed);
}
}
(source, None)
}
fn absolute_dir(base: &Path) -> PathBuf {
if base.is_absolute() {
base.to_path_buf()
} else {
match std::env::current_dir() {
Ok(directory) => directory.join(base),
Err(_) => base.to_path_buf(),
}
}
}
fn strip_include_comment(argument: &str) -> &str {
let mut quoted = false;
let mut previous = ' ';
for (index, character) in argument.char_indices() {
if character == '"' {
quoted = !quoted;
} else if character == ';' && !quoted && previous.is_whitespace() {
return argument[..index].trim_end();
}
previous = character;
}
argument
}
fn expand_include_vars(path: &str, script_dir: &Path, line_file: &str) -> String {
let mut out = String::with_capacity(path.len());
let mut rest = path;
while let Some(start) = rest.find('%') {
out.push_str(&rest[..start]);
let after = &rest[start + 1..];
let Some(end) = after.find('%') else {
out.push('%');
rest = after;
continue;
};
let name = &after[..end];
let value = match name.to_ascii_lowercase().as_str() {
"a_scriptdir" => Some(script_dir.to_string_lossy().into_owned()),
"a_linefile" => Some(line_file.to_string()),
"a_appdata" => std::env::var("APPDATA").ok(),
"a_appdatacommon" => std::env::var("PROGRAMDATA").ok(),
"a_mydocuments" => std::env::var("USERPROFILE")
.ok()
.map(|home| format!("{home}\\Documents")),
_ => None,
};
match value {
Some(value) => out.push_str(&value),
None => {
out.push('%');
out.push_str(name);
out.push('%');
}
}
rest = &after[end + 1..];
}
out.push_str(rest);
out
}
fn find_library(name: &str, script_dir: &Path) -> Option<PathBuf> {
let mut roots = vec![script_dir.join("Lib")];
if let Ok(home) = std::env::var("USERPROFILE") {
roots.push(PathBuf::from(home).join("Documents\\AutoHotkey\\Lib"));
}
if let Ok(exe) = std::env::current_exe() {
if let Some(directory) = exe.parent() {
roots.push(directory.join("Lib"));
}
}
let (library, function) = match name.split_once('\\') {
Some((library, function)) => (library, Some(function)),
None => (name, None),
};
for root in roots {
if let Some(function) = function {
let path = root.join(library).join(format!("{function}.ahk"));
if path.is_file() {
return Some(path);
}
}
let path = root.join(format!("{library}.ahk"));
if path.is_file() {
return Some(path);
}
}
None
}
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();
}
}